1 const char parsers_rcs[] = "$Id: parsers.c,v 1.139 2008/09/04 08:13:58 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.139 2008/09/04 08:13:58 fabiankeil
48 * Prepare for critical sections on Windows by adding a
49 * layer of indirection before the pthread mutex functions.
51 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
52 * Remove FEATURE_COOKIE_JAR.
54 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
55 * Remove questionable micro-optimizations
56 * whose usefulness has never been measured.
58 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
59 * s@Insufficent@Insufficient@
61 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
62 * The whole point of strclean() is to modify the
63 * first parameter, so don't mark it immutable,
64 * even though the compiler lets us get away with it.
66 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
67 * As the wafer actions are gone, we can stop including encode.h.
69 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
70 * Ditch cast from (char **) to (char **).
72 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
73 * Streamline sed()'s prototype and declare
74 * the header parse and add structures static.
76 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
77 * Factor update_server_headers() out of sed(), ditch the
78 * first_run hack and make server_patterns_light static.
80 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
81 * Wrap memmove() calls in string_move()
82 * to document the purpose in one place.
84 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
85 * Normalize linear header white space.
87 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
88 * If a header is split across multiple lines,
89 * merge them to a single line before parsing them.
91 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
92 * Don't provide get_header() with the whole client state
93 * structure when it only needs access to csp->iob.
95 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
96 * Change content_filters_enabled()'s parameter from
97 * csp->action to action so it can be also used in the
98 * CGI code. Don't bother checking if there are filters
99 * loaded, as that's somewhat besides the point.
101 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
102 * Provide get_http_time() with the buffer size so it doesn't
103 * have to blindly assume that the buffer is big enough.
105 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
106 * Don't pass the whole csp structure to flush_socket()
107 * when it only needs a file descriptor and a buffer.
109 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
110 * Remove send-wafer and send-vanilla-wafer actions.
112 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
113 * Remove inspect-jpegs action.
115 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
116 * Let client_range() also handle Request-Range headers
117 * which apparently are still supported by many servers.
119 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
120 * Improve the warning messages that get logged if the action files
121 * "enable" filters but no filters of that type have been loaded.
123 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
124 * In server_content_type():
125 * - Don't require leading white space when detecting image content types.
126 * - Change '... not replaced ...' message to sound less crazy if the text
127 * type actually is 'text/plain'.
128 * - Mark the 'text/plain == binary data' assumption for removal.
129 * - Remove a bunch of trailing white space.
131 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
132 * Minor server_content_disposition() changes:
133 * - Don't regenerate the header name all lower-case.
134 * - Some white space fixes.
135 * - Remove useless log message in case of ENOMEM.
137 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
138 * Garbage-collect the code to add a X-Forwarded-For
139 * header as it seems to be mostly used by accident.
141 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
142 * Fix a crash on mingw32 with some Last Modified times in the future.
144 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
145 * Remove a "can't happen" error block which, over
146 * time, mutated into a "guaranteed to happen" block.
148 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
149 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
150 * - Use shiny new content_filters_enabled() in client_range().
152 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
153 * I forgot about Poland.
155 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
156 * Remove Range and If-Range headers if content filtering is enabled.
158 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
159 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
160 * client_cookie_adder() to make sure send-vanilla-wafer can be
161 * controlled through tags (and thus regression-tested).
163 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
164 * - Remove "scanning headers for" log message again.
165 * - Some more whitespace fixes.
167 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
168 * Refactor client_referrer() and add conditional-forge parameter.
170 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
171 * A bunch of whitespace fixes, pointy hat to me.
173 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
174 * Fix possible memory corruption in server_http, make sure it's not
175 * executed for ordinary server headers and mark some problems for later.
177 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
178 * Let content-type-overwrite{} honour force-text-mode again.
180 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
181 * - Add prototpyes for the header parsers and make them static.
182 * - Comment out client_accept_encoding_adder() which isn't used right now.
184 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
185 * Move the ACTION_FORCE_TEXT_MODE check out of
186 * server_content_type(). Signal other functions
187 * whether or not a content type has been declared.
188 * Part of the fix for BR#1750917.
190 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
191 * Change sed() to return a jb_err in preparation for forward-override{}.
193 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
194 * Adjust "X-Filter: No" to disable dedicated header filters.
196 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
197 * Streamline client_cookie_adder().
199 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
200 * Make sure filters with dynamic jobs actually use them.
202 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
203 * - Introduce dynamic pcrs jobs that can resolve variables.
204 * - Remove unnecessary update_action_bits_for_all_tags() call.
206 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
207 * - Make tagging based on tags set by earlier taggers
208 * of the same kind possible.
209 * - Log whether or not new tags cause action bits updates
210 * (in which case a matching tag-pattern section exists).
211 * - Log if the user tries to set a tag that is already set.
213 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
214 * Introduce tags as alternative way to specify which
215 * actions apply to a request. At the moment tags can be
216 * created based on client and server headers.
218 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
219 * Log a warning if the content is compressed, filtering is
220 * enabled and Privoxy was compiled without zlib support.
223 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
224 * - Fix warnings when compiled with glibc.
225 * - Don't use crumble() for cookie crunching.
226 * - Move cookie time parsing into parse_header_time().
227 * - Let parse_header_time() return a jb_err code
228 * instead of a pointer that can only be used to
229 * check for NULL anyway.
231 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
232 * - Add better protection against malicious gzip headers.
233 * - Stop logging the first hundred bytes of decompressed content.
234 * It looks like it's working and there is always debug 16.
235 * - Log the content size after decompression in decompress_iob()
236 * instead of pcrs_filter_response().
238 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
239 * - Use dedicated header filter actions instead of abusing "filter".
240 * Replace "filter-client-headers" and "filter-client-headers"
241 * with "server-header-filter" and "client-header-filter".
242 * - Remove filter_client_header() and filter_client_header(),
243 * filter_header() now checks the shiny new
244 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
246 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
247 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
248 * - Handle "Cookie:" and "Connection:" headers a bit smarter
249 * (don't crunch them just to recreate them later on).
250 * - Add another non-standard time format for the cookie
251 * expiration date detection.
252 * - Fix a valgrind warning.
254 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
255 * Improve cookie expiration date detection.
257 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
258 * Don't run server_content_length() the first time
259 * sed() parses server headers; only adjust the
260 * Content-Length header if the page was modified.
262 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
263 * Fix log messages regarding the cookie time format
264 * (cookie and request URL were mixed up).
266 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
267 * - Let decompress_iob()
268 * - not corrupt the content if decompression fails
269 * early. (the first byte(s) were lost).
270 * - use pointer arithmetics with defined outcome for
272 * - Use a different kludge to remember a failed decompression.
274 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
275 * Search for Max-Forwards headers case-insensitive,
276 * don't generate the "501 unsupported" message for invalid
277 * Max-Forwards values and don't increase negative ones.
279 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
280 * - Let server_set_cookie() check the expiration date
281 * of cookies and don't touch the ones that are already
282 * expired. Fixes problems with low quality web applications
283 * as described in BR 932612.
285 * - Adjust comment in client_max_forwards to reality;
286 * remove invalid Max-Forwards headers.
288 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
289 * Stop filter_header() from unintentionally removing
290 * empty header lines that were enlisted by the continue
293 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
294 * - Repeat the request URL before logging any headers.
295 * Makes reading the log easier in case of simultaneous requests.
296 * - If there are more than one Content-Type headers in one request,
297 * use the first one and remove the others.
298 * - Remove "newval" variable in server_content_type().
299 * It's only used once.
301 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
302 * Correct a cast, check inflateEnd() exit code
303 * to see if we have to, replace sprintf calls
306 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
307 * Integrate a modified version of Wil Mahan's
308 * zlib patch (PR #895531).
310 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
311 * Skip empty filter files in filter_header()
312 * but don't ignore the ones that come afterwards.
313 * Fixes BR 1619208, this time for real.
315 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
316 * Reverted parts of my last commit
317 * to keep error handling working.
319 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
320 * Fixed gcc43 conversion warnings.
322 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
323 * Bringing back the "useless" localtime() call
324 * I removed in revision 1.67. On some platforms
325 * it's necessary to prevent time zone offsets.
327 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
328 * Rebuild request URL in get_destination_from_headers()
329 * to make sure redirect{pcrs command} works as expected
330 * for intercepted requests.
332 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
333 * Added get_destination_from_headers().
335 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
336 * Make pthread mutex locking more generic. Instead of
337 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
338 * and use mutex locking unless there is an _r function
339 * available. Better safe than sorry.
341 * Fixes "./configure --disable-pthread" and should result
342 * in less threading-related problems on pthread-using platforms,
343 * but it still doesn't fix BR#1122404.
345 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
346 * The special header "X-Filter: No" now disables
347 * header filtering as well.
349 * Revision 1.73 2006/09/23 13:26:38 roro
350 * Replace TABs by spaces in source code.
352 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
353 * Don't print a log message every time filter_headers is
354 * entered or left. It only creates noise without any real
357 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
358 * Fix +hide-if-modified-since{-n}.
360 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
361 * Have hide-if-modified-since interpret the random
362 * range value as minutes instead of hours. Allows
363 * more fine-grained configuration.
365 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
366 * Always have parse_header_time return a pointer
367 * that actual makes sense, even though we currently
368 * only need it to detect problems.
370 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
371 * Added config option enable-remote-http-toggle
372 * to specify if Privoxy should recognize special
373 * headers (currently only X-Filter) to change its
374 * behaviour. Disabled by default.
376 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
377 * After filtering de-chunked instances, remove
378 * "Transfer-Encoding" header entirely instead of changing
379 * it to "Transfer-Encoding: identity", which is invalid.
380 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
382 * Don't use localtime in parse_header_time. An empty time struct
383 * is good enough, it gets overwritten by strptime anyway.
385 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
386 * Use gmtime_r if available, fallback to gmtime with mutex
387 * protection for MacOSX and use vanilla gmtime for the rest.
389 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
390 * Changed client_referrer to use the right type (size_t) for
391 * hostlenght and to shorten the temporary referrer string with
392 * '\0' instead of adding a useless line break.
394 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
395 * - Back to timegm() using GnuPG's replacement if necessary.
396 * Using mktime() and localtime() could add a on hour offset if
397 * the randomize factor was big enough to lead to a summer/wintertime
400 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
402 * - Moved randomization code into pick_from_range().
404 * - Changed parse_header_time definition.
405 * time_t isn't guaranteed to be signed and
406 * if it isn't, -1 isn't available as error code.
407 * Changed some variable types in client_if_modified_since()
408 * because of the same reason.
410 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
411 * OS/2 compilation compatibility fixups
413 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
414 * Changed include from strptime.c to strptime.h
416 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
417 * Split filter-headers{} into filter-client-headers{}
418 * and filter-server-headers{}.
419 * Added parse_header_time() to share some code.
420 * Replaced timegm() with mktime().
422 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
423 * Windows service integration
425 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
426 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
428 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
429 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
430 * with what was really the latest development (the v_3_0_branch branch)
432 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
433 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
435 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
436 * Add the ability to check jpeg images for invalid
437 * lengths of comment blocks. Defensive strategy
438 * against the exploit:
439 * Microsoft Security Bulletin MS04-028
440 * Buffer Overrun in JPEG Processing (GDI+) Could
441 * Allow Code Execution (833987)
442 * Enabled with +inspect-jpegs in actions files.
444 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
445 * Excluded text/plain objects from filtering. This fixes a
446 * couple of client-crashing, download corruption and
447 * Privoxy performance issues, whose root cause lies in
448 * web servers labelling content of unknown type as text/plain.
450 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
451 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
453 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
454 * Completing the previous change
456 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
457 * Added temporary workaround for bug in PHP < 4.2.3
459 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
460 * 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.
462 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
463 * Fix typo: supressed -> suppressed
465 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
466 * Improved cookie logging
468 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
469 * Added basic support for OPTIONS and TRACE HTTP methods:
470 * - New parser function client_max_forwards which decrements
471 * the Max-Forwards HTTP header field of OPTIONS and TRACE
472 * requests by one before forwarding
473 * - New parser function client_host which extracts the host
474 * and port information from the HTTP header field if the
475 * request URI was not absolute
476 * - Don't crumble and re-add the Host: header, but only generate
477 * and append if missing
479 * Revision 1.56 2002/05/12 15:34:22 jongfoster
480 * Fixing typo in a comment
482 * Revision 1.55 2002/05/08 16:01:07 oes
483 * Optimized add_to_iob:
484 * - Use realloc instead of malloc(), memcpy(), free()
485 * - Expand to powers of two if possible, to get
486 * O(log n) reallocs instead of O(n).
487 * - Moved check for buffer limit here from chat
488 * - Report failure via returncode
490 * Revision 1.54 2002/04/02 15:03:16 oes
491 * Tiny code cosmetics
493 * Revision 1.53 2002/03/26 22:29:55 swa
494 * we have a new homepage!
496 * Revision 1.52 2002/03/24 13:25:43 swa
497 * name change related issues
499 * Revision 1.51 2002/03/13 00:27:05 jongfoster
502 * Revision 1.50 2002/03/12 01:45:35 oes
503 * More verbose logging
505 * Revision 1.49 2002/03/09 20:03:52 jongfoster
506 * - Making various functions return int rather than size_t.
507 * (Undoing a recent change). Since size_t is unsigned on
508 * Windows, functions like read_socket that return -1 on
509 * error cannot return a size_t.
511 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
512 * crashes, and also frequently caused JB to jump to 100%
513 * CPU and stay there. (Because it thought it had just
514 * read ((unsigned)-1) == 4Gb of data...)
516 * - The signature of write_socket has changed, it now simply
517 * returns success=0/failure=nonzero.
519 * - Trying to get rid of a few warnings --with-debug on
520 * Windows, I've introduced a new type "jb_socket". This is
521 * used for the socket file descriptors. On Windows, this
522 * is SOCKET (a typedef for unsigned). Everywhere else, it's
523 * an int. The error value can't be -1 any more, so it's
524 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
525 * Windows it maps to the #define INVALID_SOCKET.)
527 * - The signature of bind_port has changed.
529 * Revision 1.48 2002/03/07 03:46:53 oes
530 * Fixed compiler warnings etc
532 * Revision 1.47 2002/02/20 23:15:13 jongfoster
533 * Parsing functions now handle out-of-memory gracefully by returning
536 * Revision 1.46 2002/01/17 21:03:47 jongfoster
537 * Moving all our URL and URL pattern parsing code to urlmatch.c.
539 * Revision 1.45 2002/01/09 14:33:03 oes
540 * Added support for localtime_r.
542 * Revision 1.44 2001/12/14 01:22:54 steudten
543 * Remove 'user:pass@' from 'proto://user:pass@host' for the
544 * new added header 'Host: ..'. (See Req ID 491818)
546 * Revision 1.43 2001/11/23 00:26:38 jongfoster
547 * Fixing two really stupid errors in my previous commit
549 * Revision 1.42 2001/11/22 21:59:30 jongfoster
550 * Adding code to handle +no-cookies-keep
552 * Revision 1.41 2001/11/05 23:43:05 steudten
553 * Add time+date to log files.
555 * Revision 1.40 2001/10/26 20:13:09 jongfoster
556 * ctype.h is needed in Windows, too.
558 * Revision 1.39 2001/10/26 17:40:04 oes
559 * Introduced get_header_value()
560 * Removed http->user_agent, csp->referrer and csp->accept_types
561 * Removed client_accept()
563 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
564 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
565 * threads to call select() simultaneously. So, it's time to do a real, live,
566 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
567 * (native). Both versions will work, but using __OS2__ offers multi-threading.
569 * Revision 1.37 2001/10/23 21:36:02 jongfoster
570 * Documenting sed()'s error behaviou (doc change only)
572 * Revision 1.36 2001/10/13 12:51:51 joergs
573 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
574 * force-load), instead crumble Host: and add it (again) in client_host_adder
575 * (in case we get a HTTP/1.0 request without Host: header and forward it to
576 * a HTTP/1.1 server/proxy).
578 * Revision 1.35 2001/10/09 22:39:21 jongfoster
579 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
582 * Revision 1.34 2001/10/07 18:50:55 oes
583 * Added server_content_encoding, renamed server_transfer_encoding
585 * Revision 1.33 2001/10/07 18:04:49 oes
586 * Changed server_http11 to server_http and its pattern to "HTTP".
587 * Additional functionality: it now saves the HTTP status into
588 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
590 * Revision 1.32 2001/10/07 15:43:28 oes
591 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
592 * client_te and client_accept_encoding_adder, triggered by the new
593 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
594 * changed to allow only identity and chunked, and the TE header is
595 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
597 * parse_http_request no longer does anything than parsing. The rewriting
598 * of http->cmd and version mangling are gone. It now also recognizes
599 * the put and delete methods and saves the url in http->url. Removed
602 * renamed content_type and content_length to have the server_ prefix
604 * server_content_type now only works if csp->content_type != CT_TABOO
606 * added server_transfer_encoding, which
607 * - Sets CT_TABOO to prohibit filtering if encoding compresses
608 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
609 * - Change from "chunked" to "identity" if body was chunked
610 * but has been de-chunked for filtering.
612 * added server_content_md5 which crunches any Content-MD5 headers
613 * if the body was modified.
615 * made server_http11 conditional on +downgrade action
617 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
619 * Revision 1.31 2001/10/05 14:25:02 oes
620 * Crumble Keep-Alive from Server
622 * Revision 1.30 2001/09/29 12:56:03 joergs
623 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
625 * Revision 1.29 2001/09/24 21:09:24 jongfoster
626 * Fixing 2 memory leaks that Guy spotted, where the paramater to
627 * enlist() was not being free()d.
629 * Revision 1.28 2001/09/22 16:32:28 jongfoster
630 * Removing unused #includes.
632 * Revision 1.27 2001/09/20 15:45:25 steudten
634 * add casting from size_t to int for printf()
635 * remove local variable shadow s2
637 * Revision 1.26 2001/09/16 17:05:14 jongfoster
638 * Removing unused #include showarg.h
640 * Revision 1.25 2001/09/16 13:21:27 jongfoster
641 * Changes to use new list functions.
643 * Revision 1.24 2001/09/13 23:05:50 jongfoster
644 * Changing the string paramater to the header parsers a "const".
646 * Revision 1.23 2001/09/12 18:08:19 steudten
648 * In parse_http_request() header rewriting miss the host value, so
649 * from http://www.mydomain.com the result was just " / " not
650 * http://www.mydomain.com/ in case we forward.
652 * Revision 1.22 2001/09/10 10:58:53 oes
653 * Silenced compiler warnings
655 * Revision 1.21 2001/07/31 14:46:00 oes
656 * - Persistant connections now suppressed
657 * - sed() no longer appends empty header to csp->headers
659 * Revision 1.20 2001/07/30 22:08:36 jongfoster
660 * Tidying up #defines:
661 * - All feature #defines are now of the form FEATURE_xxx
662 * - Permanently turned off WIN_GUI_EDIT
663 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
665 * Revision 1.19 2001/07/25 17:21:54 oes
666 * client_uagent now saves copy of User-Agent: header value
668 * Revision 1.18 2001/07/13 14:02:46 oes
669 * - Included fix to repair broken HTTP requests that
670 * don't contain a path, not even '/'.
671 * - Removed all #ifdef PCRS
672 * - content_type now always inspected and classified as
673 * text, gif or other.
674 * - formatting / comments
676 * Revision 1.17 2001/06/29 21:45:41 oes
677 * Indentation, CRLF->LF, Tab-> Space
679 * Revision 1.16 2001/06/29 13:32:42 oes
681 * - Adapted free_http_request
682 * - Removed logentry from cancelled commit
684 * Revision 1.15 2001/06/03 19:12:38 oes
685 * deleted const struct interceptors
687 * Revision 1.14 2001/06/01 18:49:17 jongfoster
688 * Replaced "list_share" with "list" - the tiny memory gain was not
689 * worth the extra complexity.
691 * Revision 1.13 2001/05/31 21:30:33 jongfoster
692 * Removed list code - it's now in list.[ch]
693 * Renamed "permission" to "action", and changed many features
694 * to use the actions file rather than the global config.
696 * Revision 1.12 2001/05/31 17:33:13 oes
700 * Revision 1.11 2001/05/29 20:11:19 joergs
701 * '/ * inside comment' warning removed.
703 * Revision 1.10 2001/05/29 09:50:24 jongfoster
704 * Unified blocklist/imagelist/permissionslist.
705 * File format is still under discussion, but the internal changes
708 * Also modified interceptor behaviour:
709 * - We now intercept all URLs beginning with one of the following
710 * prefixes (and *only* these prefixes):
712 * * http://ijbswa.sf.net/config/
713 * * http://ijbswa.sourceforge.net/config/
714 * - New interceptors "home page" - go to http://i.j.b/ to see it.
715 * - Internal changes so that intercepted and fast redirect pages
716 * are not replaced with an image.
717 * - Interceptors now have the option to send a binary page direct
718 * to the client. (i.e. ijb-send-banner uses this)
719 * - Implemented show-url-info interceptor. (Which is why I needed
720 * the above interceptors changes - a typical URL is
721 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
722 * The previous mechanism would not have intercepted that, and
723 * if it had been intercepted then it then it would have replaced
726 * Revision 1.9 2001/05/28 17:26:33 jongfoster
727 * Fixing segfault if last header was crunched.
728 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
729 * can use the cross-platform sprintf() instead.)
731 * Revision 1.8 2001/05/27 22:17:04 oes
733 * - re_process_buffer no longer writes the modified buffer
734 * to the client, which was very ugly. It now returns the
735 * buffer, which it is then written by chat.
737 * - content_length now adjusts the Content-Length: header
738 * for modified documents rather than crunch()ing it.
739 * (Length info in csp->content_length, which is 0 for
740 * unmodified documents)
742 * - For this to work, sed() is called twice when filtering.
744 * Revision 1.7 2001/05/27 13:19:06 oes
745 * Patched Joergs solution for the content-length in.
747 * Revision 1.6 2001/05/26 13:39:32 jongfoster
748 * Only crunches Content-Length header if applying RE filtering.
749 * Without this fix, Microsoft Windows Update wouldn't work.
751 * Revision 1.5 2001/05/26 00:28:36 jongfoster
752 * Automatic reloading of config file.
753 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
754 * Most of the global variables have been moved to a new
755 * struct configuration_spec, accessed through csp->config->globalname
756 * Most of the globals remaining are used by the Win32 GUI.
758 * Revision 1.4 2001/05/22 18:46:04 oes
760 * - Enabled filtering banners by size rather than URL
761 * by adding patterns that replace all standard banner
762 * sizes with the "Junkbuster" gif to the re_filterfile
764 * - Enabled filtering WebBugs by providing a pattern
765 * which kills all 1x1 images
767 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
768 * which is selected by the (nonstandard and therefore
769 * capital) letter 'U' in the option string.
770 * It causes the quantifiers to be ungreedy by default.
771 * Appending a ? turns back to greedy (!).
773 * - Added a new interceptor ijb-send-banner, which
774 * sends back the "Junkbuster" gif. Without imagelist or
775 * MSIE detection support, or if tinygif = 1, or the
776 * URL isn't recognized as an imageurl, a lame HTML
777 * explanation is sent instead.
779 * - Added new feature, which permits blocking remote
780 * script redirects and firing back a local redirect
782 * The feature is conditionally compiled, i.e. it
783 * can be disabled with --disable-fast-redirects,
784 * plus it must be activated by a "fast-redirects"
785 * line in the config file, has its own log level
786 * and of course wants to be displayed by show-proxy-args
787 * Note: Boy, all the #ifdefs in 1001 locations and
788 * all the fumbling with configure.in and acconfig.h
789 * were *way* more work than the feature itself :-(
791 * - Because a generic redirect template was needed for
792 * this, tinygif = 3 now uses the same.
794 * - Moved GIFs, and other static HTTP response templates
799 * - Removed some >400 CRs again (Jon, you really worked
802 * Revision 1.3 2001/05/20 01:21:20 jongfoster
803 * Version 2.9.4 checkin.
804 * - Merged popupfile and cookiefile, and added control over PCRS
805 * filtering, in new "permissionsfile".
806 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
807 * file error you now get a message box (in the Win32 GUI) rather
808 * than the program exiting with no explanation.
809 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
811 * - Removed tabs from "config"
812 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
813 * - Bumped up version number.
815 * Revision 1.2 2001/05/17 23:02:36 oes
816 * - Made referrer option accept 'L' as a substitute for '§'
818 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
819 * Initial import of version 2.9.3 source tree
822 *********************************************************************/
829 #include <sys/types.h>
839 * Convince GNU's libc to provide a strptime prototype.
842 #endif /*__GLIBC__ */
849 #if !defined(_WIN32) && !defined(__OS2__)
855 #ifdef FEATURE_PTHREAD
857 /* jcc.h is for mutex semapores only */
858 #endif /* def FEATURE_PTHREAD */
863 #include "jbsockets.h"
864 #include "miscutil.h"
869 #ifndef HAVE_STRPTIME
870 #include "strptime.h"
873 const char parsers_h_rcs[] = PARSERS_H_VERSION;
875 /* Fix a problem with Solaris. There should be no effect on other
877 * Solaris's isspace() is a macro which uses its argument directly
878 * as an array index. Therefore we need to make sure that high-bit
879 * characters generate +ve values, and ideally we also want to make
880 * the argument match the declared parameter type of "int".
882 * Why did they write a character function that can't take a simple
883 * "char" argument? Doh!
885 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
886 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
888 static char *get_header_line(struct iob *iob);
889 static jb_err scan_headers(struct client_state *csp);
890 static jb_err header_tagger(struct client_state *csp, char *header);
891 static jb_err parse_header_time(const char *header_time, time_t *result);
893 static jb_err crumble (struct client_state *csp, char **header);
894 static jb_err connection (struct client_state *csp, char **header);
895 static jb_err filter_header (struct client_state *csp, char **header);
896 static jb_err client_referrer (struct client_state *csp, char **header);
897 static jb_err client_uagent (struct client_state *csp, char **header);
898 static jb_err client_ua (struct client_state *csp, char **header);
899 static jb_err client_from (struct client_state *csp, char **header);
900 static jb_err client_send_cookie (struct client_state *csp, char **header);
901 static jb_err client_x_forwarded (struct client_state *csp, char **header);
902 static jb_err client_accept_encoding (struct client_state *csp, char **header);
903 static jb_err client_te (struct client_state *csp, char **header);
904 static jb_err client_max_forwards (struct client_state *csp, char **header);
905 static jb_err client_host (struct client_state *csp, char **header);
906 static jb_err client_if_modified_since (struct client_state *csp, char **header);
907 static jb_err client_accept_language (struct client_state *csp, char **header);
908 static jb_err client_if_none_match (struct client_state *csp, char **header);
909 static jb_err crunch_client_header (struct client_state *csp, char **header);
910 static jb_err client_x_filter (struct client_state *csp, char **header);
911 static jb_err client_range (struct client_state *csp, char **header);
912 static jb_err server_set_cookie (struct client_state *csp, char **header);
913 static jb_err server_content_type (struct client_state *csp, char **header);
914 static jb_err server_content_length (struct client_state *csp, char **header);
915 static jb_err server_content_md5 (struct client_state *csp, char **header);
916 static jb_err server_content_encoding (struct client_state *csp, char **header);
917 static jb_err server_transfer_coding (struct client_state *csp, char **header);
918 static jb_err server_http (struct client_state *csp, char **header);
919 static jb_err crunch_server_header (struct client_state *csp, char **header);
920 static jb_err server_last_modified (struct client_state *csp, char **header);
921 static jb_err server_content_disposition(struct client_state *csp, char **header);
923 static jb_err client_host_adder (struct client_state *csp);
924 static jb_err client_xtra_adder (struct client_state *csp);
925 static jb_err connection_close_adder (struct client_state *csp);
927 static jb_err create_forged_referrer(char **header, const char *hostport);
928 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
929 static jb_err handle_conditional_hide_referrer_parameter(char **header,
930 const char *host, const int parameter_conditional_block);
933 * List of functions to run on a list of headers.
937 /** The header prefix to match */
940 /** The length of the prefix to match */
943 /** The function to apply to this line */
944 const parser_func_ptr parser;
947 static const struct parsers client_patterns[] = {
948 { "referer:", 8, client_referrer },
949 { "user-agent:", 11, client_uagent },
950 { "ua-", 3, client_ua },
951 { "from:", 5, client_from },
952 { "cookie:", 7, client_send_cookie },
953 { "x-forwarded-for:", 16, client_x_forwarded },
954 { "Accept-Encoding:", 16, client_accept_encoding },
955 { "TE:", 3, client_te },
956 { "Host:", 5, client_host },
957 { "if-modified-since:", 18, client_if_modified_since },
958 { "Keep-Alive:", 11, crumble },
959 { "connection:", 11, connection },
960 { "proxy-connection:", 17, crumble },
961 { "max-forwards:", 13, client_max_forwards },
962 { "Accept-Language:", 16, client_accept_language },
963 { "if-none-match:", 14, client_if_none_match },
964 { "Range:", 6, client_range },
965 { "Request-Range:", 14, client_range },
966 { "If-Range:", 9, client_range },
967 { "X-Filter:", 9, client_x_filter },
968 { "*", 0, crunch_client_header },
969 { "*", 0, filter_header },
973 static const struct parsers server_patterns[] = {
974 { "HTTP/", 5, server_http },
975 { "set-cookie:", 11, server_set_cookie },
976 { "connection:", 11, connection },
977 { "Content-Type:", 13, server_content_type },
978 { "Content-MD5:", 12, server_content_md5 },
979 { "Content-Encoding:", 17, server_content_encoding },
980 { "Transfer-Encoding:", 18, server_transfer_coding },
981 { "Keep-Alive:", 11, crumble },
982 { "content-disposition:", 20, server_content_disposition },
983 { "Last-Modified:", 14, server_last_modified },
984 { "*", 0, crunch_server_header },
985 { "*", 0, filter_header },
989 static const add_header_func_ptr add_client_headers[] = {
992 /* Temporarily disabled: client_accept_encoding_adder, */
993 connection_close_adder,
997 static const add_header_func_ptr add_server_headers[] = {
998 connection_close_adder,
1002 /*********************************************************************
1004 * Function : flush_socket
1006 * Description : Write any pending "buffered" content.
1009 * 1 : fd = file descriptor of the socket to read
1010 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1012 * Returns : On success, the number of bytes written are returned (zero
1013 * indicates nothing was written). On error, -1 is returned,
1014 * and errno is set appropriately. If count is zero and the
1015 * file descriptor refers to a regular file, 0 will be
1016 * returned without causing any other effect. For a special
1017 * file, the results are not portable.
1019 *********************************************************************/
1020 int flush_socket(jb_socket fd, struct iob *iob)
1022 int len = iob->eod - iob->cur;
1029 if (write_socket(fd, iob->cur, (size_t)len))
1033 iob->eod = iob->cur = iob->buf;
1039 /*********************************************************************
1041 * Function : add_to_iob
1043 * Description : Add content to the buffered page, expanding the
1044 * buffer if necessary.
1047 * 1 : csp = Current client state (buffers, headers, etc...)
1048 * 2 : buf = holds the content to be added to the page
1049 * 3 : n = number of bytes to be added
1051 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1052 * or buffer limit reached.
1054 *********************************************************************/
1055 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1057 struct iob *iob = csp->iob;
1058 size_t used, offset, need, want;
1061 if (n <= 0) return JB_ERR_OK;
1063 used = (size_t)(iob->eod - iob->buf);
1064 offset = (size_t)(iob->cur - iob->buf);
1065 need = used + (size_t)n + 1;
1068 * If the buffer can't hold the new data, extend it first.
1069 * Use the next power of two if possible, else use the actual need.
1071 if (need > csp->config->buffer_limit)
1073 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1074 return JB_ERR_MEMORY;
1077 if (need > iob->size)
1079 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1081 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1085 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1091 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1092 return JB_ERR_MEMORY;
1095 /* Update the iob pointers */
1096 iob->cur = p + offset;
1097 iob->eod = p + used;
1101 /* copy the new data into the iob buffer */
1102 memcpy(iob->eod, buf, (size_t)n);
1104 /* point to the end of the data */
1107 /* null terminate == cheap insurance */
1116 /*********************************************************************
1118 * Function : decompress_iob
1120 * Description : Decompress buffered page, expanding the
1121 * buffer as necessary. csp->iob->cur
1122 * should point to the the beginning of the
1123 * compressed data block.
1126 * 1 : csp = Current client state (buffers, headers, etc...)
1128 * Returns : JB_ERR_OK on success,
1129 * JB_ERR_MEMORY if out-of-memory limit reached, and
1130 * JB_ERR_COMPRESS if error decompressing buffer.
1132 *********************************************************************/
1133 jb_err decompress_iob(struct client_state *csp)
1135 char *buf; /* new, uncompressed buffer */
1136 char *cur; /* Current iob position (to keep the original
1137 * iob->cur unmodified if we return early) */
1138 size_t bufsize; /* allocated size of the new buffer */
1139 size_t old_size; /* Content size before decompression */
1140 size_t skip_size; /* Number of bytes at the beginning of the iob
1141 that we should NOT decompress. */
1142 int status; /* return status of the inflate() call */
1143 z_stream zstr; /* used by calls to zlib */
1145 assert(csp->iob->cur - csp->iob->buf > 0);
1146 assert(csp->iob->eod - csp->iob->cur > 0);
1148 bufsize = csp->iob->size;
1149 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1150 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1152 cur = csp->iob->cur;
1157 * This is to protect the parsing of gzipped data,
1158 * but it should(?) be valid for deflated data also.
1160 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1161 return JB_ERR_COMPRESS;
1164 if (csp->content_type & CT_GZIP)
1167 * Our task is slightly complicated by the facts that data
1168 * compressed by gzip does not include a zlib header, and
1169 * that there is no easily accessible interface in zlib to
1170 * handle a gzip header. We strip off the gzip header by
1171 * hand, and later inform zlib not to expect a header.
1175 * Strip off the gzip header. Please see RFC 1952 for more
1176 * explanation of the appropriate fields.
1178 if ((*cur++ != (char)0x1f)
1179 || (*cur++ != (char)0x8b)
1180 || (*cur++ != Z_DEFLATED))
1182 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1183 return JB_ERR_COMPRESS;
1189 * XXX: These magic numbers should be replaced
1190 * with macros to give a better idea what they do.
1194 /* The gzip header has reserved bits set; bail out. */
1195 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1196 return JB_ERR_COMPRESS;
1200 /* Skip extra fields if necessary. */
1204 * Skip a given number of bytes, specified
1205 * as a 16-bit little-endian value.
1208 * XXX: This code used to be:
1210 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1212 * which I had to change into:
1214 * cur += *cur++ + (*cur++ << 8);
1216 * at which point gcc43 finally noticed that the value
1217 * of cur is undefined (it depends on which of the
1218 * summands is evaluated first).
1220 * I haven't come across a site where this
1221 * code is actually executed yet, but I hope
1225 skip_bytes = *cur++;
1226 skip_bytes = *cur++ << 8;
1228 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1231 * The number of bytes to skip should be positive
1232 * and we'd like to stay in the buffer.
1234 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1236 log_error(LOG_LEVEL_ERROR,
1237 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1239 return JB_ERR_COMPRESS;
1241 log_error(LOG_LEVEL_INFO,
1242 "Skipping %d bytes for gzip compression. Does this sound right?",
1247 /* Skip the filename if necessary. */
1250 /* A null-terminated string is supposed to follow. */
1251 while (*cur++ && (cur < csp->iob->eod));
1255 /* Skip the comment if necessary. */
1258 /* A null-terminated string is supposed to follow. */
1259 while (*cur++ && (cur < csp->iob->eod));
1262 /* Skip the CRC if necessary. */
1268 if (cur >= csp->iob->eod)
1271 * If the current position pointer reached or passed
1272 * the buffer end, we were obviously tricked to skip
1275 log_error(LOG_LEVEL_ERROR,
1276 "Malformed gzip header detected. Aborting decompression.");
1277 return JB_ERR_COMPRESS;
1281 else if (csp->content_type & CT_DEFLATE)
1284 * XXX: The debug level should be lowered
1285 * before the next stable release.
1287 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1289 * In theory (that is, according to RFC 1950), deflate-compressed
1290 * data should begin with a two-byte zlib header and have an
1291 * adler32 checksum at the end. It seems that in practice only
1292 * the raw compressed data is sent. Note that this means that
1293 * we are not RFC 1950-compliant here, but the advantage is that
1294 * this actually works. :)
1296 * We add a dummy null byte to tell zlib where the data ends,
1297 * and later inform it not to expect a header.
1299 * Fortunately, add_to_iob() has thoughtfully null-terminated
1300 * the buffer; we can just increment the end pointer to include
1307 log_error(LOG_LEVEL_ERROR,
1308 "Unable to determine compression format for decompression");
1309 return JB_ERR_COMPRESS;
1312 /* Set up the fields required by zlib. */
1313 zstr.next_in = (Bytef *)cur;
1314 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1315 zstr.zalloc = Z_NULL;
1316 zstr.zfree = Z_NULL;
1317 zstr.opaque = Z_NULL;
1320 * Passing -MAX_WBITS to inflateInit2 tells the library
1321 * that there is no zlib header.
1323 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1325 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1326 return JB_ERR_COMPRESS;
1330 * Next, we allocate new storage for the inflated data.
1331 * We don't modify the existing iob yet, so in case there
1332 * is error in decompression we can recover gracefully.
1334 buf = zalloc(bufsize);
1337 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1338 return JB_ERR_MEMORY;
1341 assert(bufsize >= skip_size);
1342 memcpy(buf, csp->iob->buf, skip_size);
1343 zstr.avail_out = bufsize - skip_size;
1344 zstr.next_out = (Bytef *)buf + skip_size;
1346 /* Try to decompress the whole stream in one shot. */
1347 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1349 /* We need to allocate more memory for the output buffer. */
1351 char *tmpbuf; /* used for realloc'ing the buffer */
1352 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1355 * If zlib wants more data then there's a problem, because
1356 * the complete compressed file should have been buffered.
1358 if (0 == zstr.avail_in)
1360 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1361 return JB_ERR_COMPRESS;
1365 * If we tried the limit and still didn't have enough
1366 * memory, just give up.
1368 if (bufsize == csp->config->buffer_limit)
1370 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1371 return JB_ERR_MEMORY;
1374 /* Try doubling the buffer size each time. */
1377 /* Don't exceed the buffer limit. */
1378 if (bufsize > csp->config->buffer_limit)
1380 bufsize = csp->config->buffer_limit;
1383 /* Try to allocate the new buffer. */
1384 tmpbuf = realloc(buf, bufsize);
1387 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1389 return JB_ERR_MEMORY;
1393 char *oldnext_out = (char *)zstr.next_out;
1396 * Update the fields for inflate() to use the new
1397 * buffer, which may be in a location different from
1400 zstr.avail_out += bufsize - oldbufsize;
1401 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1404 * Compare with an uglier method of calculating these values
1405 * that doesn't require the extra oldbufsize variable.
1407 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1408 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1409 assert(zstr.avail_out > 0);
1415 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1417 log_error(LOG_LEVEL_ERROR,
1418 "Inconsistent stream state after decompression: %s", zstr.msg);
1420 * XXX: Intentionally no return.
1422 * According to zlib.h, Z_STREAM_ERROR is returned
1423 * "if the stream state was inconsistent".
1425 * I assume in this case inflate()'s status
1426 * would also be something different than Z_STREAM_END
1427 * so this check should be redundant, but lets see.
1431 if (status != Z_STREAM_END)
1433 /* We failed to decompress the stream. */
1434 log_error(LOG_LEVEL_ERROR,
1435 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1436 return JB_ERR_COMPRESS;
1440 * Finally, we can actually update the iob, since the
1441 * decompression was successful. First, free the old
1444 freez(csp->iob->buf);
1446 /* Now, update the iob to use the new buffer. */
1447 csp->iob->buf = buf;
1448 csp->iob->cur = csp->iob->buf + skip_size;
1449 csp->iob->eod = (char *)zstr.next_out;
1450 csp->iob->size = bufsize;
1453 * Make sure the new uncompressed iob obeys some minimal
1454 * consistency conditions.
1456 if ((csp->iob->buf < csp->iob->cur)
1457 && (csp->iob->cur <= csp->iob->eod)
1458 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1460 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1463 log_error(LOG_LEVEL_RE_FILTER,
1464 "Decompression successful. Old size: %d, new size: %d.",
1465 old_size, new_size);
1469 /* zlib thinks this is OK, so lets do the same. */
1470 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1475 /* It seems that zlib did something weird. */
1476 log_error(LOG_LEVEL_ERROR,
1477 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1478 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1479 csp->iob->eod, csp->iob->buf + csp->iob->size);
1480 return JB_ERR_COMPRESS;
1486 #endif /* defined(FEATURE_ZLIB) */
1489 /*********************************************************************
1491 * Function : string_move
1493 * Description : memmove wrapper to move the last part of a string
1494 * towards the beginning, overwriting the part in
1495 * the middle. strlcpy() can't be used here as the
1499 * 1 : dst = Destination to overwrite
1500 * 2 : src = Source to move.
1504 *********************************************************************/
1505 static void string_move(char *dst, char *src)
1509 /* +1 to copy the terminating nul as well. */
1510 memmove(dst, src, strlen(src)+1);
1514 /*********************************************************************
1516 * Function : normalize_lws
1518 * Description : Reduces unquoted linear white space in headers
1519 * to a single space in accordance with RFC 2616 2.2.
1520 * This simplifies parsing and filtering later on.
1522 * XXX: Remove log messages before
1523 * the next stable release?
1526 * 1 : header = A header with linear white space to reduce.
1530 *********************************************************************/
1531 static void normalize_lws(char *header)
1537 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1541 while (ijb_isspace(*q))
1545 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1546 string_move(p+1, q);
1551 log_error(LOG_LEVEL_HEADER,
1552 "Converting tab to space in '%s'", header);
1557 char *end_of_token = strstr(p+1, "\"");
1559 if (NULL != end_of_token)
1561 /* Don't mess with quoted text. */
1566 log_error(LOG_LEVEL_HEADER,
1567 "Ignoring single quote in '%s'", header);
1573 p = strchr(header, ':');
1574 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1577 * There's still space before the colon.
1580 string_move(p-1, p);
1585 /*********************************************************************
1587 * Function : get_header
1589 * Description : This (odd) routine will parse the csp->iob
1590 * to get the next complete header.
1593 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1595 * Returns : Any one of the following:
1597 * 1) a pointer to a dynamically allocated string that contains a header line
1598 * 2) NULL indicating that the end of the header was reached
1599 * 3) "" indicating that the end of the iob was reached before finding
1600 * a complete header line.
1602 *********************************************************************/
1603 char *get_header(struct iob *iob)
1607 header = get_header_line(iob);
1609 if ((header == NULL) || (*header == '\0'))
1612 * No complete header read yet, tell the client.
1617 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1620 * Header spans multiple lines, append the next one.
1622 char *continued_header;
1624 continued_header = get_header_line(iob);
1625 if ((continued_header == NULL) || (*continued_header == '\0'))
1628 * No complete header read yet, return what we got.
1629 * XXX: Should "unread" header instead.
1631 log_error(LOG_LEVEL_INFO,
1632 "Failed to read a multi-line header properly: '%s'",
1637 if (JB_ERR_OK != string_join(&header, continued_header))
1639 log_error(LOG_LEVEL_FATAL,
1640 "Out of memory while appending multiple headers.");
1644 /* XXX: remove before next stable release. */
1645 log_error(LOG_LEVEL_HEADER,
1646 "Merged multiple header lines to: '%s'",
1651 normalize_lws(header);
1658 /*********************************************************************
1660 * Function : get_header_line
1662 * Description : This (odd) routine will parse the csp->iob
1663 * to get the next header line.
1666 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1668 * Returns : Any one of the following:
1670 * 1) a pointer to a dynamically allocated string that contains a header line
1671 * 2) NULL indicating that the end of the header was reached
1672 * 3) "" indicating that the end of the iob was reached before finding
1673 * a complete header line.
1675 *********************************************************************/
1676 static char *get_header_line(struct iob *iob)
1680 if ((iob->cur == NULL)
1681 || ((p = strchr(iob->cur, '\n')) == NULL))
1683 return(""); /* couldn't find a complete header */
1688 ret = strdup(iob->cur);
1691 /* FIXME No way to handle error properly */
1692 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1697 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1699 /* is this a blank line (i.e. the end of the header) ? */
1711 /*********************************************************************
1713 * Function : get_header_value
1715 * Description : Get the value of a given header from a chained list
1716 * of header lines or return NULL if no such header is
1717 * present in the list.
1720 * 1 : header_list = pointer to list
1721 * 2 : header_name = string with name of header to look for.
1722 * Trailing colon required, capitalization
1725 * Returns : NULL if not found, else value of header
1727 *********************************************************************/
1728 char *get_header_value(const struct list *header_list, const char *header_name)
1730 struct list_entry *cur_entry;
1734 assert(header_list);
1735 assert(header_name);
1736 length = strlen(header_name);
1738 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1742 if (!strncmpic(cur_entry->str, header_name, length))
1745 * Found: return pointer to start of value
1747 ret = cur_entry->str + length;
1748 while (*ret && ijb_isspace(*ret)) ret++;
1762 /*********************************************************************
1764 * Function : scan_headers
1766 * Description : Scans headers, applies tags and updates action bits.
1769 * 1 : csp = Current client state (buffers, headers, etc...)
1771 * Returns : JB_ERR_OK
1773 *********************************************************************/
1774 static jb_err scan_headers(struct client_state *csp)
1776 struct list_entry *h; /* Header */
1777 jb_err err = JB_ERR_OK;
1779 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1781 /* Header crunch()ed in previous run? -> ignore */
1782 if (h->str == NULL) continue;
1783 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1784 err = header_tagger(csp, h->str);
1791 /*********************************************************************
1795 * Description : add, delete or modify lines in the HTTP header streams.
1796 * On entry, it receives a linked list of headers space
1797 * that was allocated dynamically (both the list nodes
1798 * and the header contents).
1800 * As a side effect it frees the space used by the original
1804 * 1 : csp = Current client state (buffers, headers, etc...)
1805 * 2 : filter_server_headers = Boolean to switch between
1806 * server and header filtering.
1808 * Returns : JB_ERR_OK in case off success, or
1809 * JB_ERR_MEMORY on out-of-memory error.
1811 *********************************************************************/
1812 jb_err sed(struct client_state *csp, int filter_server_headers)
1814 /* XXX: use more descriptive names. */
1815 struct list_entry *p;
1816 const struct parsers *v;
1817 const add_header_func_ptr *f;
1818 jb_err err = JB_ERR_OK;
1820 if (filter_server_headers)
1822 v = server_patterns;
1823 f = add_server_headers;
1827 v = client_patterns;
1828 f = add_client_headers;
1833 while ((err == JB_ERR_OK) && (v->str != NULL))
1835 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1837 /* Header crunch()ed in previous run? -> ignore */
1838 if (p->str == NULL) continue;
1840 /* Does the current parser handle this header? */
1841 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1842 (v->len == CHECK_EVERY_HEADER_REMAINING))
1844 err = v->parser(csp, &(p->str));
1850 /* place additional headers on the csp->headers list */
1851 while ((err == JB_ERR_OK) && (*f))
1861 /*********************************************************************
1863 * Function : update_server_headers
1865 * Description : Updates server headers after the body has been modified.
1868 * 1 : csp = Current client state (buffers, headers, etc...)
1870 * Returns : JB_ERR_OK in case off success, or
1871 * JB_ERR_MEMORY on out-of-memory error.
1873 *********************************************************************/
1874 jb_err update_server_headers(struct client_state *csp)
1876 jb_err err = JB_ERR_OK;
1878 static const struct parsers server_patterns_light[] = {
1879 { "Content-Length:", 15, server_content_length },
1880 { "Transfer-Encoding:", 18, server_transfer_coding },
1882 { "Content-Encoding:", 17, server_content_encoding },
1883 #endif /* def FEATURE_ZLIB */
1887 if (strncmpic(csp->http->cmd, "HEAD", 4))
1889 const struct parsers *v;
1890 struct list_entry *p;
1892 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1894 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1896 /* Header crunch()ed in previous run? -> ignore */
1897 if (p->str == NULL) continue;
1899 /* Does the current parser handle this header? */
1900 if (strncmpic(p->str, v->str, v->len) == 0)
1902 err = v->parser(csp, (char **)&(p->str));
1912 /*********************************************************************
1914 * Function : header_tagger
1916 * Description : Executes all text substitutions from applying
1917 * tag actions and saves the result as tag.
1919 * XXX: Shares enough code with filter_header() and
1920 * pcrs_filter_response() to warrant some helper functions.
1923 * 1 : csp = Current client state (buffers, headers, etc...)
1924 * 2 : header = Header that is used as tagger input
1926 * Returns : JB_ERR_OK on success and always succeeds
1928 *********************************************************************/
1929 static jb_err header_tagger(struct client_state *csp, char *header)
1931 int wanted_filter_type;
1932 int multi_action_index;
1936 struct file_list *fl;
1937 struct re_filterfile_spec *b;
1938 struct list_entry *tag_name;
1940 int found_filters = 0;
1941 const size_t header_length = strlen(header);
1943 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1945 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1946 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1950 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1951 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1954 /* Check if there are any filters */
1955 for (i = 0; i < MAX_AF_FILES; i++)
1968 if (0 == found_filters)
1970 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1971 "tagging enabled, but no taggers available.");
1975 for (i = 0; i < MAX_AF_FILES; i++)
1978 if ((NULL == fl) || (NULL == fl->f))
1981 * Either there are no filter files
1982 * left, or this filter file just
1983 * contains no valid filters.
1985 * Continue to be sure we don't miss
1986 * valid filter files that are chained
1987 * after empty or invalid ones.
1992 /* For all filters, */
1993 for (b = fl->f; b; b = b->next)
1995 if (b->type != wanted_filter_type)
1997 /* skip the ones we don't care about, */
2000 /* leaving only taggers that could apply, of which we use the ones, */
2001 for (tag_name = csp->action->multi[multi_action_index]->first;
2002 NULL != tag_name; tag_name = tag_name->next)
2004 /* that do apply, and */
2005 if (strcmp(b->name, tag_name->str) == 0)
2007 char *modified_tag = NULL;
2009 size_t size = header_length;
2010 pcrs_job *joblist = b->joblist;
2012 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2014 if (NULL == joblist)
2016 log_error(LOG_LEVEL_RE_FILTER,
2017 "Tagger %s has empty joblist. Nothing to do.", b->name);
2021 /* execute their pcrs_joblist on the header. */
2022 for (job = joblist; NULL != job; job = job->next)
2024 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2028 /* Success, continue with the modified version. */
2037 /* Tagger doesn't match */
2040 /* Regex failure, log it but continue anyway. */
2041 log_error(LOG_LEVEL_ERROR,
2042 "Problems with tagger \'%s\' and header \'%s\': %s",
2043 b->name, *header, pcrs_strerror(hits));
2045 freez(modified_tag);
2049 if (b->dynamic) pcrs_free_joblist(joblist);
2051 /* If this tagger matched */
2057 * There is to technical limitation which makes
2058 * it impossible to use empty tags, but I assume
2059 * no one would do it intentionally.
2062 log_error(LOG_LEVEL_INFO,
2063 "Tagger \'%s\' created an empty tag. Ignored.",
2068 if (!list_contains_item(csp->tags, tag))
2070 if (JB_ERR_OK != enlist(csp->tags, tag))
2072 log_error(LOG_LEVEL_ERROR,
2073 "Insufficient memory to add tag \'%s\', "
2074 "based on tagger \'%s\' and header \'%s\'",
2075 tag, b->name, *header);
2079 char *action_message;
2081 * update the action bits right away, to make
2082 * tagging based on tags set by earlier taggers
2083 * of the same kind possible.
2085 if (update_action_bits_for_tag(csp, tag))
2087 action_message = "Action bits updated accordingly.";
2091 action_message = "No action bits update necessary.";
2094 log_error(LOG_LEVEL_HEADER,
2095 "Tagger \'%s\' added tag \'%s\'. %s",
2096 b->name, tag, action_message);
2101 /* XXX: Is this log-worthy? */
2102 log_error(LOG_LEVEL_HEADER,
2103 "Tagger \'%s\' didn't add tag \'%s\'. "
2104 "Tag already present", b->name, tag);
2107 } /* if the tagger matched */
2108 } /* if the tagger applies */
2109 } /* for every tagger that could apply */
2110 } /* for all filters */
2111 } /* for all filter files */
2116 /* here begins the family of parser functions that reformat header lines */
2118 /*********************************************************************
2120 * Function : filter_header
2122 * Description : Executes all text substitutions from all applying
2123 * +(server|client)-header-filter actions on the header.
2124 * Most of the code was copied from pcrs_filter_response,
2125 * including the rather short variable names
2128 * 1 : csp = Current client state (buffers, headers, etc...)
2129 * 2 : header = On input, pointer to header to modify.
2130 * On output, pointer to the modified header, or NULL
2131 * to remove the header. This function frees the
2132 * original string if necessary.
2134 * Returns : JB_ERR_OK on success and always succeeds
2136 *********************************************************************/
2137 static jb_err filter_header(struct client_state *csp, char **header)
2141 size_t size = strlen(*header);
2143 char *newheader = NULL;
2146 struct file_list *fl;
2147 struct re_filterfile_spec *b;
2148 struct list_entry *filtername;
2150 int i, found_filters = 0;
2151 int wanted_filter_type;
2152 int multi_action_index;
2154 if (csp->flags & CSP_FLAG_NO_FILTERING)
2159 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2161 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2162 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2166 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2167 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2171 * Need to check the set of re_filterfiles...
2173 for (i = 0; i < MAX_AF_FILES; i++)
2186 if (0 == found_filters)
2188 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2189 "header filtering enabled, but no matching filters available.");
2193 for (i = 0; i < MAX_AF_FILES; i++)
2196 if ((NULL == fl) || (NULL == fl->f))
2199 * Either there are no filter files
2200 * left, or this filter file just
2201 * contains no valid filters.
2203 * Continue to be sure we don't miss
2204 * valid filter files that are chained
2205 * after empty or invalid ones.
2210 * For all applying +filter actions, look if a filter by that
2211 * name exists and if yes, execute its pcrs_joblist on the
2214 for (b = fl->f; b; b = b->next)
2216 if (b->type != wanted_filter_type)
2218 /* Skip other filter types */
2222 for (filtername = csp->action->multi[multi_action_index]->first;
2223 filtername ; filtername = filtername->next)
2225 if (strcmp(b->name, filtername->str) == 0)
2227 int current_hits = 0;
2228 pcrs_job *joblist = b->joblist;
2230 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2232 if (NULL == joblist)
2234 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2238 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2239 *header, size, b->name);
2241 /* Apply all jobs from the joblist */
2242 for (job = joblist; NULL != job; job = job->next)
2244 matches = pcrs_execute(job, *header, size, &newheader, &size);
2247 current_hits += matches;
2248 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2250 *header = newheader;
2252 else if ( 0 == matches )
2254 /* Filter doesn't change header */
2260 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2261 *header, b->name, pcrs_strerror(matches));
2262 if (newheader != NULL)
2264 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2270 if (b->dynamic) pcrs_free_joblist(joblist);
2272 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2273 hits += current_hits;
2280 * Additionally checking for hits is important because if
2281 * the continue hack is triggered, server headers can
2282 * arrive empty to separate multiple heads from each other.
2284 if ((0 == size) && hits)
2286 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2294 /*********************************************************************
2296 * Function : connection
2298 * Description : Makes sure that the value of the Connection: header
2299 * is "close" and signals connection_close_adder
2303 * 1 : csp = Current client state (buffers, headers, etc...)
2304 * 2 : header = On input, pointer to header to modify.
2305 * On output, pointer to the modified header, or NULL
2306 * to remove the header. This function frees the
2307 * original string if necessary.
2309 * Returns : JB_ERR_OK on success, or
2310 * JB_ERR_MEMORY on out-of-memory error.
2312 *********************************************************************/
2313 static jb_err connection(struct client_state *csp, char **header)
2315 char *old_header = *header;
2317 /* Do we have a 'Connection: close' header? */
2318 if (strcmpic(*header, "Connection: close"))
2320 /* No, create one */
2321 *header = strdup("Connection: close");
2324 return JB_ERR_MEMORY;
2326 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2330 /* Signal connection_close_adder() to return early. */
2331 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2333 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2337 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2344 /*********************************************************************
2346 * Function : crumble
2348 * Description : This is called if a header matches a pattern to "crunch"
2351 * 1 : csp = Current client state (buffers, headers, etc...)
2352 * 2 : header = On input, pointer to header to modify.
2353 * On output, pointer to the modified header, or NULL
2354 * to remove the header. This function frees the
2355 * original string if necessary.
2357 * Returns : JB_ERR_OK on success, or
2358 * JB_ERR_MEMORY on out-of-memory error.
2360 *********************************************************************/
2361 static jb_err crumble(struct client_state *csp, char **header)
2363 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2369 /*********************************************************************
2371 * Function : crunch_server_header
2373 * Description : Crunch server header if it matches a string supplied by the
2374 * user. Called from `sed'.
2377 * 1 : csp = Current client state (buffers, headers, etc...)
2378 * 2 : header = On input, pointer to header to modify.
2379 * On output, pointer to the modified header, or NULL
2380 * to remove the header. This function frees the
2381 * original string if necessary.
2383 * Returns : JB_ERR_OK on success and always succeeds
2385 *********************************************************************/
2386 static jb_err crunch_server_header(struct client_state *csp, char **header)
2388 const char *crunch_pattern;
2390 /* Do we feel like crunching? */
2391 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2393 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2395 /* Is the current header the lucky one? */
2396 if (strstr(*header, crunch_pattern))
2398 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2407 /*********************************************************************
2409 * Function : server_content_type
2411 * Description : Set the content-type for filterable types (text/.*,
2412 * .*xml.*, javascript and image/gif) unless filtering has been
2413 * forbidden (CT_TABOO) while parsing earlier headers.
2414 * NOTE: Since text/plain is commonly used by web servers
2415 * for files whose correct type is unknown, we don't
2416 * set CT_TEXT for it.
2419 * 1 : csp = Current client state (buffers, headers, etc...)
2420 * 2 : header = On input, pointer to header to modify.
2421 * On output, pointer to the modified header, or NULL
2422 * to remove the header. This function frees the
2423 * original string if necessary.
2425 * Returns : JB_ERR_OK on success, or
2426 * JB_ERR_MEMORY on out-of-memory error.
2428 *********************************************************************/
2429 static jb_err server_content_type(struct client_state *csp, char **header)
2431 /* Remove header if it isn't the first Content-Type header */
2432 if ((csp->content_type & CT_DECLARED))
2435 * Another, slightly slower, way to see if
2436 * we already parsed another Content-Type header.
2438 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2440 log_error(LOG_LEVEL_ERROR,
2441 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2449 * Signal that the Content-Type has been set.
2451 csp->content_type |= CT_DECLARED;
2453 if (!(csp->content_type & CT_TABOO))
2456 * XXX: The assumption that text/plain is a sign of
2457 * binary data seems to be somewhat unreasonable nowadays
2458 * and should be dropped after 3.0.8 is out.
2460 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2461 || strstr(*header, "xml")
2462 || strstr(*header, "application/x-javascript"))
2464 csp->content_type |= CT_TEXT;
2466 else if (strstr(*header, "image/gif"))
2468 csp->content_type |= CT_GIF;
2473 * Are we messing with the content type?
2475 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2478 * Make sure the user doesn't accidently
2479 * change the content type of binary documents.
2481 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2484 *header = strdup("Content-Type: ");
2485 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2489 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2490 return JB_ERR_MEMORY;
2492 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2496 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2497 "It doesn't look like a content type that should be filtered. "
2498 "Enable force-text-mode if you know what you're doing.", *header);
2506 /*********************************************************************
2508 * Function : server_transfer_coding
2510 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2511 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2512 * - Remove header if body was chunked but has been
2513 * de-chunked for filtering.
2516 * 1 : csp = Current client state (buffers, headers, etc...)
2517 * 2 : header = On input, pointer to header to modify.
2518 * On output, pointer to the modified header, or NULL
2519 * to remove the header. This function frees the
2520 * original string if necessary.
2522 * Returns : JB_ERR_OK on success, or
2523 * JB_ERR_MEMORY on out-of-memory error.
2525 *********************************************************************/
2526 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2529 * Turn off pcrs and gif filtering if body compressed
2531 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2535 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2537 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2538 csp->http->cmd, *header);
2539 #endif /* def FEATURE_ZLIB */
2540 csp->content_type = CT_TABOO;
2544 * Raise flag if body chunked
2546 if (strstr(*header, "chunked"))
2548 csp->flags |= CSP_FLAG_CHUNKED;
2551 * If the body was modified, it has been de-chunked first
2552 * and the header must be removed.
2554 * FIXME: If there is more than one transfer encoding,
2555 * only the "chunked" part should be removed here.
2557 if (csp->flags & CSP_FLAG_MODIFIED)
2559 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2568 /*********************************************************************
2570 * Function : server_content_encoding
2572 * Description : This function is run twice for each request,
2573 * unless FEATURE_ZLIB and filtering are disabled.
2575 * The first run is used to check if the content
2576 * is compressed, if FEATURE_ZLIB is disabled
2577 * filtering is then disabled as well, if FEATURE_ZLIB
2578 * is enabled the content is marked for decompression.
2580 * The second run is used to remove the Content-Encoding
2581 * header if the decompression was successful.
2584 * 1 : csp = Current client state (buffers, headers, etc...)
2585 * 2 : header = On input, pointer to header to modify.
2586 * On output, pointer to the modified header, or NULL
2587 * to remove the header. This function frees the
2588 * original string if necessary.
2590 * Returns : JB_ERR_OK on success, or
2591 * JB_ERR_MEMORY on out-of-memory error.
2593 *********************************************************************/
2594 static jb_err server_content_encoding(struct client_state *csp, char **header)
2597 if ((csp->flags & CSP_FLAG_MODIFIED)
2598 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2601 * We successfully decompressed the content,
2602 * and have to clean the header now, so the
2603 * client no longer expects compressed data..
2605 * XXX: There is a difference between cleaning
2606 * and removing it completely.
2608 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2611 else if (strstr(*header, "gzip"))
2613 /* Mark for gzip decompression */
2614 csp->content_type |= CT_GZIP;
2616 else if (strstr(*header, "deflate"))
2618 /* Mark for zlib decompression */
2619 csp->content_type |= CT_DEFLATE;
2621 else if (strstr(*header, "compress"))
2624 * We can't decompress this; therefore we can't filter
2627 csp->content_type |= CT_TABOO;
2629 #else /* !defined(FEATURE_ZLIB) */
2630 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2633 * Body is compressed, turn off pcrs and gif filtering.
2635 csp->content_type |= CT_TABOO;
2638 * Log a warning if the user expects the content to be filtered.
2640 if ((csp->rlist != NULL) &&
2641 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2643 log_error(LOG_LEVEL_INFO,
2644 "Compressed content detected, content filtering disabled. "
2645 "Consider recompiling Privoxy with zlib support or "
2646 "enable the prevent-compression action.");
2649 #endif /* defined(FEATURE_ZLIB) */
2656 /*********************************************************************
2658 * Function : server_content_length
2660 * Description : Adjust Content-Length header if we modified
2664 * 1 : csp = Current client state (buffers, headers, etc...)
2665 * 2 : header = On input, pointer to header to modify.
2666 * On output, pointer to the modified header, or NULL
2667 * to remove the header. This function frees the
2668 * original string if necessary.
2670 * Returns : JB_ERR_OK on success, or
2671 * JB_ERR_MEMORY on out-of-memory error.
2673 *********************************************************************/
2674 static jb_err server_content_length(struct client_state *csp, char **header)
2676 const size_t max_header_length = 80;
2678 /* Regenerate header if the content was modified. */
2679 if (csp->flags & CSP_FLAG_MODIFIED)
2682 *header = (char *) zalloc(max_header_length);
2683 if (*header == NULL)
2685 return JB_ERR_MEMORY;
2688 snprintf(*header, max_header_length, "Content-Length: %d",
2689 (int)csp->content_length);
2690 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2691 (int)csp->content_length);
2698 /*********************************************************************
2700 * Function : server_content_md5
2702 * Description : Crumble any Content-MD5 headers if the document was
2703 * modified. FIXME: Should we re-compute instead?
2706 * 1 : csp = Current client state (buffers, headers, etc...)
2707 * 2 : header = On input, pointer to header to modify.
2708 * On output, pointer to the modified header, or NULL
2709 * to remove the header. This function frees the
2710 * original string if necessary.
2712 * Returns : JB_ERR_OK on success, or
2713 * JB_ERR_MEMORY on out-of-memory error.
2715 *********************************************************************/
2716 static jb_err server_content_md5(struct client_state *csp, char **header)
2718 if (csp->flags & CSP_FLAG_MODIFIED)
2720 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2728 /*********************************************************************
2730 * Function : server_content_disposition
2732 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2733 * Called from `sed'.
2736 * 1 : csp = Current client state (buffers, headers, etc...)
2737 * 2 : header = On input, pointer to header to modify.
2738 * On output, pointer to the modified header, or NULL
2739 * to remove the header. This function frees the
2740 * original string if necessary.
2742 * Returns : JB_ERR_OK on success, or
2743 * JB_ERR_MEMORY on out-of-memory error.
2745 *********************************************************************/
2746 static jb_err server_content_disposition(struct client_state *csp, char **header)
2751 * Are we messing with the Content-Disposition header?
2753 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2759 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2761 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2764 * Blocking content-disposition header
2766 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2773 * Replacing Content-Disposition header
2776 *header = strdup("Content-Disposition: ");
2777 string_append(header, newval);
2779 if (*header != NULL)
2781 log_error(LOG_LEVEL_HEADER,
2782 "Content-Disposition header crunched and replaced with: %s", *header);
2785 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2789 /*********************************************************************
2791 * Function : server_last_modified
2793 * Description : Changes Last-Modified header to the actual date
2794 * to help hide-if-modified-since.
2795 * Called from `sed'.
2798 * 1 : csp = Current client state (buffers, headers, etc...)
2799 * 2 : header = On input, pointer to header to modify.
2800 * On output, pointer to the modified header, or NULL
2801 * to remove the header. This function frees the
2802 * original string if necessary.
2804 * Returns : JB_ERR_OK on success, or
2805 * JB_ERR_MEMORY on out-of-memory error.
2807 *********************************************************************/
2808 static jb_err server_last_modified(struct client_state *csp, char **header)
2811 char buf[BUFFER_SIZE];
2814 #ifdef HAVE_GMTIME_R
2817 struct tm *timeptr = NULL;
2818 time_t now, last_modified;
2820 long int days, hours, minutes, seconds;
2823 * Are we messing with the Last-Modified header?
2825 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2831 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2833 if (0 == strcmpic(newval, "block") )
2836 * Blocking Last-Modified header. Useless but why not.
2838 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2842 else if (0 == strcmpic(newval, "reset-to-request-time"))
2845 * Setting Last-Modified Header to now.
2847 get_http_time(0, buf, sizeof(buf));
2849 *header = strdup("Last-Modified: ");
2850 string_append(header, buf);
2852 if (*header == NULL)
2854 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2858 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2861 else if (0 == strcmpic(newval, "randomize"))
2863 const char *header_time = *header + sizeof("Last-Modified:");
2865 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2867 #ifdef HAVE_GMTIME_R
2868 timeptr = gmtime_r(&now, &gmt);
2869 #elif FEATURE_PTHREAD
2870 privoxy_mutex_lock(&gmtime_mutex);
2871 timeptr = gmtime(&now);
2872 privoxy_mutex_unlock(&gmtime_mutex);
2874 timeptr = gmtime(&now);
2876 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2878 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2883 rtime = (long int)difftime(now, last_modified);
2892 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2894 rtime = pick_from_range(rtime);
2895 if (negative) rtime *= -1;
2896 last_modified += rtime;
2897 #ifdef HAVE_GMTIME_R
2898 timeptr = gmtime_r(&last_modified, &gmt);
2899 #elif FEATURE_PTHREAD
2900 privoxy_mutex_lock(&gmtime_mutex);
2901 timeptr = gmtime(&last_modified);
2902 privoxy_mutex_unlock(&gmtime_mutex);
2904 timeptr = gmtime(&last_modified);
2906 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2908 *header = strdup("Last-Modified: ");
2909 string_append(header, newheader);
2911 if (*header == NULL)
2913 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2914 return JB_ERR_MEMORY;
2917 days = rtime / (3600 * 24);
2918 hours = rtime / 3600 % 24;
2919 minutes = rtime / 60 % 60;
2920 seconds = rtime % 60;
2922 log_error(LOG_LEVEL_HEADER,
2923 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2924 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2925 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2929 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2938 /*********************************************************************
2940 * Function : client_accept_encoding
2942 * Description : Rewrite the client's Accept-Encoding header so that
2943 * if doesn't allow compression, if the action applies.
2944 * Note: For HTTP/1.0 the absence of the header is enough.
2947 * 1 : csp = Current client state (buffers, headers, etc...)
2948 * 2 : header = On input, pointer to header to modify.
2949 * On output, pointer to the modified header, or NULL
2950 * to remove the header. This function frees the
2951 * original string if necessary.
2953 * Returns : JB_ERR_OK on success, or
2954 * JB_ERR_MEMORY on out-of-memory error.
2956 *********************************************************************/
2957 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2959 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2961 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2965 /* Temporarily disable the correct behaviour to
2966 * work around a PHP bug.
2968 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2970 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2971 * if (*header == NULL)
2973 * return JB_ERR_MEMORY;
2984 /*********************************************************************
2986 * Function : client_te
2988 * Description : Rewrite the client's TE header so that
2989 * if doesn't allow compression, if the action applies.
2992 * 1 : csp = Current client state (buffers, headers, etc...)
2993 * 2 : header = On input, pointer to header to modify.
2994 * On output, pointer to the modified header, or NULL
2995 * to remove the header. This function frees the
2996 * original string if necessary.
2998 * Returns : JB_ERR_OK on success, or
2999 * JB_ERR_MEMORY on out-of-memory error.
3001 *********************************************************************/
3002 static jb_err client_te(struct client_state *csp, char **header)
3004 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3007 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3014 /*********************************************************************
3016 * Function : client_referrer
3018 * Description : Handle the "referer" config setting properly.
3019 * Called from `sed'.
3022 * 1 : csp = Current client state (buffers, headers, etc...)
3023 * 2 : header = On input, pointer to header to modify.
3024 * On output, pointer to the modified header, or NULL
3025 * to remove the header. This function frees the
3026 * original string if necessary.
3028 * Returns : JB_ERR_OK on success, or
3029 * JB_ERR_MEMORY on out-of-memory error.
3031 *********************************************************************/
3032 static jb_err client_referrer(struct client_state *csp, char **header)
3034 const char *parameter;
3035 /* booleans for parameters we have to check multiple times */
3036 int parameter_conditional_block;
3037 int parameter_conditional_forge;
3039 #ifdef FEATURE_FORCE_LOAD
3041 * Since the referrer can include the prefix even
3042 * if the request itself is non-forced, we must
3043 * clean it unconditionally.
3045 * XXX: strclean is too broad
3047 strclean(*header, FORCE_PREFIX);
3048 #endif /* def FEATURE_FORCE_LOAD */
3050 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3052 /* Nothing left to do */
3056 parameter = csp->action->string[ACTION_STRING_REFERER];
3057 assert(parameter != NULL);
3058 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3059 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3061 if (!parameter_conditional_block && !parameter_conditional_forge)
3064 * As conditional-block and conditional-forge are the only
3065 * parameters that rely on the original referrer, we can
3066 * remove it now for all the others.
3071 if (0 == strcmpic(parameter, "block"))
3073 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3076 else if (parameter_conditional_block || parameter_conditional_forge)
3078 return handle_conditional_hide_referrer_parameter(header,
3079 csp->http->hostport, parameter_conditional_block);
3081 else if (0 == strcmpic(parameter, "forge"))
3083 return create_forged_referrer(header, csp->http->hostport);
3087 /* interpret parameter as user-supplied referer to fake */
3088 return create_fake_referrer(header, parameter);
3093 /*********************************************************************
3095 * Function : client_accept_language
3097 * Description : Handle the "Accept-Language" config setting properly.
3098 * Called from `sed'.
3101 * 1 : csp = Current client state (buffers, headers, etc...)
3102 * 2 : header = On input, pointer to header to modify.
3103 * On output, pointer to the modified header, or NULL
3104 * to remove the header. This function frees the
3105 * original string if necessary.
3107 * Returns : JB_ERR_OK on success, or
3108 * JB_ERR_MEMORY on out-of-memory error.
3110 *********************************************************************/
3111 static jb_err client_accept_language(struct client_state *csp, char **header)
3116 * Are we messing with the Accept-Language?
3118 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3120 /*I don't think so*/
3124 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3126 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3129 * Blocking Accept-Language header
3131 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3138 * Replacing Accept-Language header
3141 *header = strdup("Accept-Language: ");
3142 string_append(header, newval);
3144 if (*header == NULL)
3146 log_error(LOG_LEVEL_ERROR,
3147 "Insufficient memory. Accept-Language header crunched without replacement.");
3151 log_error(LOG_LEVEL_HEADER,
3152 "Accept-Language header crunched and replaced with: %s", *header);
3155 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3159 /*********************************************************************
3161 * Function : crunch_client_header
3163 * Description : Crunch client header if it matches a string supplied by the
3164 * user. Called from `sed'.
3167 * 1 : csp = Current client state (buffers, headers, etc...)
3168 * 2 : header = On input, pointer to header to modify.
3169 * On output, pointer to the modified header, or NULL
3170 * to remove the header. This function frees the
3171 * original string if necessary.
3173 * Returns : JB_ERR_OK on success and always succeeds
3175 *********************************************************************/
3176 static jb_err crunch_client_header(struct client_state *csp, char **header)
3178 const char *crunch_pattern;
3180 /* Do we feel like crunching? */
3181 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3183 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3185 /* Is the current header the lucky one? */
3186 if (strstr(*header, crunch_pattern))
3188 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3196 /*********************************************************************
3198 * Function : client_uagent
3200 * Description : Handle the "user-agent" config setting properly
3201 * and remember its original value to enable browser
3202 * bug workarounds. Called from `sed'.
3205 * 1 : csp = Current client state (buffers, headers, etc...)
3206 * 2 : header = On input, pointer to header to modify.
3207 * On output, pointer to the modified header, or NULL
3208 * to remove the header. This function frees the
3209 * original string if necessary.
3211 * Returns : JB_ERR_OK on success, or
3212 * JB_ERR_MEMORY on out-of-memory error.
3214 *********************************************************************/
3215 static jb_err client_uagent(struct client_state *csp, char **header)
3219 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3224 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3231 *header = strdup("User-Agent: ");
3232 string_append(header, newval);
3234 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3236 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3240 /*********************************************************************
3242 * Function : client_ua
3244 * Description : Handle "ua-" headers properly. Called from `sed'.
3247 * 1 : csp = Current client state (buffers, headers, etc...)
3248 * 2 : header = On input, pointer to header to modify.
3249 * On output, pointer to the modified header, or NULL
3250 * to remove the header. This function frees the
3251 * original string if necessary.
3253 * Returns : JB_ERR_OK on success, or
3254 * JB_ERR_MEMORY on out-of-memory error.
3256 *********************************************************************/
3257 static jb_err client_ua(struct client_state *csp, char **header)
3259 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3261 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3269 /*********************************************************************
3271 * Function : client_from
3273 * Description : Handle the "from" config setting properly.
3274 * Called from `sed'.
3277 * 1 : csp = Current client state (buffers, headers, etc...)
3278 * 2 : header = On input, pointer to header to modify.
3279 * On output, pointer to the modified header, or NULL
3280 * to remove the header. This function frees the
3281 * original string if necessary.
3283 * Returns : JB_ERR_OK on success, or
3284 * JB_ERR_MEMORY on out-of-memory error.
3286 *********************************************************************/
3287 static jb_err client_from(struct client_state *csp, char **header)
3291 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3298 newval = csp->action->string[ACTION_STRING_FROM];
3301 * Are we blocking the e-mail address?
3303 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3305 log_error(LOG_LEVEL_HEADER, "crunched From!");
3309 log_error(LOG_LEVEL_HEADER, " modified");
3311 *header = strdup("From: ");
3312 string_append(header, newval);
3314 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3318 /*********************************************************************
3320 * Function : client_send_cookie
3322 * Description : Crunches the "cookie" header if necessary.
3323 * Called from `sed'.
3325 * XXX: Stupid name, doesn't send squat.
3328 * 1 : csp = Current client state (buffers, headers, etc...)
3329 * 2 : header = On input, pointer to header to modify.
3330 * On output, pointer to the modified header, or NULL
3331 * to remove the header. This function frees the
3332 * original string if necessary.
3334 * Returns : JB_ERR_OK on success, or
3335 * JB_ERR_MEMORY on out-of-memory error.
3337 *********************************************************************/
3338 static jb_err client_send_cookie(struct client_state *csp, char **header)
3340 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3342 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3350 /*********************************************************************
3352 * Function : client_x_forwarded
3354 * Description : Handle the "x-forwarded-for" config setting properly,
3355 * also used in the add_client_headers list. Called from `sed'.
3358 * 1 : csp = Current client state (buffers, headers, etc...)
3359 * 2 : header = On input, pointer to header to modify.
3360 * On output, pointer to the modified header, or NULL
3361 * to remove the header. This function frees the
3362 * original string if necessary.
3364 * Returns : JB_ERR_OK on success, or
3365 * JB_ERR_MEMORY on out-of-memory error.
3367 *********************************************************************/
3368 jb_err client_x_forwarded(struct client_state *csp, char **header)
3370 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3373 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3380 /*********************************************************************
3382 * Function : client_max_forwards
3384 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3385 * from the value of the Max-Forwards header field.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3389 * 2 : header = On input, pointer to header to modify.
3390 * On output, pointer to the modified header, or NULL
3391 * to remove the header. This function frees the
3392 * original string if necessary.
3394 * Returns : JB_ERR_OK on success, or
3395 * JB_ERR_MEMORY on out-of-memory error.
3397 *********************************************************************/
3398 static jb_err client_max_forwards(struct client_state *csp, char **header)
3402 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3403 (0 == strcmpic(csp->http->gpc, "options")))
3405 assert(*(*header+12) == ':');
3406 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3408 if (max_forwards > 0)
3410 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3411 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3412 csp->http->gpc, max_forwards);
3414 else if (max_forwards < 0)
3416 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3422 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3431 /*********************************************************************
3433 * Function : client_host
3435 * Description : If the request URI did not contain host and
3436 * port information, parse and evaluate the Host
3439 * Also, kill ill-formed HOST: headers as sent by
3440 * Apple's iTunes software when used with a proxy.
3443 * 1 : csp = Current client state (buffers, headers, etc...)
3444 * 2 : header = On input, pointer to header to modify.
3445 * On output, pointer to the modified header, or NULL
3446 * to remove the header. This function frees the
3447 * original string if necessary.
3449 * Returns : JB_ERR_OK on success, or
3450 * JB_ERR_MEMORY on out-of-memory error.
3452 *********************************************************************/
3453 static jb_err client_host(struct client_state *csp, char **header)
3458 * If the header field name is all upper-case, chances are that it's
3459 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3460 * not a problem -- they are regenerated later.
3462 if ((*header)[1] == 'O')
3464 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3469 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3470 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3473 if (NULL == (p = strdup((*header)+6)))
3475 return JB_ERR_MEMORY;
3478 if (NULL == (q = strdup(p)))
3481 return JB_ERR_MEMORY;
3484 freez(csp->http->hostport);
3485 csp->http->hostport = p;
3486 freez(csp->http->host);
3487 csp->http->host = q;
3488 q = strchr(csp->http->host, ':');
3491 /* Terminate hostname and evaluate port string */
3493 csp->http->port = atoi(q);
3497 csp->http->port = csp->http->ssl ? 443 : 80;
3500 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3501 csp->http->hostport, csp->http->host, csp->http->port);
3504 /* Signal client_host_adder() to return right away */
3505 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3511 /*********************************************************************
3513 * Function : client_if_modified_since
3515 * Description : Remove or modify the If-Modified-Since header.
3518 * 1 : csp = Current client state (buffers, headers, etc...)
3519 * 2 : header = On input, pointer to header to modify.
3520 * On output, pointer to the modified header, or NULL
3521 * to remove the header. This function frees the
3522 * original string if necessary.
3524 * Returns : JB_ERR_OK on success, or
3525 * JB_ERR_MEMORY on out-of-memory error.
3527 *********************************************************************/
3528 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3531 #ifdef HAVE_GMTIME_R
3534 struct tm *timeptr = NULL;
3538 long int hours, minutes, seconds;
3542 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3545 * The client got an error message because of a temporary problem,
3546 * the problem is gone and the client now tries to revalidate our
3547 * error message on the real server. The revalidation would always
3548 * end with the transmission of the whole document and there is
3549 * no need to expose the bogus If-Modified-Since header.
3551 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3554 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3556 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3558 if ((0 == strcmpic(newval, "block")))
3560 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3563 else /* add random value */
3565 const char *header_time = *header + sizeof("If-Modified-Since:");
3567 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3569 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3574 rtime = strtol(newval, &endptr, 0);
3577 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3578 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3585 rtime = pick_from_range(rtime);
3589 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3592 tm += rtime * (negative ? -1 : 1);
3593 #ifdef HAVE_GMTIME_R
3594 timeptr = gmtime_r(&tm, &gmt);
3595 #elif FEATURE_PTHREAD
3596 privoxy_mutex_lock(&gmtime_mutex);
3597 timeptr = gmtime(&tm);
3598 privoxy_mutex_unlock(&gmtime_mutex);
3600 timeptr = gmtime(&tm);
3602 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3605 *header = strdup("If-Modified-Since: ");
3606 string_append(header, newheader);
3608 if (*header == NULL)
3610 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3611 return JB_ERR_MEMORY;
3614 hours = rtime / 3600;
3615 minutes = rtime / 60 % 60;
3616 seconds = rtime % 60;
3618 log_error(LOG_LEVEL_HEADER,
3619 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3620 *header, (negative) ? "subtracted" : "added", hours,
3621 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3622 seconds, (seconds == 1) ? ")" : "s)");
3631 /*********************************************************************
3633 * Function : client_if_none_match
3635 * Description : Remove the If-None-Match header.
3638 * 1 : csp = Current client state (buffers, headers, etc...)
3639 * 2 : header = On input, pointer to header to modify.
3640 * On output, pointer to the modified header, or NULL
3641 * to remove the header. This function frees the
3642 * original string if necessary.
3644 * Returns : JB_ERR_OK on success, or
3645 * JB_ERR_MEMORY on out-of-memory error.
3647 *********************************************************************/
3648 static jb_err client_if_none_match(struct client_state *csp, char **header)
3650 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3652 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3660 /*********************************************************************
3662 * Function : client_x_filter
3664 * Description : Disables filtering if the client set "X-Filter: No".
3665 * Called from `sed'.
3668 * 1 : csp = Current client state (buffers, headers, etc...)
3669 * 2 : header = On input, pointer to header to modify.
3670 * On output, pointer to the modified header, or NULL
3671 * to remove the header. This function frees the
3672 * original string if necessary.
3674 * Returns : JB_ERR_OK on success
3676 *********************************************************************/
3677 jb_err client_x_filter(struct client_state *csp, char **header)
3679 if ( 0 == strcmpic(*header, "X-Filter: No"))
3681 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3683 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3687 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3689 log_error(LOG_LEVEL_HEADER,
3690 "force-text-mode overruled the client's request to fetch without filtering!");
3694 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3695 csp->flags |= CSP_FLAG_NO_FILTERING;
3696 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3698 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3706 /*********************************************************************
3708 * Function : client_range
3710 * Description : Removes Range, Request-Range and If-Range headers if
3711 * content filtering is enabled. If the client's version
3712 * of the document has been altered by Privoxy, the server
3713 * could interpret the range differently than the client
3714 * intended in which case the user could end up with
3715 * corrupted content.
3718 * 1 : csp = Current client state (buffers, headers, etc...)
3719 * 2 : header = On input, pointer to header to modify.
3720 * On output, pointer to the modified header, or NULL
3721 * to remove the header. This function frees the
3722 * original string if necessary.
3724 * Returns : JB_ERR_OK
3726 *********************************************************************/
3727 static jb_err client_range(struct client_state *csp, char **header)
3729 if (content_filters_enabled(csp->action))
3731 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3732 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3739 /* the following functions add headers directly to the header list */
3741 /*********************************************************************
3743 * Function : client_host_adder
3745 * Description : Adds the Host: header field if it is missing.
3746 * Called from `sed'.
3749 * 1 : csp = Current client state (buffers, headers, etc...)
3751 * Returns : JB_ERR_OK on success, or
3752 * JB_ERR_MEMORY on out-of-memory error.
3754 *********************************************************************/
3755 static jb_err client_host_adder(struct client_state *csp)
3760 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3762 /* Header already set by the client, nothing to do. */
3766 if ( !csp->http->hostport || !*(csp->http->hostport))
3768 /* XXX: When does this happen and why is it OK? */
3769 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3774 * remove 'user:pass@' from 'proto://user:pass@host'
3776 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3782 p = csp->http->hostport;
3785 /* XXX: Just add it, we already made sure that it will be unique */
3786 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3787 err = enlist_unique_header(csp->headers, "Host", p);
3794 /*********************************************************************
3796 * Function : client_accept_encoding_adder
3798 * Description : Add an Accept-Encoding header to the client's request
3799 * that disables compression if the action applies, and
3800 * the header is not already there. Called from `sed'.
3801 * Note: For HTTP/1.0, the absence of the header is enough.
3804 * 1 : csp = Current client state (buffers, headers, etc...)
3806 * Returns : JB_ERR_OK on success, or
3807 * JB_ERR_MEMORY on out-of-memory error.
3809 *********************************************************************/
3810 static jb_err client_accept_encoding_adder(struct client_state *csp)
3812 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3813 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3815 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3823 /*********************************************************************
3825 * Function : client_xtra_adder
3827 * Description : Used in the add_client_headers list. Called from `sed'.
3830 * 1 : csp = Current client state (buffers, headers, etc...)
3832 * Returns : JB_ERR_OK on success, or
3833 * JB_ERR_MEMORY on out-of-memory error.
3835 *********************************************************************/
3836 static jb_err client_xtra_adder(struct client_state *csp)
3838 struct list_entry *lst;
3841 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3842 lst ; lst = lst->next)
3844 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3845 err = enlist(csp->headers, lst->str);
3857 /*********************************************************************
3859 * Function : connection_close_adder
3861 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3862 * support. Adds a "Connection: close" header to csp->headers
3863 * unless the header was already present. Called from `sed'.
3865 * FIXME: This whole function shouldn't be neccessary!
3868 * 1 : csp = Current client state (buffers, headers, etc...)
3870 * Returns : JB_ERR_OK on success, or
3871 * JB_ERR_MEMORY on out-of-memory error.
3873 *********************************************************************/
3874 static jb_err connection_close_adder(struct client_state *csp)
3876 const unsigned int flags = csp->flags;
3879 * Return right away if
3881 * - we're parsing server headers and the server header
3882 * "Connection: close" is already set, or if
3884 * - we're parsing client headers and the client header
3885 * "Connection: close" is already set.
3887 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3888 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3889 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3890 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3895 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3897 return enlist(csp->headers, "Connection: close");
3901 /*********************************************************************
3903 * Function : server_http
3905 * Description : - Save the HTTP Status into csp->http->status
3906 * - Set CT_TABOO to prevent filtering if the answer
3907 * is a partial range (HTTP status 206)
3908 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3912 * 1 : csp = Current client state (buffers, headers, etc...)
3913 * 2 : header = On input, pointer to header to modify.
3914 * On output, pointer to the modified header, or NULL
3915 * to remove the header. This function frees the
3916 * original string if necessary.
3918 * Returns : JB_ERR_OK on success, or
3919 * JB_ERR_MEMORY on out-of-memory error.
3921 *********************************************************************/
3922 static jb_err server_http(struct client_state *csp, char **header)
3924 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3925 if (csp->http->status == 206)
3927 csp->content_type = CT_TABOO;
3930 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3932 /* XXX: Should we do a real validity check here? */
3933 if (strlen(*header) > 8)
3936 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3941 * XXX: Should we block the request or
3942 * enlist a valid status code line here?
3944 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3945 "Downgrading to HTTP/1.0 impossible.");
3953 /*********************************************************************
3955 * Function : server_set_cookie
3957 * Description : Handle the server "cookie" header properly.
3958 * Log cookie to the jar file. Then "crunch",
3959 * accept or rewrite it to a session cookie.
3960 * Called from `sed'.
3962 * TODO: Allow the user to specify a new expiration
3963 * time to cause the cookie to expire even before the
3964 * browser is closed.
3967 * 1 : csp = Current client state (buffers, headers, etc...)
3968 * 2 : header = On input, pointer to header to modify.
3969 * On output, pointer to the modified header, or NULL
3970 * to remove the header. This function frees the
3971 * original string if necessary.
3973 * Returns : JB_ERR_OK on success, or
3974 * JB_ERR_MEMORY on out-of-memory error.
3976 *********************************************************************/
3977 static jb_err server_set_cookie(struct client_state *csp, char **header)
3984 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3986 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3989 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3991 /* Flag whether or not to log a message */
3994 /* A variable to store the tag we're working on */
3997 /* Skip "Set-Cookie:" (11 characters) in header */
3998 cur_tag = *header + 11;
4000 /* skip whitespace between "Set-Cookie:" and value */
4001 while (*cur_tag && ijb_isspace(*cur_tag))
4006 /* Loop through each tag in the cookie */
4010 char *next_tag = strchr(cur_tag, ';');
4011 if (next_tag != NULL)
4013 /* Skip the ';' character itself */
4016 /* skip whitespace ";" and start of tag */
4017 while (*next_tag && ijb_isspace(*next_tag))
4024 /* "Next tag" is the end of the string */
4025 next_tag = cur_tag + strlen(cur_tag);
4029 * Check the expiration date to see
4030 * if the cookie is still valid, if yes,
4031 * rewrite it to a session cookie.
4033 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4035 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4037 /* Did we detect the date properly? */
4038 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4041 * Nope, treat it as if it was still valid.
4043 * XXX: Should we remove the whole cookie instead?
4045 log_error(LOG_LEVEL_ERROR,
4046 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4047 string_move(cur_tag, next_tag);
4053 * Yes. Check if the cookie is still valid.
4055 * If the cookie is already expired it's probably
4056 * a delete cookie and even if it isn't, the browser
4057 * will discard it anyway.
4061 * XXX: timegm() isn't available on some AmigaOS
4062 * versions and our replacement doesn't work.
4064 * Our options are to either:
4066 * - disable session-cookies-only completely if timegm
4069 * - to simply remove all expired tags, like it has
4070 * been done until Privoxy 3.0.6 and to live with
4071 * the consequence that it can cause login/logout
4072 * problems on servers that don't validate their
4073 * input properly, or
4075 * - to replace it with mktime in which
4076 * case there is a slight chance of valid cookies
4077 * passing as already expired.
4079 * This is the way it's currently done and it's not
4080 * as bad as it sounds. If the missing GMT offset is
4081 * enough to change the result of the expiration check
4082 * the cookie will be only valid for a few hours
4083 * anyway, which in many cases will be shorter
4084 * than a browser session.
4086 if (cookie_time - now < 0)
4088 log_error(LOG_LEVEL_HEADER,
4089 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4090 /* Just in case some clown sets more then one expiration date */
4096 * Still valid, delete expiration date by copying
4097 * the rest of the string over it.
4099 string_move(cur_tag, next_tag);
4101 /* That changed the header, need to issue a log message */
4105 * Note that the next tag has now been moved to *cur_tag,
4106 * so we do not need to update the cur_tag pointer.
4114 /* Move on to next cookie tag */
4121 assert(NULL != *header);
4122 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4131 #ifdef FEATURE_FORCE_LOAD
4132 /*********************************************************************
4134 * Function : strclean
4136 * Description : In-Situ-Eliminate all occurances of substring in
4140 * 1 : string = string to clean
4141 * 2 : substring = substring to eliminate
4143 * Returns : Number of eliminations
4145 *********************************************************************/
4146 int strclean(char *string, const char *substring)
4152 len = strlen(substring);
4154 while((pos = strstr(string, substring)) != NULL)
4161 while (*p++ != '\0');
4168 #endif /* def FEATURE_FORCE_LOAD */
4171 /*********************************************************************
4173 * Function : parse_header_time
4175 * Description : Parses time formats used in HTTP header strings
4176 * to get the numerical respresentation.
4179 * 1 : header_time = HTTP header time as string.
4180 * 2 : result = storage for header_time in seconds
4182 * Returns : JB_ERR_OK if the time format was recognized, or
4183 * JB_ERR_PARSE otherwise.
4185 *********************************************************************/
4186 static jb_err parse_header_time(const char *header_time, time_t *result)
4191 * Zero out gmt to prevent time zone offsets.
4193 * While this is only necessary on some platforms
4194 * (mingw32 for example), I don't know how to
4195 * detect these automatically and doing it everywhere
4198 memset(&gmt, 0, sizeof(gmt));
4200 /* Tue, 02 Jun 2037 20:00:00 */
4201 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4202 /* Tue, 02-Jun-2037 20:00:00 */
4203 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4204 /* Tue, 02-Jun-37 20:00:00 */
4205 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4206 /* Tuesday, 02-Jun-2037 20:00:00 */
4207 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4208 /* Tuesday Jun 02 20:00:00 2037 */
4209 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4211 return JB_ERR_PARSE;
4214 *result = timegm(&gmt);
4221 /*********************************************************************
4223 * Function : get_destination_from_headers
4225 * Description : Parse the "Host:" header to get the request's destination.
4226 * Only needed if the client's request was forcefully
4227 * redirected into Privoxy.
4229 * Code mainly copied from client_host() which is currently
4230 * run too late for this purpose.
4233 * 1 : headers = List of headers (one of them hopefully being
4234 * the "Host:" header)
4235 * 2 : http = storage for the result (host, port and hostport).
4237 * Returns : JB_ERR_MEMORY in case of memory problems,
4238 * JB_ERR_PARSE if the host header couldn't be found,
4239 * JB_ERR_OK otherwise.
4241 *********************************************************************/
4242 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4248 host = get_header_value(headers, "Host:");
4252 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4253 return JB_ERR_PARSE;
4256 if (NULL == (p = strdup((host))))
4258 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4259 return JB_ERR_MEMORY;
4262 if (NULL == (q = strdup(p)))
4265 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4266 return JB_ERR_MEMORY;
4269 freez(http->hostport);
4273 q = strchr(http->host, ':');
4276 /* Terminate hostname and evaluate port string */
4278 http->port = atoi(q);
4282 http->port = http->ssl ? 443 : 80;
4285 /* Rebuild request URL */
4287 http->url = strdup(http->ssl ? "https://" : "http://");
4288 string_append(&http->url, http->hostport);
4289 string_append(&http->url, http->path);
4290 if (http->url == NULL)
4292 return JB_ERR_MEMORY;
4295 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4303 /*********************************************************************
4305 * Function : create_forged_referrer
4307 * Description : Helper for client_referrer to forge a referer as
4308 * 'http://[hostname:port/' to fool stupid
4309 * checks for in-site links
4312 * 1 : header = Pointer to header pointer
4313 * 2 : hostport = Host and optionally port as string
4315 * Returns : JB_ERR_OK in case of success, or
4316 * JB_ERR_MEMORY in case of memory problems.
4318 *********************************************************************/
4319 static jb_err create_forged_referrer(char **header, const char *hostport)
4321 assert(NULL == *header);
4323 *header = strdup("Referer: http://");
4324 string_append(header, hostport);
4325 string_append(header, "/");
4327 if (NULL == *header)
4329 return JB_ERR_MEMORY;
4332 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4339 /*********************************************************************
4341 * Function : create_fake_referrer
4343 * Description : Helper for client_referrer to create a fake referrer
4344 * based on a string supplied by the user.
4347 * 1 : header = Pointer to header pointer
4348 * 2 : hosthost = Referrer to fake
4350 * Returns : JB_ERR_OK in case of success, or
4351 * JB_ERR_MEMORY in case of memory problems.
4353 *********************************************************************/
4354 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4356 assert(NULL == *header);
4358 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4360 log_error(LOG_LEVEL_HEADER,
4361 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4363 *header = strdup("Referer: ");
4364 string_append(header, fake_referrer);
4366 if (NULL == *header)
4368 return JB_ERR_MEMORY;
4371 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4378 /*********************************************************************
4380 * Function : handle_conditional_hide_referrer_parameter
4382 * Description : Helper for client_referrer to crunch or forge
4383 * the referrer header if the host has changed.
4386 * 1 : header = Pointer to header pointer
4387 * 2 : host = The target host (may include the port)
4388 * 3 : parameter_conditional_block = Boolean to signal
4389 * if we're in conditional-block mode. If not set,
4390 * we're in conditional-forge mode.
4392 * Returns : JB_ERR_OK in case of success, or
4393 * JB_ERR_MEMORY in case of memory problems.
4395 *********************************************************************/
4396 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4397 const char *host, const int parameter_conditional_block)
4399 char *referer = strdup(*header);
4400 const size_t hostlenght = strlen(host);
4402 if (NULL == referer)
4405 return JB_ERR_MEMORY;
4408 /* referer begins with 'Referer: http[s]://' */
4409 if (hostlenght < (strlen(referer)-17))
4412 * Shorten referer to make sure the referer is blocked
4413 * if www.example.org/www.example.com-shall-see-the-referer/
4414 * links to www.example.com/
4416 referer[hostlenght+17] = '\0';
4418 if (NULL == strstr(referer, host))
4420 /* Host has changed */
4421 if (parameter_conditional_block)
4423 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4430 return create_forged_referrer(header, host);