1 const char parsers_rcs[] = "$Id: parsers.c,v 1.137 2008/05/30 15:50:08 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.137 2008/05/30 15:50:08 fabiankeil
48 * Remove questionable micro-optimizations
49 * whose usefulness has never been measured.
51 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
52 * s@Insufficent@Insufficient@
54 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
55 * The whole point of strclean() is to modify the
56 * first parameter, so don't mark it immutable,
57 * even though the compiler lets us get away with it.
59 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
60 * As the wafer actions are gone, we can stop including encode.h.
62 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
63 * Ditch cast from (char **) to (char **).
65 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
66 * Streamline sed()'s prototype and declare
67 * the header parse and add structures static.
69 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
70 * Factor update_server_headers() out of sed(), ditch the
71 * first_run hack and make server_patterns_light static.
73 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
74 * Wrap memmove() calls in string_move()
75 * to document the purpose in one place.
77 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
78 * Normalize linear header white space.
80 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
81 * If a header is split across multiple lines,
82 * merge them to a single line before parsing them.
84 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
85 * Don't provide get_header() with the whole client state
86 * structure when it only needs access to csp->iob.
88 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
89 * Change content_filters_enabled()'s parameter from
90 * csp->action to action so it can be also used in the
91 * CGI code. Don't bother checking if there are filters
92 * loaded, as that's somewhat besides the point.
94 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
95 * Provide get_http_time() with the buffer size so it doesn't
96 * have to blindly assume that the buffer is big enough.
98 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
99 * Don't pass the whole csp structure to flush_socket()
100 * when it only needs a file descriptor and a buffer.
102 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
103 * Remove send-wafer and send-vanilla-wafer actions.
105 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
106 * Remove inspect-jpegs action.
108 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
109 * Let client_range() also handle Request-Range headers
110 * which apparently are still supported by many servers.
112 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
113 * Improve the warning messages that get logged if the action files
114 * "enable" filters but no filters of that type have been loaded.
116 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
117 * In server_content_type():
118 * - Don't require leading white space when detecting image content types.
119 * - Change '... not replaced ...' message to sound less crazy if the text
120 * type actually is 'text/plain'.
121 * - Mark the 'text/plain == binary data' assumption for removal.
122 * - Remove a bunch of trailing white space.
124 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
125 * Minor server_content_disposition() changes:
126 * - Don't regenerate the header name all lower-case.
127 * - Some white space fixes.
128 * - Remove useless log message in case of ENOMEM.
130 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
131 * Garbage-collect the code to add a X-Forwarded-For
132 * header as it seems to be mostly used by accident.
134 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
135 * Fix a crash on mingw32 with some Last Modified times in the future.
137 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
138 * Remove a "can't happen" error block which, over
139 * time, mutated into a "guaranteed to happen" block.
141 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
142 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
143 * - Use shiny new content_filters_enabled() in client_range().
145 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
146 * I forgot about Poland.
148 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
149 * Remove Range and If-Range headers if content filtering is enabled.
151 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
152 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
153 * client_cookie_adder() to make sure send-vanilla-wafer can be
154 * controlled through tags (and thus regression-tested).
156 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
157 * - Remove "scanning headers for" log message again.
158 * - Some more whitespace fixes.
160 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
161 * Refactor client_referrer() and add conditional-forge parameter.
163 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
164 * A bunch of whitespace fixes, pointy hat to me.
166 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
167 * Fix possible memory corruption in server_http, make sure it's not
168 * executed for ordinary server headers and mark some problems for later.
170 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
171 * Let content-type-overwrite{} honour force-text-mode again.
173 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
174 * - Add prototpyes for the header parsers and make them static.
175 * - Comment out client_accept_encoding_adder() which isn't used right now.
177 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
178 * Move the ACTION_FORCE_TEXT_MODE check out of
179 * server_content_type(). Signal other functions
180 * whether or not a content type has been declared.
181 * Part of the fix for BR#1750917.
183 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
184 * Change sed() to return a jb_err in preparation for forward-override{}.
186 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
187 * Adjust "X-Filter: No" to disable dedicated header filters.
189 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
190 * Streamline client_cookie_adder().
192 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
193 * Make sure filters with dynamic jobs actually use them.
195 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
196 * - Introduce dynamic pcrs jobs that can resolve variables.
197 * - Remove unnecessary update_action_bits_for_all_tags() call.
199 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
200 * - Make tagging based on tags set by earlier taggers
201 * of the same kind possible.
202 * - Log whether or not new tags cause action bits updates
203 * (in which case a matching tag-pattern section exists).
204 * - Log if the user tries to set a tag that is already set.
206 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
207 * Introduce tags as alternative way to specify which
208 * actions apply to a request. At the moment tags can be
209 * created based on client and server headers.
211 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
212 * Log a warning if the content is compressed, filtering is
213 * enabled and Privoxy was compiled without zlib support.
216 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
217 * - Fix warnings when compiled with glibc.
218 * - Don't use crumble() for cookie crunching.
219 * - Move cookie time parsing into parse_header_time().
220 * - Let parse_header_time() return a jb_err code
221 * instead of a pointer that can only be used to
222 * check for NULL anyway.
224 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
225 * - Add better protection against malicious gzip headers.
226 * - Stop logging the first hundred bytes of decompressed content.
227 * It looks like it's working and there is always debug 16.
228 * - Log the content size after decompression in decompress_iob()
229 * instead of pcrs_filter_response().
231 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
232 * - Use dedicated header filter actions instead of abusing "filter".
233 * Replace "filter-client-headers" and "filter-client-headers"
234 * with "server-header-filter" and "client-header-filter".
235 * - Remove filter_client_header() and filter_client_header(),
236 * filter_header() now checks the shiny new
237 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
239 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
240 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
241 * - Handle "Cookie:" and "Connection:" headers a bit smarter
242 * (don't crunch them just to recreate them later on).
243 * - Add another non-standard time format for the cookie
244 * expiration date detection.
245 * - Fix a valgrind warning.
247 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
248 * Improve cookie expiration date detection.
250 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
251 * Don't run server_content_length() the first time
252 * sed() parses server headers; only adjust the
253 * Content-Length header if the page was modified.
255 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
256 * Fix log messages regarding the cookie time format
257 * (cookie and request URL were mixed up).
259 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
260 * - Let decompress_iob()
261 * - not corrupt the content if decompression fails
262 * early. (the first byte(s) were lost).
263 * - use pointer arithmetics with defined outcome for
265 * - Use a different kludge to remember a failed decompression.
267 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
268 * Search for Max-Forwards headers case-insensitive,
269 * don't generate the "501 unsupported" message for invalid
270 * Max-Forwards values and don't increase negative ones.
272 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
273 * - Let server_set_cookie() check the expiration date
274 * of cookies and don't touch the ones that are already
275 * expired. Fixes problems with low quality web applications
276 * as described in BR 932612.
278 * - Adjust comment in client_max_forwards to reality;
279 * remove invalid Max-Forwards headers.
281 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
282 * Stop filter_header() from unintentionally removing
283 * empty header lines that were enlisted by the continue
286 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
287 * - Repeat the request URL before logging any headers.
288 * Makes reading the log easier in case of simultaneous requests.
289 * - If there are more than one Content-Type headers in one request,
290 * use the first one and remove the others.
291 * - Remove "newval" variable in server_content_type().
292 * It's only used once.
294 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
295 * Correct a cast, check inflateEnd() exit code
296 * to see if we have to, replace sprintf calls
299 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
300 * Integrate a modified version of Wil Mahan's
301 * zlib patch (PR #895531).
303 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
304 * Skip empty filter files in filter_header()
305 * but don't ignore the ones that come afterwards.
306 * Fixes BR 1619208, this time for real.
308 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
309 * Reverted parts of my last commit
310 * to keep error handling working.
312 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
313 * Fixed gcc43 conversion warnings.
315 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
316 * Bringing back the "useless" localtime() call
317 * I removed in revision 1.67. On some platforms
318 * it's necessary to prevent time zone offsets.
320 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
321 * Rebuild request URL in get_destination_from_headers()
322 * to make sure redirect{pcrs command} works as expected
323 * for intercepted requests.
325 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
326 * Added get_destination_from_headers().
328 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
329 * Make pthread mutex locking more generic. Instead of
330 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
331 * and use mutex locking unless there is an _r function
332 * available. Better safe than sorry.
334 * Fixes "./configure --disable-pthread" and should result
335 * in less threading-related problems on pthread-using platforms,
336 * but it still doesn't fix BR#1122404.
338 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
339 * The special header "X-Filter: No" now disables
340 * header filtering as well.
342 * Revision 1.73 2006/09/23 13:26:38 roro
343 * Replace TABs by spaces in source code.
345 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
346 * Don't print a log message every time filter_headers is
347 * entered or left. It only creates noise without any real
350 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
351 * Fix +hide-if-modified-since{-n}.
353 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
354 * Have hide-if-modified-since interpret the random
355 * range value as minutes instead of hours. Allows
356 * more fine-grained configuration.
358 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
359 * Always have parse_header_time return a pointer
360 * that actual makes sense, even though we currently
361 * only need it to detect problems.
363 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
364 * Added config option enable-remote-http-toggle
365 * to specify if Privoxy should recognize special
366 * headers (currently only X-Filter) to change its
367 * behaviour. Disabled by default.
369 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
370 * After filtering de-chunked instances, remove
371 * "Transfer-Encoding" header entirely instead of changing
372 * it to "Transfer-Encoding: identity", which is invalid.
373 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
375 * Don't use localtime in parse_header_time. An empty time struct
376 * is good enough, it gets overwritten by strptime anyway.
378 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
379 * Use gmtime_r if available, fallback to gmtime with mutex
380 * protection for MacOSX and use vanilla gmtime for the rest.
382 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
383 * Changed client_referrer to use the right type (size_t) for
384 * hostlenght and to shorten the temporary referrer string with
385 * '\0' instead of adding a useless line break.
387 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
388 * - Back to timegm() using GnuPG's replacement if necessary.
389 * Using mktime() and localtime() could add a on hour offset if
390 * the randomize factor was big enough to lead to a summer/wintertime
393 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
395 * - Moved randomization code into pick_from_range().
397 * - Changed parse_header_time definition.
398 * time_t isn't guaranteed to be signed and
399 * if it isn't, -1 isn't available as error code.
400 * Changed some variable types in client_if_modified_since()
401 * because of the same reason.
403 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
404 * OS/2 compilation compatibility fixups
406 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
407 * Changed include from strptime.c to strptime.h
409 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
410 * Split filter-headers{} into filter-client-headers{}
411 * and filter-server-headers{}.
412 * Added parse_header_time() to share some code.
413 * Replaced timegm() with mktime().
415 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
416 * Windows service integration
418 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
419 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
421 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
422 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
423 * with what was really the latest development (the v_3_0_branch branch)
425 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
426 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
428 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
429 * Add the ability to check jpeg images for invalid
430 * lengths of comment blocks. Defensive strategy
431 * against the exploit:
432 * Microsoft Security Bulletin MS04-028
433 * Buffer Overrun in JPEG Processing (GDI+) Could
434 * Allow Code Execution (833987)
435 * Enabled with +inspect-jpegs in actions files.
437 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
438 * Excluded text/plain objects from filtering. This fixes a
439 * couple of client-crashing, download corruption and
440 * Privoxy performance issues, whose root cause lies in
441 * web servers labelling content of unknown type as text/plain.
443 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
444 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
446 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
447 * Completing the previous change
449 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
450 * Added temporary workaround for bug in PHP < 4.2.3
452 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
453 * 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.
455 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
456 * Fix typo: supressed -> suppressed
458 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
459 * Improved cookie logging
461 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
462 * Added basic support for OPTIONS and TRACE HTTP methods:
463 * - New parser function client_max_forwards which decrements
464 * the Max-Forwards HTTP header field of OPTIONS and TRACE
465 * requests by one before forwarding
466 * - New parser function client_host which extracts the host
467 * and port information from the HTTP header field if the
468 * request URI was not absolute
469 * - Don't crumble and re-add the Host: header, but only generate
470 * and append if missing
472 * Revision 1.56 2002/05/12 15:34:22 jongfoster
473 * Fixing typo in a comment
475 * Revision 1.55 2002/05/08 16:01:07 oes
476 * Optimized add_to_iob:
477 * - Use realloc instead of malloc(), memcpy(), free()
478 * - Expand to powers of two if possible, to get
479 * O(log n) reallocs instead of O(n).
480 * - Moved check for buffer limit here from chat
481 * - Report failure via returncode
483 * Revision 1.54 2002/04/02 15:03:16 oes
484 * Tiny code cosmetics
486 * Revision 1.53 2002/03/26 22:29:55 swa
487 * we have a new homepage!
489 * Revision 1.52 2002/03/24 13:25:43 swa
490 * name change related issues
492 * Revision 1.51 2002/03/13 00:27:05 jongfoster
495 * Revision 1.50 2002/03/12 01:45:35 oes
496 * More verbose logging
498 * Revision 1.49 2002/03/09 20:03:52 jongfoster
499 * - Making various functions return int rather than size_t.
500 * (Undoing a recent change). Since size_t is unsigned on
501 * Windows, functions like read_socket that return -1 on
502 * error cannot return a size_t.
504 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
505 * crashes, and also frequently caused JB to jump to 100%
506 * CPU and stay there. (Because it thought it had just
507 * read ((unsigned)-1) == 4Gb of data...)
509 * - The signature of write_socket has changed, it now simply
510 * returns success=0/failure=nonzero.
512 * - Trying to get rid of a few warnings --with-debug on
513 * Windows, I've introduced a new type "jb_socket". This is
514 * used for the socket file descriptors. On Windows, this
515 * is SOCKET (a typedef for unsigned). Everywhere else, it's
516 * an int. The error value can't be -1 any more, so it's
517 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
518 * Windows it maps to the #define INVALID_SOCKET.)
520 * - The signature of bind_port has changed.
522 * Revision 1.48 2002/03/07 03:46:53 oes
523 * Fixed compiler warnings etc
525 * Revision 1.47 2002/02/20 23:15:13 jongfoster
526 * Parsing functions now handle out-of-memory gracefully by returning
529 * Revision 1.46 2002/01/17 21:03:47 jongfoster
530 * Moving all our URL and URL pattern parsing code to urlmatch.c.
532 * Revision 1.45 2002/01/09 14:33:03 oes
533 * Added support for localtime_r.
535 * Revision 1.44 2001/12/14 01:22:54 steudten
536 * Remove 'user:pass@' from 'proto://user:pass@host' for the
537 * new added header 'Host: ..'. (See Req ID 491818)
539 * Revision 1.43 2001/11/23 00:26:38 jongfoster
540 * Fixing two really stupid errors in my previous commit
542 * Revision 1.42 2001/11/22 21:59:30 jongfoster
543 * Adding code to handle +no-cookies-keep
545 * Revision 1.41 2001/11/05 23:43:05 steudten
546 * Add time+date to log files.
548 * Revision 1.40 2001/10/26 20:13:09 jongfoster
549 * ctype.h is needed in Windows, too.
551 * Revision 1.39 2001/10/26 17:40:04 oes
552 * Introduced get_header_value()
553 * Removed http->user_agent, csp->referrer and csp->accept_types
554 * Removed client_accept()
556 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
557 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
558 * threads to call select() simultaneously. So, it's time to do a real, live,
559 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
560 * (native). Both versions will work, but using __OS2__ offers multi-threading.
562 * Revision 1.37 2001/10/23 21:36:02 jongfoster
563 * Documenting sed()'s error behaviou (doc change only)
565 * Revision 1.36 2001/10/13 12:51:51 joergs
566 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
567 * force-load), instead crumble Host: and add it (again) in client_host_adder
568 * (in case we get a HTTP/1.0 request without Host: header and forward it to
569 * a HTTP/1.1 server/proxy).
571 * Revision 1.35 2001/10/09 22:39:21 jongfoster
572 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
575 * Revision 1.34 2001/10/07 18:50:55 oes
576 * Added server_content_encoding, renamed server_transfer_encoding
578 * Revision 1.33 2001/10/07 18:04:49 oes
579 * Changed server_http11 to server_http and its pattern to "HTTP".
580 * Additional functionality: it now saves the HTTP status into
581 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
583 * Revision 1.32 2001/10/07 15:43:28 oes
584 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
585 * client_te and client_accept_encoding_adder, triggered by the new
586 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
587 * changed to allow only identity and chunked, and the TE header is
588 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
590 * parse_http_request no longer does anything than parsing. The rewriting
591 * of http->cmd and version mangling are gone. It now also recognizes
592 * the put and delete methods and saves the url in http->url. Removed
595 * renamed content_type and content_length to have the server_ prefix
597 * server_content_type now only works if csp->content_type != CT_TABOO
599 * added server_transfer_encoding, which
600 * - Sets CT_TABOO to prohibit filtering if encoding compresses
601 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
602 * - Change from "chunked" to "identity" if body was chunked
603 * but has been de-chunked for filtering.
605 * added server_content_md5 which crunches any Content-MD5 headers
606 * if the body was modified.
608 * made server_http11 conditional on +downgrade action
610 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
612 * Revision 1.31 2001/10/05 14:25:02 oes
613 * Crumble Keep-Alive from Server
615 * Revision 1.30 2001/09/29 12:56:03 joergs
616 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
618 * Revision 1.29 2001/09/24 21:09:24 jongfoster
619 * Fixing 2 memory leaks that Guy spotted, where the paramater to
620 * enlist() was not being free()d.
622 * Revision 1.28 2001/09/22 16:32:28 jongfoster
623 * Removing unused #includes.
625 * Revision 1.27 2001/09/20 15:45:25 steudten
627 * add casting from size_t to int for printf()
628 * remove local variable shadow s2
630 * Revision 1.26 2001/09/16 17:05:14 jongfoster
631 * Removing unused #include showarg.h
633 * Revision 1.25 2001/09/16 13:21:27 jongfoster
634 * Changes to use new list functions.
636 * Revision 1.24 2001/09/13 23:05:50 jongfoster
637 * Changing the string paramater to the header parsers a "const".
639 * Revision 1.23 2001/09/12 18:08:19 steudten
641 * In parse_http_request() header rewriting miss the host value, so
642 * from http://www.mydomain.com the result was just " / " not
643 * http://www.mydomain.com/ in case we forward.
645 * Revision 1.22 2001/09/10 10:58:53 oes
646 * Silenced compiler warnings
648 * Revision 1.21 2001/07/31 14:46:00 oes
649 * - Persistant connections now suppressed
650 * - sed() no longer appends empty header to csp->headers
652 * Revision 1.20 2001/07/30 22:08:36 jongfoster
653 * Tidying up #defines:
654 * - All feature #defines are now of the form FEATURE_xxx
655 * - Permanently turned off WIN_GUI_EDIT
656 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
658 * Revision 1.19 2001/07/25 17:21:54 oes
659 * client_uagent now saves copy of User-Agent: header value
661 * Revision 1.18 2001/07/13 14:02:46 oes
662 * - Included fix to repair broken HTTP requests that
663 * don't contain a path, not even '/'.
664 * - Removed all #ifdef PCRS
665 * - content_type now always inspected and classified as
666 * text, gif or other.
667 * - formatting / comments
669 * Revision 1.17 2001/06/29 21:45:41 oes
670 * Indentation, CRLF->LF, Tab-> Space
672 * Revision 1.16 2001/06/29 13:32:42 oes
674 * - Adapted free_http_request
675 * - Removed logentry from cancelled commit
677 * Revision 1.15 2001/06/03 19:12:38 oes
678 * deleted const struct interceptors
680 * Revision 1.14 2001/06/01 18:49:17 jongfoster
681 * Replaced "list_share" with "list" - the tiny memory gain was not
682 * worth the extra complexity.
684 * Revision 1.13 2001/05/31 21:30:33 jongfoster
685 * Removed list code - it's now in list.[ch]
686 * Renamed "permission" to "action", and changed many features
687 * to use the actions file rather than the global config.
689 * Revision 1.12 2001/05/31 17:33:13 oes
693 * Revision 1.11 2001/05/29 20:11:19 joergs
694 * '/ * inside comment' warning removed.
696 * Revision 1.10 2001/05/29 09:50:24 jongfoster
697 * Unified blocklist/imagelist/permissionslist.
698 * File format is still under discussion, but the internal changes
701 * Also modified interceptor behaviour:
702 * - We now intercept all URLs beginning with one of the following
703 * prefixes (and *only* these prefixes):
705 * * http://ijbswa.sf.net/config/
706 * * http://ijbswa.sourceforge.net/config/
707 * - New interceptors "home page" - go to http://i.j.b/ to see it.
708 * - Internal changes so that intercepted and fast redirect pages
709 * are not replaced with an image.
710 * - Interceptors now have the option to send a binary page direct
711 * to the client. (i.e. ijb-send-banner uses this)
712 * - Implemented show-url-info interceptor. (Which is why I needed
713 * the above interceptors changes - a typical URL is
714 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
715 * The previous mechanism would not have intercepted that, and
716 * if it had been intercepted then it then it would have replaced
719 * Revision 1.9 2001/05/28 17:26:33 jongfoster
720 * Fixing segfault if last header was crunched.
721 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
722 * can use the cross-platform sprintf() instead.)
724 * Revision 1.8 2001/05/27 22:17:04 oes
726 * - re_process_buffer no longer writes the modified buffer
727 * to the client, which was very ugly. It now returns the
728 * buffer, which it is then written by chat.
730 * - content_length now adjusts the Content-Length: header
731 * for modified documents rather than crunch()ing it.
732 * (Length info in csp->content_length, which is 0 for
733 * unmodified documents)
735 * - For this to work, sed() is called twice when filtering.
737 * Revision 1.7 2001/05/27 13:19:06 oes
738 * Patched Joergs solution for the content-length in.
740 * Revision 1.6 2001/05/26 13:39:32 jongfoster
741 * Only crunches Content-Length header if applying RE filtering.
742 * Without this fix, Microsoft Windows Update wouldn't work.
744 * Revision 1.5 2001/05/26 00:28:36 jongfoster
745 * Automatic reloading of config file.
746 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
747 * Most of the global variables have been moved to a new
748 * struct configuration_spec, accessed through csp->config->globalname
749 * Most of the globals remaining are used by the Win32 GUI.
751 * Revision 1.4 2001/05/22 18:46:04 oes
753 * - Enabled filtering banners by size rather than URL
754 * by adding patterns that replace all standard banner
755 * sizes with the "Junkbuster" gif to the re_filterfile
757 * - Enabled filtering WebBugs by providing a pattern
758 * which kills all 1x1 images
760 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
761 * which is selected by the (nonstandard and therefore
762 * capital) letter 'U' in the option string.
763 * It causes the quantifiers to be ungreedy by default.
764 * Appending a ? turns back to greedy (!).
766 * - Added a new interceptor ijb-send-banner, which
767 * sends back the "Junkbuster" gif. Without imagelist or
768 * MSIE detection support, or if tinygif = 1, or the
769 * URL isn't recognized as an imageurl, a lame HTML
770 * explanation is sent instead.
772 * - Added new feature, which permits blocking remote
773 * script redirects and firing back a local redirect
775 * The feature is conditionally compiled, i.e. it
776 * can be disabled with --disable-fast-redirects,
777 * plus it must be activated by a "fast-redirects"
778 * line in the config file, has its own log level
779 * and of course wants to be displayed by show-proxy-args
780 * Note: Boy, all the #ifdefs in 1001 locations and
781 * all the fumbling with configure.in and acconfig.h
782 * were *way* more work than the feature itself :-(
784 * - Because a generic redirect template was needed for
785 * this, tinygif = 3 now uses the same.
787 * - Moved GIFs, and other static HTTP response templates
792 * - Removed some >400 CRs again (Jon, you really worked
795 * Revision 1.3 2001/05/20 01:21:20 jongfoster
796 * Version 2.9.4 checkin.
797 * - Merged popupfile and cookiefile, and added control over PCRS
798 * filtering, in new "permissionsfile".
799 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
800 * file error you now get a message box (in the Win32 GUI) rather
801 * than the program exiting with no explanation.
802 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
804 * - Removed tabs from "config"
805 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
806 * - Bumped up version number.
808 * Revision 1.2 2001/05/17 23:02:36 oes
809 * - Made referrer option accept 'L' as a substitute for '§'
811 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
812 * Initial import of version 2.9.3 source tree
815 *********************************************************************/
822 #include <sys/types.h>
832 * Convince GNU's libc to provide a strptime prototype.
835 #endif /*__GLIBC__ */
842 #if !defined(_WIN32) && !defined(__OS2__)
848 #ifdef FEATURE_PTHREAD
850 /* jcc.h is for mutex semapores only */
851 #endif /* def FEATURE_PTHREAD */
856 #include "jbsockets.h"
857 #include "miscutil.h"
862 #ifndef HAVE_STRPTIME
863 #include "strptime.h"
866 const char parsers_h_rcs[] = PARSERS_H_VERSION;
868 /* Fix a problem with Solaris. There should be no effect on other
870 * Solaris's isspace() is a macro which uses its argument directly
871 * as an array index. Therefore we need to make sure that high-bit
872 * characters generate +ve values, and ideally we also want to make
873 * the argument match the declared parameter type of "int".
875 * Why did they write a character function that can't take a simple
876 * "char" argument? Doh!
878 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
879 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
881 static char *get_header_line(struct iob *iob);
882 static jb_err scan_headers(struct client_state *csp);
883 static jb_err header_tagger(struct client_state *csp, char *header);
884 static jb_err parse_header_time(const char *header_time, time_t *result);
886 static jb_err crumble (struct client_state *csp, char **header);
887 static jb_err connection (struct client_state *csp, char **header);
888 static jb_err filter_header (struct client_state *csp, char **header);
889 static jb_err client_referrer (struct client_state *csp, char **header);
890 static jb_err client_uagent (struct client_state *csp, char **header);
891 static jb_err client_ua (struct client_state *csp, char **header);
892 static jb_err client_from (struct client_state *csp, char **header);
893 static jb_err client_send_cookie (struct client_state *csp, char **header);
894 static jb_err client_x_forwarded (struct client_state *csp, char **header);
895 static jb_err client_accept_encoding (struct client_state *csp, char **header);
896 static jb_err client_te (struct client_state *csp, char **header);
897 static jb_err client_max_forwards (struct client_state *csp, char **header);
898 static jb_err client_host (struct client_state *csp, char **header);
899 static jb_err client_if_modified_since (struct client_state *csp, char **header);
900 static jb_err client_accept_language (struct client_state *csp, char **header);
901 static jb_err client_if_none_match (struct client_state *csp, char **header);
902 static jb_err crunch_client_header (struct client_state *csp, char **header);
903 static jb_err client_x_filter (struct client_state *csp, char **header);
904 static jb_err client_range (struct client_state *csp, char **header);
905 static jb_err server_set_cookie (struct client_state *csp, char **header);
906 static jb_err server_content_type (struct client_state *csp, char **header);
907 static jb_err server_content_length (struct client_state *csp, char **header);
908 static jb_err server_content_md5 (struct client_state *csp, char **header);
909 static jb_err server_content_encoding (struct client_state *csp, char **header);
910 static jb_err server_transfer_coding (struct client_state *csp, char **header);
911 static jb_err server_http (struct client_state *csp, char **header);
912 static jb_err crunch_server_header (struct client_state *csp, char **header);
913 static jb_err server_last_modified (struct client_state *csp, char **header);
914 static jb_err server_content_disposition(struct client_state *csp, char **header);
916 static jb_err client_host_adder (struct client_state *csp);
917 static jb_err client_xtra_adder (struct client_state *csp);
918 static jb_err connection_close_adder (struct client_state *csp);
920 static jb_err create_forged_referrer(char **header, const char *hostport);
921 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
922 static jb_err handle_conditional_hide_referrer_parameter(char **header,
923 const char *host, const int parameter_conditional_block);
926 * List of functions to run on a list of headers.
930 /** The header prefix to match */
933 /** The length of the prefix to match */
936 /** The function to apply to this line */
937 const parser_func_ptr parser;
940 static const struct parsers client_patterns[] = {
941 { "referer:", 8, client_referrer },
942 { "user-agent:", 11, client_uagent },
943 { "ua-", 3, client_ua },
944 { "from:", 5, client_from },
945 { "cookie:", 7, client_send_cookie },
946 { "x-forwarded-for:", 16, client_x_forwarded },
947 { "Accept-Encoding:", 16, client_accept_encoding },
948 { "TE:", 3, client_te },
949 { "Host:", 5, client_host },
950 { "if-modified-since:", 18, client_if_modified_since },
951 { "Keep-Alive:", 11, crumble },
952 { "connection:", 11, connection },
953 { "proxy-connection:", 17, crumble },
954 { "max-forwards:", 13, client_max_forwards },
955 { "Accept-Language:", 16, client_accept_language },
956 { "if-none-match:", 14, client_if_none_match },
957 { "Range:", 6, client_range },
958 { "Request-Range:", 14, client_range },
959 { "If-Range:", 9, client_range },
960 { "X-Filter:", 9, client_x_filter },
961 { "*", 0, crunch_client_header },
962 { "*", 0, filter_header },
966 static const struct parsers server_patterns[] = {
967 { "HTTP/", 5, server_http },
968 { "set-cookie:", 11, server_set_cookie },
969 { "connection:", 11, connection },
970 { "Content-Type:", 13, server_content_type },
971 { "Content-MD5:", 12, server_content_md5 },
972 { "Content-Encoding:", 17, server_content_encoding },
973 { "Transfer-Encoding:", 18, server_transfer_coding },
974 { "Keep-Alive:", 11, crumble },
975 { "content-disposition:", 20, server_content_disposition },
976 { "Last-Modified:", 14, server_last_modified },
977 { "*", 0, crunch_server_header },
978 { "*", 0, filter_header },
982 static const add_header_func_ptr add_client_headers[] = {
985 /* Temporarily disabled: client_accept_encoding_adder, */
986 connection_close_adder,
990 static const add_header_func_ptr add_server_headers[] = {
991 connection_close_adder,
995 /*********************************************************************
997 * Function : flush_socket
999 * Description : Write any pending "buffered" content.
1002 * 1 : fd = file descriptor of the socket to read
1003 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1005 * Returns : On success, the number of bytes written are returned (zero
1006 * indicates nothing was written). On error, -1 is returned,
1007 * and errno is set appropriately. If count is zero and the
1008 * file descriptor refers to a regular file, 0 will be
1009 * returned without causing any other effect. For a special
1010 * file, the results are not portable.
1012 *********************************************************************/
1013 int flush_socket(jb_socket fd, struct iob *iob)
1015 int len = iob->eod - iob->cur;
1022 if (write_socket(fd, iob->cur, (size_t)len))
1026 iob->eod = iob->cur = iob->buf;
1032 /*********************************************************************
1034 * Function : add_to_iob
1036 * Description : Add content to the buffered page, expanding the
1037 * buffer if necessary.
1040 * 1 : csp = Current client state (buffers, headers, etc...)
1041 * 2 : buf = holds the content to be added to the page
1042 * 3 : n = number of bytes to be added
1044 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1045 * or buffer limit reached.
1047 *********************************************************************/
1048 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1050 struct iob *iob = csp->iob;
1051 size_t used, offset, need, want;
1054 if (n <= 0) return JB_ERR_OK;
1056 used = (size_t)(iob->eod - iob->buf);
1057 offset = (size_t)(iob->cur - iob->buf);
1058 need = used + (size_t)n + 1;
1061 * If the buffer can't hold the new data, extend it first.
1062 * Use the next power of two if possible, else use the actual need.
1064 if (need > csp->config->buffer_limit)
1066 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1067 return JB_ERR_MEMORY;
1070 if (need > iob->size)
1072 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1074 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1078 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1084 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1085 return JB_ERR_MEMORY;
1088 /* Update the iob pointers */
1089 iob->cur = p + offset;
1090 iob->eod = p + used;
1094 /* copy the new data into the iob buffer */
1095 memcpy(iob->eod, buf, (size_t)n);
1097 /* point to the end of the data */
1100 /* null terminate == cheap insurance */
1109 /*********************************************************************
1111 * Function : decompress_iob
1113 * Description : Decompress buffered page, expanding the
1114 * buffer as necessary. csp->iob->cur
1115 * should point to the the beginning of the
1116 * compressed data block.
1119 * 1 : csp = Current client state (buffers, headers, etc...)
1121 * Returns : JB_ERR_OK on success,
1122 * JB_ERR_MEMORY if out-of-memory limit reached, and
1123 * JB_ERR_COMPRESS if error decompressing buffer.
1125 *********************************************************************/
1126 jb_err decompress_iob(struct client_state *csp)
1128 char *buf; /* new, uncompressed buffer */
1129 char *cur; /* Current iob position (to keep the original
1130 * iob->cur unmodified if we return early) */
1131 size_t bufsize; /* allocated size of the new buffer */
1132 size_t old_size; /* Content size before decompression */
1133 size_t skip_size; /* Number of bytes at the beginning of the iob
1134 that we should NOT decompress. */
1135 int status; /* return status of the inflate() call */
1136 z_stream zstr; /* used by calls to zlib */
1138 assert(csp->iob->cur - csp->iob->buf > 0);
1139 assert(csp->iob->eod - csp->iob->cur > 0);
1141 bufsize = csp->iob->size;
1142 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1143 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1145 cur = csp->iob->cur;
1150 * This is to protect the parsing of gzipped data,
1151 * but it should(?) be valid for deflated data also.
1153 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1154 return JB_ERR_COMPRESS;
1157 if (csp->content_type & CT_GZIP)
1160 * Our task is slightly complicated by the facts that data
1161 * compressed by gzip does not include a zlib header, and
1162 * that there is no easily accessible interface in zlib to
1163 * handle a gzip header. We strip off the gzip header by
1164 * hand, and later inform zlib not to expect a header.
1168 * Strip off the gzip header. Please see RFC 1952 for more
1169 * explanation of the appropriate fields.
1171 if ((*cur++ != (char)0x1f)
1172 || (*cur++ != (char)0x8b)
1173 || (*cur++ != Z_DEFLATED))
1175 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1176 return JB_ERR_COMPRESS;
1182 * XXX: These magic numbers should be replaced
1183 * with macros to give a better idea what they do.
1187 /* The gzip header has reserved bits set; bail out. */
1188 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1189 return JB_ERR_COMPRESS;
1193 /* Skip extra fields if necessary. */
1197 * Skip a given number of bytes, specified
1198 * as a 16-bit little-endian value.
1201 * XXX: This code used to be:
1203 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1205 * which I had to change into:
1207 * cur += *cur++ + (*cur++ << 8);
1209 * at which point gcc43 finally noticed that the value
1210 * of cur is undefined (it depends on which of the
1211 * summands is evaluated first).
1213 * I haven't come across a site where this
1214 * code is actually executed yet, but I hope
1218 skip_bytes = *cur++;
1219 skip_bytes = *cur++ << 8;
1221 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1224 * The number of bytes to skip should be positive
1225 * and we'd like to stay in the buffer.
1227 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1229 log_error(LOG_LEVEL_ERROR,
1230 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1232 return JB_ERR_COMPRESS;
1234 log_error(LOG_LEVEL_INFO,
1235 "Skipping %d bytes for gzip compression. Does this sound right?",
1240 /* Skip the filename if necessary. */
1243 /* A null-terminated string is supposed to follow. */
1244 while (*cur++ && (cur < csp->iob->eod));
1248 /* Skip the comment if necessary. */
1251 /* A null-terminated string is supposed to follow. */
1252 while (*cur++ && (cur < csp->iob->eod));
1255 /* Skip the CRC if necessary. */
1261 if (cur >= csp->iob->eod)
1264 * If the current position pointer reached or passed
1265 * the buffer end, we were obviously tricked to skip
1268 log_error(LOG_LEVEL_ERROR,
1269 "Malformed gzip header detected. Aborting decompression.");
1270 return JB_ERR_COMPRESS;
1274 else if (csp->content_type & CT_DEFLATE)
1277 * XXX: The debug level should be lowered
1278 * before the next stable release.
1280 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1282 * In theory (that is, according to RFC 1950), deflate-compressed
1283 * data should begin with a two-byte zlib header and have an
1284 * adler32 checksum at the end. It seems that in practice only
1285 * the raw compressed data is sent. Note that this means that
1286 * we are not RFC 1950-compliant here, but the advantage is that
1287 * this actually works. :)
1289 * We add a dummy null byte to tell zlib where the data ends,
1290 * and later inform it not to expect a header.
1292 * Fortunately, add_to_iob() has thoughtfully null-terminated
1293 * the buffer; we can just increment the end pointer to include
1300 log_error(LOG_LEVEL_ERROR,
1301 "Unable to determine compression format for decompression");
1302 return JB_ERR_COMPRESS;
1305 /* Set up the fields required by zlib. */
1306 zstr.next_in = (Bytef *)cur;
1307 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1308 zstr.zalloc = Z_NULL;
1309 zstr.zfree = Z_NULL;
1310 zstr.opaque = Z_NULL;
1313 * Passing -MAX_WBITS to inflateInit2 tells the library
1314 * that there is no zlib header.
1316 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1318 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1319 return JB_ERR_COMPRESS;
1323 * Next, we allocate new storage for the inflated data.
1324 * We don't modify the existing iob yet, so in case there
1325 * is error in decompression we can recover gracefully.
1327 buf = zalloc(bufsize);
1330 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1331 return JB_ERR_MEMORY;
1334 assert(bufsize >= skip_size);
1335 memcpy(buf, csp->iob->buf, skip_size);
1336 zstr.avail_out = bufsize - skip_size;
1337 zstr.next_out = (Bytef *)buf + skip_size;
1339 /* Try to decompress the whole stream in one shot. */
1340 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1342 /* We need to allocate more memory for the output buffer. */
1344 char *tmpbuf; /* used for realloc'ing the buffer */
1345 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1348 * If zlib wants more data then there's a problem, because
1349 * the complete compressed file should have been buffered.
1351 if (0 == zstr.avail_in)
1353 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1354 return JB_ERR_COMPRESS;
1358 * If we tried the limit and still didn't have enough
1359 * memory, just give up.
1361 if (bufsize == csp->config->buffer_limit)
1363 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1364 return JB_ERR_MEMORY;
1367 /* Try doubling the buffer size each time. */
1370 /* Don't exceed the buffer limit. */
1371 if (bufsize > csp->config->buffer_limit)
1373 bufsize = csp->config->buffer_limit;
1376 /* Try to allocate the new buffer. */
1377 tmpbuf = realloc(buf, bufsize);
1380 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1382 return JB_ERR_MEMORY;
1386 char *oldnext_out = (char *)zstr.next_out;
1389 * Update the fields for inflate() to use the new
1390 * buffer, which may be in a location different from
1393 zstr.avail_out += bufsize - oldbufsize;
1394 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1397 * Compare with an uglier method of calculating these values
1398 * that doesn't require the extra oldbufsize variable.
1400 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1401 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1402 assert(zstr.avail_out > 0);
1408 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1410 log_error(LOG_LEVEL_ERROR,
1411 "Inconsistent stream state after decompression: %s", zstr.msg);
1413 * XXX: Intentionally no return.
1415 * According to zlib.h, Z_STREAM_ERROR is returned
1416 * "if the stream state was inconsistent".
1418 * I assume in this case inflate()'s status
1419 * would also be something different than Z_STREAM_END
1420 * so this check should be redundant, but lets see.
1424 if (status != Z_STREAM_END)
1426 /* We failed to decompress the stream. */
1427 log_error(LOG_LEVEL_ERROR,
1428 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1429 return JB_ERR_COMPRESS;
1433 * Finally, we can actually update the iob, since the
1434 * decompression was successful. First, free the old
1437 freez(csp->iob->buf);
1439 /* Now, update the iob to use the new buffer. */
1440 csp->iob->buf = buf;
1441 csp->iob->cur = csp->iob->buf + skip_size;
1442 csp->iob->eod = (char *)zstr.next_out;
1443 csp->iob->size = bufsize;
1446 * Make sure the new uncompressed iob obeys some minimal
1447 * consistency conditions.
1449 if ((csp->iob->buf < csp->iob->cur)
1450 && (csp->iob->cur <= csp->iob->eod)
1451 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1453 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1456 log_error(LOG_LEVEL_RE_FILTER,
1457 "Decompression successful. Old size: %d, new size: %d.",
1458 old_size, new_size);
1462 /* zlib thinks this is OK, so lets do the same. */
1463 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1468 /* It seems that zlib did something weird. */
1469 log_error(LOG_LEVEL_ERROR,
1470 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1471 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1472 csp->iob->eod, csp->iob->buf + csp->iob->size);
1473 return JB_ERR_COMPRESS;
1479 #endif /* defined(FEATURE_ZLIB) */
1482 /*********************************************************************
1484 * Function : string_move
1486 * Description : memmove wrapper to move the last part of a string
1487 * towards the beginning, overwriting the part in
1488 * the middle. strlcpy() can't be used here as the
1492 * 1 : dst = Destination to overwrite
1493 * 2 : src = Source to move.
1497 *********************************************************************/
1498 static void string_move(char *dst, char *src)
1502 /* +1 to copy the terminating nul as well. */
1503 memmove(dst, src, strlen(src)+1);
1507 /*********************************************************************
1509 * Function : normalize_lws
1511 * Description : Reduces unquoted linear white space in headers
1512 * to a single space in accordance with RFC 2616 2.2.
1513 * This simplifies parsing and filtering later on.
1515 * XXX: Remove log messages before
1516 * the next stable release?
1519 * 1 : header = A header with linear white space to reduce.
1523 *********************************************************************/
1524 static void normalize_lws(char *header)
1530 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1534 while (ijb_isspace(*q))
1538 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1539 string_move(p+1, q);
1544 log_error(LOG_LEVEL_HEADER,
1545 "Converting tab to space in '%s'", header);
1550 char *end_of_token = strstr(p+1, "\"");
1552 if (NULL != end_of_token)
1554 /* Don't mess with quoted text. */
1559 log_error(LOG_LEVEL_HEADER,
1560 "Ignoring single quote in '%s'", header);
1566 p = strchr(header, ':');
1567 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1570 * There's still space before the colon.
1573 string_move(p-1, p);
1578 /*********************************************************************
1580 * Function : get_header
1582 * Description : This (odd) routine will parse the csp->iob
1583 * to get the next complete header.
1586 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1588 * Returns : Any one of the following:
1590 * 1) a pointer to a dynamically allocated string that contains a header line
1591 * 2) NULL indicating that the end of the header was reached
1592 * 3) "" indicating that the end of the iob was reached before finding
1593 * a complete header line.
1595 *********************************************************************/
1596 char *get_header(struct iob *iob)
1600 header = get_header_line(iob);
1602 if ((header == NULL) || (*header == '\0'))
1605 * No complete header read yet, tell the client.
1610 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1613 * Header spans multiple lines, append the next one.
1615 char *continued_header;
1617 continued_header = get_header_line(iob);
1618 if ((continued_header == NULL) || (*continued_header == '\0'))
1621 * No complete header read yet, return what we got.
1622 * XXX: Should "unread" header instead.
1624 log_error(LOG_LEVEL_INFO,
1625 "Failed to read a multi-line header properly: '%s'",
1630 if (JB_ERR_OK != string_join(&header, continued_header))
1632 log_error(LOG_LEVEL_FATAL,
1633 "Out of memory while appending multiple headers.");
1637 /* XXX: remove before next stable release. */
1638 log_error(LOG_LEVEL_HEADER,
1639 "Merged multiple header lines to: '%s'",
1644 normalize_lws(header);
1651 /*********************************************************************
1653 * Function : get_header_line
1655 * Description : This (odd) routine will parse the csp->iob
1656 * to get the next header line.
1659 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1661 * Returns : Any one of the following:
1663 * 1) a pointer to a dynamically allocated string that contains a header line
1664 * 2) NULL indicating that the end of the header was reached
1665 * 3) "" indicating that the end of the iob was reached before finding
1666 * a complete header line.
1668 *********************************************************************/
1669 static char *get_header_line(struct iob *iob)
1673 if ((iob->cur == NULL)
1674 || ((p = strchr(iob->cur, '\n')) == NULL))
1676 return(""); /* couldn't find a complete header */
1681 ret = strdup(iob->cur);
1684 /* FIXME No way to handle error properly */
1685 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1690 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1692 /* is this a blank line (i.e. the end of the header) ? */
1704 /*********************************************************************
1706 * Function : get_header_value
1708 * Description : Get the value of a given header from a chained list
1709 * of header lines or return NULL if no such header is
1710 * present in the list.
1713 * 1 : header_list = pointer to list
1714 * 2 : header_name = string with name of header to look for.
1715 * Trailing colon required, capitalization
1718 * Returns : NULL if not found, else value of header
1720 *********************************************************************/
1721 char *get_header_value(const struct list *header_list, const char *header_name)
1723 struct list_entry *cur_entry;
1727 assert(header_list);
1728 assert(header_name);
1729 length = strlen(header_name);
1731 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1735 if (!strncmpic(cur_entry->str, header_name, length))
1738 * Found: return pointer to start of value
1740 ret = (char *) (cur_entry->str + length);
1741 while (*ret && ijb_isspace(*ret)) ret++;
1755 /*********************************************************************
1757 * Function : scan_headers
1759 * Description : Scans headers, applies tags and updates action bits.
1762 * 1 : csp = Current client state (buffers, headers, etc...)
1764 * Returns : JB_ERR_OK
1766 *********************************************************************/
1767 static jb_err scan_headers(struct client_state *csp)
1769 struct list_entry *h; /* Header */
1770 jb_err err = JB_ERR_OK;
1772 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1774 /* Header crunch()ed in previous run? -> ignore */
1775 if (h->str == NULL) continue;
1776 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1777 err = header_tagger(csp, h->str);
1784 /*********************************************************************
1788 * Description : add, delete or modify lines in the HTTP header streams.
1789 * On entry, it receives a linked list of headers space
1790 * that was allocated dynamically (both the list nodes
1791 * and the header contents).
1793 * As a side effect it frees the space used by the original
1797 * 1 : csp = Current client state (buffers, headers, etc...)
1798 * 2 : filter_server_headers = Boolean to switch between
1799 * server and header filtering.
1801 * Returns : JB_ERR_OK in case off success, or
1802 * JB_ERR_MEMORY on out-of-memory error.
1804 *********************************************************************/
1805 jb_err sed(struct client_state *csp, int filter_server_headers)
1807 /* XXX: use more descriptive names. */
1808 struct list_entry *p;
1809 const struct parsers *v;
1810 const add_header_func_ptr *f;
1811 jb_err err = JB_ERR_OK;
1813 if (filter_server_headers)
1815 v = server_patterns;
1816 f = add_server_headers;
1820 v = client_patterns;
1821 f = add_client_headers;
1826 while ((err == JB_ERR_OK) && (v->str != NULL))
1828 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1830 /* Header crunch()ed in previous run? -> ignore */
1831 if (p->str == NULL) continue;
1833 /* Does the current parser handle this header? */
1834 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1835 (v->len == CHECK_EVERY_HEADER_REMAINING))
1837 err = v->parser(csp, &(p->str));
1843 /* place additional headers on the csp->headers list */
1844 while ((err == JB_ERR_OK) && (*f))
1854 /*********************************************************************
1856 * Function : update_server_headers
1858 * Description : Updates server headers after the body has been modified.
1861 * 1 : csp = Current client state (buffers, headers, etc...)
1863 * Returns : JB_ERR_OK in case off success, or
1864 * JB_ERR_MEMORY on out-of-memory error.
1866 *********************************************************************/
1867 jb_err update_server_headers(struct client_state *csp)
1869 jb_err err = JB_ERR_OK;
1871 static const struct parsers server_patterns_light[] = {
1872 { "Content-Length:", 15, server_content_length },
1873 { "Transfer-Encoding:", 18, server_transfer_coding },
1875 { "Content-Encoding:", 17, server_content_encoding },
1876 #endif /* def FEATURE_ZLIB */
1880 if (strncmpic(csp->http->cmd, "HEAD", 4))
1882 const struct parsers *v;
1883 struct list_entry *p;
1885 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1887 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1889 /* Header crunch()ed in previous run? -> ignore */
1890 if (p->str == NULL) continue;
1892 /* Does the current parser handle this header? */
1893 if (strncmpic(p->str, v->str, v->len) == 0)
1895 err = v->parser(csp, (char **)&(p->str));
1905 /*********************************************************************
1907 * Function : header_tagger
1909 * Description : Executes all text substitutions from applying
1910 * tag actions and saves the result as tag.
1912 * XXX: Shares enough code with filter_header() and
1913 * pcrs_filter_response() to warrant some helper functions.
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * 2 : header = Header that is used as tagger input
1919 * Returns : JB_ERR_OK on success and always succeeds
1921 *********************************************************************/
1922 static jb_err header_tagger(struct client_state *csp, char *header)
1924 int wanted_filter_type;
1925 int multi_action_index;
1929 struct file_list *fl;
1930 struct re_filterfile_spec *b;
1931 struct list_entry *tag_name;
1933 int found_filters = 0;
1934 const size_t header_length = strlen(header);
1936 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1938 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1939 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1943 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1944 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1947 /* Check if there are any filters */
1948 for (i = 0; i < MAX_AF_FILES; i++)
1961 if (0 == found_filters)
1963 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1964 "tagging enabled, but no taggers available.");
1968 for (i = 0; i < MAX_AF_FILES; i++)
1971 if ((NULL == fl) || (NULL == fl->f))
1974 * Either there are no filter files
1975 * left, or this filter file just
1976 * contains no valid filters.
1978 * Continue to be sure we don't miss
1979 * valid filter files that are chained
1980 * after empty or invalid ones.
1985 /* For all filters, */
1986 for (b = fl->f; b; b = b->next)
1988 if (b->type != wanted_filter_type)
1990 /* skip the ones we don't care about, */
1993 /* leaving only taggers that could apply, of which we use the ones, */
1994 for (tag_name = csp->action->multi[multi_action_index]->first;
1995 NULL != tag_name; tag_name = tag_name->next)
1997 /* that do apply, and */
1998 if (strcmp(b->name, tag_name->str) == 0)
2000 char *modified_tag = NULL;
2002 size_t size = header_length;
2003 pcrs_job *joblist = b->joblist;
2005 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2007 if (NULL == joblist)
2009 log_error(LOG_LEVEL_RE_FILTER,
2010 "Tagger %s has empty joblist. Nothing to do.", b->name);
2014 /* execute their pcrs_joblist on the header. */
2015 for (job = joblist; NULL != job; job = job->next)
2017 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2021 /* Success, continue with the modified version. */
2030 /* Tagger doesn't match */
2033 /* Regex failure, log it but continue anyway. */
2034 log_error(LOG_LEVEL_ERROR,
2035 "Problems with tagger \'%s\' and header \'%s\': %s",
2036 b->name, *header, pcrs_strerror(hits));
2038 freez(modified_tag);
2042 if (b->dynamic) pcrs_free_joblist(joblist);
2044 /* If this tagger matched */
2050 * There is to technical limitation which makes
2051 * it impossible to use empty tags, but I assume
2052 * no one would do it intentionally.
2055 log_error(LOG_LEVEL_INFO,
2056 "Tagger \'%s\' created an empty tag. Ignored.",
2061 if (!list_contains_item(csp->tags, tag))
2063 if (JB_ERR_OK != enlist(csp->tags, tag))
2065 log_error(LOG_LEVEL_ERROR,
2066 "Insufficient memory to add tag \'%s\', "
2067 "based on tagger \'%s\' and header \'%s\'",
2068 tag, b->name, *header);
2072 char *action_message;
2074 * update the action bits right away, to make
2075 * tagging based on tags set by earlier taggers
2076 * of the same kind possible.
2078 if (update_action_bits_for_tag(csp, tag))
2080 action_message = "Action bits updated accordingly.";
2084 action_message = "No action bits update necessary.";
2087 log_error(LOG_LEVEL_HEADER,
2088 "Tagger \'%s\' added tag \'%s\'. %s",
2089 b->name, tag, action_message);
2094 /* XXX: Is this log-worthy? */
2095 log_error(LOG_LEVEL_HEADER,
2096 "Tagger \'%s\' didn't add tag \'%s\'. "
2097 "Tag already present", b->name, tag);
2100 } /* if the tagger matched */
2101 } /* if the tagger applies */
2102 } /* for every tagger that could apply */
2103 } /* for all filters */
2104 } /* for all filter files */
2109 /* here begins the family of parser functions that reformat header lines */
2111 /*********************************************************************
2113 * Function : filter_header
2115 * Description : Executes all text substitutions from all applying
2116 * +(server|client)-header-filter actions on the header.
2117 * Most of the code was copied from pcrs_filter_response,
2118 * including the rather short variable names
2121 * 1 : csp = Current client state (buffers, headers, etc...)
2122 * 2 : header = On input, pointer to header to modify.
2123 * On output, pointer to the modified header, or NULL
2124 * to remove the header. This function frees the
2125 * original string if necessary.
2127 * Returns : JB_ERR_OK on success and always succeeds
2129 *********************************************************************/
2130 static jb_err filter_header(struct client_state *csp, char **header)
2134 size_t size = strlen(*header);
2136 char *newheader = NULL;
2139 struct file_list *fl;
2140 struct re_filterfile_spec *b;
2141 struct list_entry *filtername;
2143 int i, found_filters = 0;
2144 int wanted_filter_type;
2145 int multi_action_index;
2147 if (csp->flags & CSP_FLAG_NO_FILTERING)
2152 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2154 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2155 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2159 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2160 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2164 * Need to check the set of re_filterfiles...
2166 for (i = 0; i < MAX_AF_FILES; i++)
2179 if (0 == found_filters)
2181 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2182 "header filtering enabled, but no matching filters available.");
2186 for (i = 0; i < MAX_AF_FILES; i++)
2189 if ((NULL == fl) || (NULL == fl->f))
2192 * Either there are no filter files
2193 * left, or this filter file just
2194 * contains no valid filters.
2196 * Continue to be sure we don't miss
2197 * valid filter files that are chained
2198 * after empty or invalid ones.
2203 * For all applying +filter actions, look if a filter by that
2204 * name exists and if yes, execute its pcrs_joblist on the
2207 for (b = fl->f; b; b = b->next)
2209 if (b->type != wanted_filter_type)
2211 /* Skip other filter types */
2215 for (filtername = csp->action->multi[multi_action_index]->first;
2216 filtername ; filtername = filtername->next)
2218 if (strcmp(b->name, filtername->str) == 0)
2220 int current_hits = 0;
2221 pcrs_job *joblist = b->joblist;
2223 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2225 if (NULL == joblist)
2227 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2231 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2232 *header, size, b->name);
2234 /* Apply all jobs from the joblist */
2235 for (job = joblist; NULL != job; job = job->next)
2237 matches = pcrs_execute(job, *header, size, &newheader, &size);
2240 current_hits += matches;
2241 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2243 *header = newheader;
2245 else if ( 0 == matches )
2247 /* Filter doesn't change header */
2253 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2254 *header, b->name, pcrs_strerror(matches));
2255 if (newheader != NULL)
2257 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2263 if (b->dynamic) pcrs_free_joblist(joblist);
2265 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2266 hits += current_hits;
2273 * Additionally checking for hits is important because if
2274 * the continue hack is triggered, server headers can
2275 * arrive empty to separate multiple heads from each other.
2277 if ((0 == size) && hits)
2279 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2287 /*********************************************************************
2289 * Function : connection
2291 * Description : Makes sure that the value of the Connection: header
2292 * is "close" and signals connection_close_adder
2296 * 1 : csp = Current client state (buffers, headers, etc...)
2297 * 2 : header = On input, pointer to header to modify.
2298 * On output, pointer to the modified header, or NULL
2299 * to remove the header. This function frees the
2300 * original string if necessary.
2302 * Returns : JB_ERR_OK on success, or
2303 * JB_ERR_MEMORY on out-of-memory error.
2305 *********************************************************************/
2306 static jb_err connection(struct client_state *csp, char **header)
2308 char *old_header = *header;
2310 /* Do we have a 'Connection: close' header? */
2311 if (strcmpic(*header, "Connection: close"))
2313 /* No, create one */
2314 *header = strdup("Connection: close");
2317 return JB_ERR_MEMORY;
2319 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2323 /* Signal connection_close_adder() to return early. */
2324 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2326 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2330 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2337 /*********************************************************************
2339 * Function : crumble
2341 * Description : This is called if a header matches a pattern to "crunch"
2344 * 1 : csp = Current client state (buffers, headers, etc...)
2345 * 2 : header = On input, pointer to header to modify.
2346 * On output, pointer to the modified header, or NULL
2347 * to remove the header. This function frees the
2348 * original string if necessary.
2350 * Returns : JB_ERR_OK on success, or
2351 * JB_ERR_MEMORY on out-of-memory error.
2353 *********************************************************************/
2354 static jb_err crumble(struct client_state *csp, char **header)
2356 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2362 /*********************************************************************
2364 * Function : crunch_server_header
2366 * Description : Crunch server header if it matches a string supplied by the
2367 * user. Called from `sed'.
2370 * 1 : csp = Current client state (buffers, headers, etc...)
2371 * 2 : header = On input, pointer to header to modify.
2372 * On output, pointer to the modified header, or NULL
2373 * to remove the header. This function frees the
2374 * original string if necessary.
2376 * Returns : JB_ERR_OK on success and always succeeds
2378 *********************************************************************/
2379 static jb_err crunch_server_header(struct client_state *csp, char **header)
2381 const char *crunch_pattern;
2383 /* Do we feel like crunching? */
2384 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2386 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2388 /* Is the current header the lucky one? */
2389 if (strstr(*header, crunch_pattern))
2391 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2400 /*********************************************************************
2402 * Function : server_content_type
2404 * Description : Set the content-type for filterable types (text/.*,
2405 * .*xml.*, javascript and image/gif) unless filtering has been
2406 * forbidden (CT_TABOO) while parsing earlier headers.
2407 * NOTE: Since text/plain is commonly used by web servers
2408 * for files whose correct type is unknown, we don't
2409 * set CT_TEXT for it.
2412 * 1 : csp = Current client state (buffers, headers, etc...)
2413 * 2 : header = On input, pointer to header to modify.
2414 * On output, pointer to the modified header, or NULL
2415 * to remove the header. This function frees the
2416 * original string if necessary.
2418 * Returns : JB_ERR_OK on success, or
2419 * JB_ERR_MEMORY on out-of-memory error.
2421 *********************************************************************/
2422 static jb_err server_content_type(struct client_state *csp, char **header)
2424 /* Remove header if it isn't the first Content-Type header */
2425 if ((csp->content_type & CT_DECLARED))
2428 * Another, slightly slower, way to see if
2429 * we already parsed another Content-Type header.
2431 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2433 log_error(LOG_LEVEL_ERROR,
2434 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2442 * Signal that the Content-Type has been set.
2444 csp->content_type |= CT_DECLARED;
2446 if (!(csp->content_type & CT_TABOO))
2449 * XXX: The assumption that text/plain is a sign of
2450 * binary data seems to be somewhat unreasonable nowadays
2451 * and should be dropped after 3.0.8 is out.
2453 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2454 || strstr(*header, "xml")
2455 || strstr(*header, "application/x-javascript"))
2457 csp->content_type |= CT_TEXT;
2459 else if (strstr(*header, "image/gif"))
2461 csp->content_type |= CT_GIF;
2466 * Are we messing with the content type?
2468 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2471 * Make sure the user doesn't accidently
2472 * change the content type of binary documents.
2474 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2477 *header = strdup("Content-Type: ");
2478 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2482 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2483 return JB_ERR_MEMORY;
2485 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2489 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2490 "It doesn't look like a content type that should be filtered. "
2491 "Enable force-text-mode if you know what you're doing.", *header);
2499 /*********************************************************************
2501 * Function : server_transfer_coding
2503 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2504 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2505 * - Remove header if body was chunked but has been
2506 * de-chunked for filtering.
2509 * 1 : csp = Current client state (buffers, headers, etc...)
2510 * 2 : header = On input, pointer to header to modify.
2511 * On output, pointer to the modified header, or NULL
2512 * to remove the header. This function frees the
2513 * original string if necessary.
2515 * Returns : JB_ERR_OK on success, or
2516 * JB_ERR_MEMORY on out-of-memory error.
2518 *********************************************************************/
2519 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2522 * Turn off pcrs and gif filtering if body compressed
2524 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2528 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2530 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2531 csp->http->cmd, *header);
2532 #endif /* def FEATURE_ZLIB */
2533 csp->content_type = CT_TABOO;
2537 * Raise flag if body chunked
2539 if (strstr(*header, "chunked"))
2541 csp->flags |= CSP_FLAG_CHUNKED;
2544 * If the body was modified, it has been de-chunked first
2545 * and the header must be removed.
2547 * FIXME: If there is more than one transfer encoding,
2548 * only the "chunked" part should be removed here.
2550 if (csp->flags & CSP_FLAG_MODIFIED)
2552 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2561 /*********************************************************************
2563 * Function : server_content_encoding
2565 * Description : This function is run twice for each request,
2566 * unless FEATURE_ZLIB and filtering are disabled.
2568 * The first run is used to check if the content
2569 * is compressed, if FEATURE_ZLIB is disabled
2570 * filtering is then disabled as well, if FEATURE_ZLIB
2571 * is enabled the content is marked for decompression.
2573 * The second run is used to remove the Content-Encoding
2574 * header if the decompression was successful.
2577 * 1 : csp = Current client state (buffers, headers, etc...)
2578 * 2 : header = On input, pointer to header to modify.
2579 * On output, pointer to the modified header, or NULL
2580 * to remove the header. This function frees the
2581 * original string if necessary.
2583 * Returns : JB_ERR_OK on success, or
2584 * JB_ERR_MEMORY on out-of-memory error.
2586 *********************************************************************/
2587 static jb_err server_content_encoding(struct client_state *csp, char **header)
2590 if ((csp->flags & CSP_FLAG_MODIFIED)
2591 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2594 * We successfully decompressed the content,
2595 * and have to clean the header now, so the
2596 * client no longer expects compressed data..
2598 * XXX: There is a difference between cleaning
2599 * and removing it completely.
2601 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2604 else if (strstr(*header, "gzip"))
2606 /* Mark for gzip decompression */
2607 csp->content_type |= CT_GZIP;
2609 else if (strstr(*header, "deflate"))
2611 /* Mark for zlib decompression */
2612 csp->content_type |= CT_DEFLATE;
2614 else if (strstr(*header, "compress"))
2617 * We can't decompress this; therefore we can't filter
2620 csp->content_type |= CT_TABOO;
2622 #else /* !defined(FEATURE_ZLIB) */
2623 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2626 * Body is compressed, turn off pcrs and gif filtering.
2628 csp->content_type |= CT_TABOO;
2631 * Log a warning if the user expects the content to be filtered.
2633 if ((csp->rlist != NULL) &&
2634 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2636 log_error(LOG_LEVEL_INFO,
2637 "Compressed content detected, content filtering disabled. "
2638 "Consider recompiling Privoxy with zlib support or "
2639 "enable the prevent-compression action.");
2642 #endif /* defined(FEATURE_ZLIB) */
2649 /*********************************************************************
2651 * Function : server_content_length
2653 * Description : Adjust Content-Length header if we modified
2657 * 1 : csp = Current client state (buffers, headers, etc...)
2658 * 2 : header = On input, pointer to header to modify.
2659 * On output, pointer to the modified header, or NULL
2660 * to remove the header. This function frees the
2661 * original string if necessary.
2663 * Returns : JB_ERR_OK on success, or
2664 * JB_ERR_MEMORY on out-of-memory error.
2666 *********************************************************************/
2667 static jb_err server_content_length(struct client_state *csp, char **header)
2669 const size_t max_header_length = 80;
2671 /* Regenerate header if the content was modified. */
2672 if (csp->flags & CSP_FLAG_MODIFIED)
2675 *header = (char *) zalloc(max_header_length);
2676 if (*header == NULL)
2678 return JB_ERR_MEMORY;
2681 snprintf(*header, max_header_length, "Content-Length: %d",
2682 (int)csp->content_length);
2683 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2684 (int)csp->content_length);
2691 /*********************************************************************
2693 * Function : server_content_md5
2695 * Description : Crumble any Content-MD5 headers if the document was
2696 * modified. FIXME: Should we re-compute instead?
2699 * 1 : csp = Current client state (buffers, headers, etc...)
2700 * 2 : header = On input, pointer to header to modify.
2701 * On output, pointer to the modified header, or NULL
2702 * to remove the header. This function frees the
2703 * original string if necessary.
2705 * Returns : JB_ERR_OK on success, or
2706 * JB_ERR_MEMORY on out-of-memory error.
2708 *********************************************************************/
2709 static jb_err server_content_md5(struct client_state *csp, char **header)
2711 if (csp->flags & CSP_FLAG_MODIFIED)
2713 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2721 /*********************************************************************
2723 * Function : server_content_disposition
2725 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2726 * Called from `sed'.
2729 * 1 : csp = Current client state (buffers, headers, etc...)
2730 * 2 : header = On input, pointer to header to modify.
2731 * On output, pointer to the modified header, or NULL
2732 * to remove the header. This function frees the
2733 * original string if necessary.
2735 * Returns : JB_ERR_OK on success, or
2736 * JB_ERR_MEMORY on out-of-memory error.
2738 *********************************************************************/
2739 static jb_err server_content_disposition(struct client_state *csp, char **header)
2744 * Are we messing with the Content-Disposition header?
2746 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2752 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2754 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2757 * Blocking content-disposition header
2759 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2766 * Replacing Content-Disposition header
2769 *header = strdup("Content-Disposition: ");
2770 string_append(header, newval);
2772 if (*header != NULL)
2774 log_error(LOG_LEVEL_HEADER,
2775 "Content-Disposition header crunched and replaced with: %s", *header);
2778 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2782 /*********************************************************************
2784 * Function : server_last_modified
2786 * Description : Changes Last-Modified header to the actual date
2787 * to help hide-if-modified-since.
2788 * Called from `sed'.
2791 * 1 : csp = Current client state (buffers, headers, etc...)
2792 * 2 : header = On input, pointer to header to modify.
2793 * On output, pointer to the modified header, or NULL
2794 * to remove the header. This function frees the
2795 * original string if necessary.
2797 * Returns : JB_ERR_OK on success, or
2798 * JB_ERR_MEMORY on out-of-memory error.
2800 *********************************************************************/
2801 static jb_err server_last_modified(struct client_state *csp, char **header)
2804 char buf[BUFFER_SIZE];
2807 #ifdef HAVE_GMTIME_R
2810 struct tm *timeptr = NULL;
2811 time_t now, last_modified;
2813 long int days, hours, minutes, seconds;
2816 * Are we messing with the Last-Modified header?
2818 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2824 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2826 if (0 == strcmpic(newval, "block") )
2829 * Blocking Last-Modified header. Useless but why not.
2831 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2835 else if (0 == strcmpic(newval, "reset-to-request-time"))
2838 * Setting Last-Modified Header to now.
2840 get_http_time(0, buf, sizeof(buf));
2842 *header = strdup("Last-Modified: ");
2843 string_append(header, buf);
2845 if (*header == NULL)
2847 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2851 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2854 else if (0 == strcmpic(newval, "randomize"))
2856 const char *header_time = *header + sizeof("Last-Modified:");
2858 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2860 #ifdef HAVE_GMTIME_R
2861 timeptr = gmtime_r(&now, &gmt);
2862 #elif FEATURE_PTHREAD
2863 pthread_mutex_lock(&gmtime_mutex);
2864 timeptr = gmtime(&now);
2865 pthread_mutex_unlock(&gmtime_mutex);
2867 timeptr = gmtime(&now);
2869 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2871 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2876 rtime = (long int)difftime(now, last_modified);
2885 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2887 rtime = pick_from_range(rtime);
2888 if (negative) rtime *= -1;
2889 last_modified += rtime;
2890 #ifdef HAVE_GMTIME_R
2891 timeptr = gmtime_r(&last_modified, &gmt);
2892 #elif FEATURE_PTHREAD
2893 pthread_mutex_lock(&gmtime_mutex);
2894 timeptr = gmtime(&last_modified);
2895 pthread_mutex_unlock(&gmtime_mutex);
2897 timeptr = gmtime(&last_modified);
2899 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2901 *header = strdup("Last-Modified: ");
2902 string_append(header, newheader);
2904 if (*header == NULL)
2906 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2907 return JB_ERR_MEMORY;
2910 days = rtime / (3600 * 24);
2911 hours = rtime / 3600 % 24;
2912 minutes = rtime / 60 % 60;
2913 seconds = rtime % 60;
2915 log_error(LOG_LEVEL_HEADER,
2916 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2917 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2918 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2922 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2931 /*********************************************************************
2933 * Function : client_accept_encoding
2935 * Description : Rewrite the client's Accept-Encoding header so that
2936 * if doesn't allow compression, if the action applies.
2937 * Note: For HTTP/1.0 the absence of the header is enough.
2940 * 1 : csp = Current client state (buffers, headers, etc...)
2941 * 2 : header = On input, pointer to header to modify.
2942 * On output, pointer to the modified header, or NULL
2943 * to remove the header. This function frees the
2944 * original string if necessary.
2946 * Returns : JB_ERR_OK on success, or
2947 * JB_ERR_MEMORY on out-of-memory error.
2949 *********************************************************************/
2950 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2952 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2954 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2958 /* Temporarily disable the correct behaviour to
2959 * work around a PHP bug.
2961 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2963 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2964 * if (*header == NULL)
2966 * return JB_ERR_MEMORY;
2977 /*********************************************************************
2979 * Function : client_te
2981 * Description : Rewrite the client's TE header so that
2982 * if doesn't allow compression, if the action applies.
2985 * 1 : csp = Current client state (buffers, headers, etc...)
2986 * 2 : header = On input, pointer to header to modify.
2987 * On output, pointer to the modified header, or NULL
2988 * to remove the header. This function frees the
2989 * original string if necessary.
2991 * Returns : JB_ERR_OK on success, or
2992 * JB_ERR_MEMORY on out-of-memory error.
2994 *********************************************************************/
2995 static jb_err client_te(struct client_state *csp, char **header)
2997 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3000 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3007 /*********************************************************************
3009 * Function : client_referrer
3011 * Description : Handle the "referer" config setting properly.
3012 * Called from `sed'.
3015 * 1 : csp = Current client state (buffers, headers, etc...)
3016 * 2 : header = On input, pointer to header to modify.
3017 * On output, pointer to the modified header, or NULL
3018 * to remove the header. This function frees the
3019 * original string if necessary.
3021 * Returns : JB_ERR_OK on success, or
3022 * JB_ERR_MEMORY on out-of-memory error.
3024 *********************************************************************/
3025 static jb_err client_referrer(struct client_state *csp, char **header)
3027 const char *parameter;
3028 /* booleans for parameters we have to check multiple times */
3029 int parameter_conditional_block;
3030 int parameter_conditional_forge;
3032 #ifdef FEATURE_FORCE_LOAD
3034 * Since the referrer can include the prefix even
3035 * if the request itself is non-forced, we must
3036 * clean it unconditionally.
3038 * XXX: strclean is too broad
3040 strclean(*header, FORCE_PREFIX);
3041 #endif /* def FEATURE_FORCE_LOAD */
3043 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3045 /* Nothing left to do */
3049 parameter = csp->action->string[ACTION_STRING_REFERER];
3050 assert(parameter != NULL);
3051 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3052 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3054 if (!parameter_conditional_block && !parameter_conditional_forge)
3057 * As conditional-block and conditional-forge are the only
3058 * parameters that rely on the original referrer, we can
3059 * remove it now for all the others.
3064 if (0 == strcmpic(parameter, "block"))
3066 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3069 else if (parameter_conditional_block || parameter_conditional_forge)
3071 return handle_conditional_hide_referrer_parameter(header,
3072 csp->http->hostport, parameter_conditional_block);
3074 else if (0 == strcmpic(parameter, "forge"))
3076 return create_forged_referrer(header, csp->http->hostport);
3080 /* interpret parameter as user-supplied referer to fake */
3081 return create_fake_referrer(header, parameter);
3086 /*********************************************************************
3088 * Function : client_accept_language
3090 * Description : Handle the "Accept-Language" config setting properly.
3091 * Called from `sed'.
3094 * 1 : csp = Current client state (buffers, headers, etc...)
3095 * 2 : header = On input, pointer to header to modify.
3096 * On output, pointer to the modified header, or NULL
3097 * to remove the header. This function frees the
3098 * original string if necessary.
3100 * Returns : JB_ERR_OK on success, or
3101 * JB_ERR_MEMORY on out-of-memory error.
3103 *********************************************************************/
3104 static jb_err client_accept_language(struct client_state *csp, char **header)
3109 * Are we messing with the Accept-Language?
3111 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3113 /*I don't think so*/
3117 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3119 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3122 * Blocking Accept-Language header
3124 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3131 * Replacing Accept-Language header
3134 *header = strdup("Accept-Language: ");
3135 string_append(header, newval);
3137 if (*header == NULL)
3139 log_error(LOG_LEVEL_ERROR,
3140 "Insufficient memory. Accept-Language header crunched without replacement.");
3144 log_error(LOG_LEVEL_HEADER,
3145 "Accept-Language header crunched and replaced with: %s", *header);
3148 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3152 /*********************************************************************
3154 * Function : crunch_client_header
3156 * Description : Crunch client header if it matches a string supplied by the
3157 * user. Called from `sed'.
3160 * 1 : csp = Current client state (buffers, headers, etc...)
3161 * 2 : header = On input, pointer to header to modify.
3162 * On output, pointer to the modified header, or NULL
3163 * to remove the header. This function frees the
3164 * original string if necessary.
3166 * Returns : JB_ERR_OK on success and always succeeds
3168 *********************************************************************/
3169 static jb_err crunch_client_header(struct client_state *csp, char **header)
3171 const char *crunch_pattern;
3173 /* Do we feel like crunching? */
3174 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3176 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3178 /* Is the current header the lucky one? */
3179 if (strstr(*header, crunch_pattern))
3181 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3189 /*********************************************************************
3191 * Function : client_uagent
3193 * Description : Handle the "user-agent" config setting properly
3194 * and remember its original value to enable browser
3195 * bug workarounds. Called from `sed'.
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3199 * 2 : header = On input, pointer to header to modify.
3200 * On output, pointer to the modified header, or NULL
3201 * to remove the header. This function frees the
3202 * original string if necessary.
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 static jb_err client_uagent(struct client_state *csp, char **header)
3212 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3217 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3224 *header = strdup("User-Agent: ");
3225 string_append(header, newval);
3227 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3229 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3233 /*********************************************************************
3235 * Function : client_ua
3237 * Description : Handle "ua-" headers properly. Called from `sed'.
3240 * 1 : csp = Current client state (buffers, headers, etc...)
3241 * 2 : header = On input, pointer to header to modify.
3242 * On output, pointer to the modified header, or NULL
3243 * to remove the header. This function frees the
3244 * original string if necessary.
3246 * Returns : JB_ERR_OK on success, or
3247 * JB_ERR_MEMORY on out-of-memory error.
3249 *********************************************************************/
3250 static jb_err client_ua(struct client_state *csp, char **header)
3252 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3254 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3262 /*********************************************************************
3264 * Function : client_from
3266 * Description : Handle the "from" config setting properly.
3267 * Called from `sed'.
3270 * 1 : csp = Current client state (buffers, headers, etc...)
3271 * 2 : header = On input, pointer to header to modify.
3272 * On output, pointer to the modified header, or NULL
3273 * to remove the header. This function frees the
3274 * original string if necessary.
3276 * Returns : JB_ERR_OK on success, or
3277 * JB_ERR_MEMORY on out-of-memory error.
3279 *********************************************************************/
3280 static jb_err client_from(struct client_state *csp, char **header)
3284 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3291 newval = csp->action->string[ACTION_STRING_FROM];
3294 * Are we blocking the e-mail address?
3296 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3298 log_error(LOG_LEVEL_HEADER, "crunched From!");
3302 log_error(LOG_LEVEL_HEADER, " modified");
3304 *header = strdup("From: ");
3305 string_append(header, newval);
3307 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3311 /*********************************************************************
3313 * Function : client_send_cookie
3315 * Description : Crunches the "cookie" header if necessary.
3316 * Called from `sed'.
3318 * XXX: Stupid name, doesn't send squat.
3321 * 1 : csp = Current client state (buffers, headers, etc...)
3322 * 2 : header = On input, pointer to header to modify.
3323 * On output, pointer to the modified header, or NULL
3324 * to remove the header. This function frees the
3325 * original string if necessary.
3327 * Returns : JB_ERR_OK on success, or
3328 * JB_ERR_MEMORY on out-of-memory error.
3330 *********************************************************************/
3331 static jb_err client_send_cookie(struct client_state *csp, char **header)
3333 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3335 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3343 /*********************************************************************
3345 * Function : client_x_forwarded
3347 * Description : Handle the "x-forwarded-for" config setting properly,
3348 * also used in the add_client_headers list. Called from `sed'.
3351 * 1 : csp = Current client state (buffers, headers, etc...)
3352 * 2 : header = On input, pointer to header to modify.
3353 * On output, pointer to the modified header, or NULL
3354 * to remove the header. This function frees the
3355 * original string if necessary.
3357 * Returns : JB_ERR_OK on success, or
3358 * JB_ERR_MEMORY on out-of-memory error.
3360 *********************************************************************/
3361 jb_err client_x_forwarded(struct client_state *csp, char **header)
3363 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3366 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3373 /*********************************************************************
3375 * Function : client_max_forwards
3377 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3378 * from the value of the Max-Forwards header field.
3381 * 1 : csp = Current client state (buffers, headers, etc...)
3382 * 2 : header = On input, pointer to header to modify.
3383 * On output, pointer to the modified header, or NULL
3384 * to remove the header. This function frees the
3385 * original string if necessary.
3387 * Returns : JB_ERR_OK on success, or
3388 * JB_ERR_MEMORY on out-of-memory error.
3390 *********************************************************************/
3391 static jb_err client_max_forwards(struct client_state *csp, char **header)
3395 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3396 (0 == strcmpic(csp->http->gpc, "options")))
3398 assert(*(*header+12) == ':');
3399 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3401 if (max_forwards > 0)
3403 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3404 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3405 csp->http->gpc, max_forwards);
3407 else if (max_forwards < 0)
3409 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3415 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3424 /*********************************************************************
3426 * Function : client_host
3428 * Description : If the request URI did not contain host and
3429 * port information, parse and evaluate the Host
3432 * Also, kill ill-formed HOST: headers as sent by
3433 * Apple's iTunes software when used with a proxy.
3436 * 1 : csp = Current client state (buffers, headers, etc...)
3437 * 2 : header = On input, pointer to header to modify.
3438 * On output, pointer to the modified header, or NULL
3439 * to remove the header. This function frees the
3440 * original string if necessary.
3442 * Returns : JB_ERR_OK on success, or
3443 * JB_ERR_MEMORY on out-of-memory error.
3445 *********************************************************************/
3446 static jb_err client_host(struct client_state *csp, char **header)
3451 * If the header field name is all upper-case, chances are that it's
3452 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3453 * not a problem -- they are regenerated later.
3455 if ((*header)[1] == 'O')
3457 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3462 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3463 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3466 if (NULL == (p = strdup((*header)+6)))
3468 return JB_ERR_MEMORY;
3471 if (NULL == (q = strdup(p)))
3474 return JB_ERR_MEMORY;
3477 freez(csp->http->hostport);
3478 csp->http->hostport = p;
3479 freez(csp->http->host);
3480 csp->http->host = q;
3481 q = strchr(csp->http->host, ':');
3484 /* Terminate hostname and evaluate port string */
3486 csp->http->port = atoi(q);
3490 csp->http->port = csp->http->ssl ? 443 : 80;
3493 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3494 csp->http->hostport, csp->http->host, csp->http->port);
3497 /* Signal client_host_adder() to return right away */
3498 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3504 /*********************************************************************
3506 * Function : client_if_modified_since
3508 * Description : Remove or modify the If-Modified-Since header.
3511 * 1 : csp = Current client state (buffers, headers, etc...)
3512 * 2 : header = On input, pointer to header to modify.
3513 * On output, pointer to the modified header, or NULL
3514 * to remove the header. This function frees the
3515 * original string if necessary.
3517 * Returns : JB_ERR_OK on success, or
3518 * JB_ERR_MEMORY on out-of-memory error.
3520 *********************************************************************/
3521 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3524 #ifdef HAVE_GMTIME_R
3527 struct tm *timeptr = NULL;
3531 long int hours, minutes, seconds;
3535 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3538 * The client got an error message because of a temporary problem,
3539 * the problem is gone and the client now tries to revalidate our
3540 * error message on the real server. The revalidation would always
3541 * end with the transmission of the whole document and there is
3542 * no need to expose the bogus If-Modified-Since header.
3544 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3547 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3549 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3551 if ((0 == strcmpic(newval, "block")))
3553 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3556 else /* add random value */
3558 const char *header_time = *header + sizeof("If-Modified-Since:");
3560 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3562 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3567 rtime = strtol(newval, &endptr, 0);
3570 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3571 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3578 rtime = pick_from_range(rtime);
3582 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3585 tm += rtime * (negative ? -1 : 1);
3586 #ifdef HAVE_GMTIME_R
3587 timeptr = gmtime_r(&tm, &gmt);
3588 #elif FEATURE_PTHREAD
3589 pthread_mutex_lock(&gmtime_mutex);
3590 timeptr = gmtime(&tm);
3591 pthread_mutex_unlock(&gmtime_mutex);
3593 timeptr = gmtime(&tm);
3595 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3598 *header = strdup("If-Modified-Since: ");
3599 string_append(header, newheader);
3601 if (*header == NULL)
3603 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3604 return JB_ERR_MEMORY;
3607 hours = rtime / 3600;
3608 minutes = rtime / 60 % 60;
3609 seconds = rtime % 60;
3611 log_error(LOG_LEVEL_HEADER,
3612 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3613 *header, (negative) ? "subtracted" : "added", hours,
3614 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3615 seconds, (seconds == 1) ? ")" : "s)");
3624 /*********************************************************************
3626 * Function : client_if_none_match
3628 * Description : Remove the If-None-Match header.
3631 * 1 : csp = Current client state (buffers, headers, etc...)
3632 * 2 : header = On input, pointer to header to modify.
3633 * On output, pointer to the modified header, or NULL
3634 * to remove the header. This function frees the
3635 * original string if necessary.
3637 * Returns : JB_ERR_OK on success, or
3638 * JB_ERR_MEMORY on out-of-memory error.
3640 *********************************************************************/
3641 static jb_err client_if_none_match(struct client_state *csp, char **header)
3643 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3645 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3653 /*********************************************************************
3655 * Function : client_x_filter
3657 * Description : Disables filtering if the client set "X-Filter: No".
3658 * Called from `sed'.
3661 * 1 : csp = Current client state (buffers, headers, etc...)
3662 * 2 : header = On input, pointer to header to modify.
3663 * On output, pointer to the modified header, or NULL
3664 * to remove the header. This function frees the
3665 * original string if necessary.
3667 * Returns : JB_ERR_OK on success
3669 *********************************************************************/
3670 jb_err client_x_filter(struct client_state *csp, char **header)
3672 if ( 0 == strcmpic(*header, "X-Filter: No"))
3674 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3676 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3680 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3682 log_error(LOG_LEVEL_HEADER,
3683 "force-text-mode overruled the client's request to fetch without filtering!");
3687 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3688 csp->flags |= CSP_FLAG_NO_FILTERING;
3689 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3691 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3699 /*********************************************************************
3701 * Function : client_range
3703 * Description : Removes Range, Request-Range and If-Range headers if
3704 * content filtering is enabled. If the client's version
3705 * of the document has been altered by Privoxy, the server
3706 * could interpret the range differently than the client
3707 * intended in which case the user could end up with
3708 * corrupted content.
3711 * 1 : csp = Current client state (buffers, headers, etc...)
3712 * 2 : header = On input, pointer to header to modify.
3713 * On output, pointer to the modified header, or NULL
3714 * to remove the header. This function frees the
3715 * original string if necessary.
3717 * Returns : JB_ERR_OK
3719 *********************************************************************/
3720 static jb_err client_range(struct client_state *csp, char **header)
3722 if (content_filters_enabled(csp->action))
3724 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3725 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3732 /* the following functions add headers directly to the header list */
3734 /*********************************************************************
3736 * Function : client_host_adder
3738 * Description : Adds the Host: header field if it is missing.
3739 * Called from `sed'.
3742 * 1 : csp = Current client state (buffers, headers, etc...)
3744 * Returns : JB_ERR_OK on success, or
3745 * JB_ERR_MEMORY on out-of-memory error.
3747 *********************************************************************/
3748 static jb_err client_host_adder(struct client_state *csp)
3753 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3755 /* Header already set by the client, nothing to do. */
3759 if ( !csp->http->hostport || !*(csp->http->hostport))
3761 /* XXX: When does this happen and why is it OK? */
3762 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3767 * remove 'user:pass@' from 'proto://user:pass@host'
3769 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3775 p = csp->http->hostport;
3778 /* XXX: Just add it, we already made sure that it will be unique */
3779 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3780 err = enlist_unique_header(csp->headers, "Host", p);
3787 /*********************************************************************
3789 * Function : client_accept_encoding_adder
3791 * Description : Add an Accept-Encoding header to the client's request
3792 * that disables compression if the action applies, and
3793 * the header is not already there. Called from `sed'.
3794 * Note: For HTTP/1.0, the absence of the header is enough.
3797 * 1 : csp = Current client state (buffers, headers, etc...)
3799 * Returns : JB_ERR_OK on success, or
3800 * JB_ERR_MEMORY on out-of-memory error.
3802 *********************************************************************/
3803 static jb_err client_accept_encoding_adder(struct client_state *csp)
3805 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3806 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3808 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3816 /*********************************************************************
3818 * Function : client_xtra_adder
3820 * Description : Used in the add_client_headers list. Called from `sed'.
3823 * 1 : csp = Current client state (buffers, headers, etc...)
3825 * Returns : JB_ERR_OK on success, or
3826 * JB_ERR_MEMORY on out-of-memory error.
3828 *********************************************************************/
3829 static jb_err client_xtra_adder(struct client_state *csp)
3831 struct list_entry *lst;
3834 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3835 lst ; lst = lst->next)
3837 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3838 err = enlist(csp->headers, lst->str);
3850 /*********************************************************************
3852 * Function : connection_close_adder
3854 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3855 * support. Adds a "Connection: close" header to csp->headers
3856 * unless the header was already present. Called from `sed'.
3858 * FIXME: This whole function shouldn't be neccessary!
3861 * 1 : csp = Current client state (buffers, headers, etc...)
3863 * Returns : JB_ERR_OK on success, or
3864 * JB_ERR_MEMORY on out-of-memory error.
3866 *********************************************************************/
3867 static jb_err connection_close_adder(struct client_state *csp)
3869 const unsigned int flags = csp->flags;
3872 * Return right away if
3874 * - we're parsing server headers and the server header
3875 * "Connection: close" is already set, or if
3877 * - we're parsing client headers and the client header
3878 * "Connection: close" is already set.
3880 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3881 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3882 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3883 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3888 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3890 return enlist(csp->headers, "Connection: close");
3894 /*********************************************************************
3896 * Function : server_http
3898 * Description : - Save the HTTP Status into csp->http->status
3899 * - Set CT_TABOO to prevent filtering if the answer
3900 * is a partial range (HTTP status 206)
3901 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3905 * 1 : csp = Current client state (buffers, headers, etc...)
3906 * 2 : header = On input, pointer to header to modify.
3907 * On output, pointer to the modified header, or NULL
3908 * to remove the header. This function frees the
3909 * original string if necessary.
3911 * Returns : JB_ERR_OK on success, or
3912 * JB_ERR_MEMORY on out-of-memory error.
3914 *********************************************************************/
3915 static jb_err server_http(struct client_state *csp, char **header)
3917 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3918 if (csp->http->status == 206)
3920 csp->content_type = CT_TABOO;
3923 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3925 /* XXX: Should we do a real validity check here? */
3926 if (strlen(*header) > 8)
3929 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3934 * XXX: Should we block the request or
3935 * enlist a valid status code line here?
3937 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3938 "Downgrading to HTTP/1.0 impossible.");
3946 /*********************************************************************
3948 * Function : server_set_cookie
3950 * Description : Handle the server "cookie" header properly.
3951 * Log cookie to the jar file. Then "crunch",
3952 * accept or rewrite it to a session cookie.
3953 * Called from `sed'.
3955 * TODO: Allow the user to specify a new expiration
3956 * time to cause the cookie to expire even before the
3957 * browser is closed.
3960 * 1 : csp = Current client state (buffers, headers, etc...)
3961 * 2 : header = On input, pointer to header to modify.
3962 * On output, pointer to the modified header, or NULL
3963 * to remove the header. This function frees the
3964 * original string if necessary.
3966 * Returns : JB_ERR_OK on success, or
3967 * JB_ERR_MEMORY on out-of-memory error.
3969 *********************************************************************/
3970 static jb_err server_set_cookie(struct client_state *csp, char **header)
3977 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3979 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3982 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3984 /* Flag whether or not to log a message */
3987 /* A variable to store the tag we're working on */
3990 /* Skip "Set-Cookie:" (11 characters) in header */
3991 cur_tag = *header + 11;
3993 /* skip whitespace between "Set-Cookie:" and value */
3994 while (*cur_tag && ijb_isspace(*cur_tag))
3999 /* Loop through each tag in the cookie */
4003 char *next_tag = strchr(cur_tag, ';');
4004 if (next_tag != NULL)
4006 /* Skip the ';' character itself */
4009 /* skip whitespace ";" and start of tag */
4010 while (*next_tag && ijb_isspace(*next_tag))
4017 /* "Next tag" is the end of the string */
4018 next_tag = cur_tag + strlen(cur_tag);
4022 * Check the expiration date to see
4023 * if the cookie is still valid, if yes,
4024 * rewrite it to a session cookie.
4026 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4028 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4030 /* Did we detect the date properly? */
4031 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4034 * Nope, treat it as if it was still valid.
4036 * XXX: Should we remove the whole cookie instead?
4038 log_error(LOG_LEVEL_ERROR,
4039 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4040 string_move(cur_tag, next_tag);
4046 * Yes. Check if the cookie is still valid.
4048 * If the cookie is already expired it's probably
4049 * a delete cookie and even if it isn't, the browser
4050 * will discard it anyway.
4054 * XXX: timegm() isn't available on some AmigaOS
4055 * versions and our replacement doesn't work.
4057 * Our options are to either:
4059 * - disable session-cookies-only completely if timegm
4062 * - to simply remove all expired tags, like it has
4063 * been done until Privoxy 3.0.6 and to live with
4064 * the consequence that it can cause login/logout
4065 * problems on servers that don't validate their
4066 * input properly, or
4068 * - to replace it with mktime in which
4069 * case there is a slight chance of valid cookies
4070 * passing as already expired.
4072 * This is the way it's currently done and it's not
4073 * as bad as it sounds. If the missing GMT offset is
4074 * enough to change the result of the expiration check
4075 * the cookie will be only valid for a few hours
4076 * anyway, which in many cases will be shorter
4077 * than a browser session.
4079 if (cookie_time - now < 0)
4081 log_error(LOG_LEVEL_HEADER,
4082 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4083 /* Just in case some clown sets more then one expiration date */
4089 * Still valid, delete expiration date by copying
4090 * the rest of the string over it.
4092 string_move(cur_tag, next_tag);
4094 /* That changed the header, need to issue a log message */
4098 * Note that the next tag has now been moved to *cur_tag,
4099 * so we do not need to update the cur_tag pointer.
4107 /* Move on to next cookie tag */
4114 assert(NULL != *header);
4115 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4124 #ifdef FEATURE_FORCE_LOAD
4125 /*********************************************************************
4127 * Function : strclean
4129 * Description : In-Situ-Eliminate all occurances of substring in
4133 * 1 : string = string to clean
4134 * 2 : substring = substring to eliminate
4136 * Returns : Number of eliminations
4138 *********************************************************************/
4139 int strclean(char *string, const char *substring)
4145 len = strlen(substring);
4147 while((pos = strstr(string, substring)) != NULL)
4154 while (*p++ != '\0');
4161 #endif /* def FEATURE_FORCE_LOAD */
4164 /*********************************************************************
4166 * Function : parse_header_time
4168 * Description : Parses time formats used in HTTP header strings
4169 * to get the numerical respresentation.
4172 * 1 : header_time = HTTP header time as string.
4173 * 2 : result = storage for header_time in seconds
4175 * Returns : JB_ERR_OK if the time format was recognized, or
4176 * JB_ERR_PARSE otherwise.
4178 *********************************************************************/
4179 static jb_err parse_header_time(const char *header_time, time_t *result)
4184 * Zero out gmt to prevent time zone offsets.
4186 * While this is only necessary on some platforms
4187 * (mingw32 for example), I don't know how to
4188 * detect these automatically and doing it everywhere
4191 memset(&gmt, 0, sizeof(gmt));
4193 /* Tue, 02 Jun 2037 20:00:00 */
4194 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4195 /* Tue, 02-Jun-2037 20:00:00 */
4196 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4197 /* Tue, 02-Jun-37 20:00:00 */
4198 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4199 /* Tuesday, 02-Jun-2037 20:00:00 */
4200 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4201 /* Tuesday Jun 02 20:00:00 2037 */
4202 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4204 return JB_ERR_PARSE;
4207 *result = timegm(&gmt);
4214 /*********************************************************************
4216 * Function : get_destination_from_headers
4218 * Description : Parse the "Host:" header to get the request's destination.
4219 * Only needed if the client's request was forcefully
4220 * redirected into Privoxy.
4222 * Code mainly copied from client_host() which is currently
4223 * run too late for this purpose.
4226 * 1 : headers = List of headers (one of them hopefully being
4227 * the "Host:" header)
4228 * 2 : http = storage for the result (host, port and hostport).
4230 * Returns : JB_ERR_MEMORY in case of memory problems,
4231 * JB_ERR_PARSE if the host header couldn't be found,
4232 * JB_ERR_OK otherwise.
4234 *********************************************************************/
4235 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4241 host = get_header_value(headers, "Host:");
4245 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4246 return JB_ERR_PARSE;
4249 if (NULL == (p = strdup((host))))
4251 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4252 return JB_ERR_MEMORY;
4255 if (NULL == (q = strdup(p)))
4258 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4259 return JB_ERR_MEMORY;
4262 freez(http->hostport);
4266 q = strchr(http->host, ':');
4269 /* Terminate hostname and evaluate port string */
4271 http->port = atoi(q);
4275 http->port = http->ssl ? 443 : 80;
4278 /* Rebuild request URL */
4280 http->url = strdup(http->ssl ? "https://" : "http://");
4281 string_append(&http->url, http->hostport);
4282 string_append(&http->url, http->path);
4283 if (http->url == NULL)
4285 return JB_ERR_MEMORY;
4288 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4296 /*********************************************************************
4298 * Function : create_forged_referrer
4300 * Description : Helper for client_referrer to forge a referer as
4301 * 'http://[hostname:port/' to fool stupid
4302 * checks for in-site links
4305 * 1 : header = Pointer to header pointer
4306 * 2 : hostport = Host and optionally port as string
4308 * Returns : JB_ERR_OK in case of success, or
4309 * JB_ERR_MEMORY in case of memory problems.
4311 *********************************************************************/
4312 static jb_err create_forged_referrer(char **header, const char *hostport)
4314 assert(NULL == *header);
4316 *header = strdup("Referer: http://");
4317 string_append(header, hostport);
4318 string_append(header, "/");
4320 if (NULL == *header)
4322 return JB_ERR_MEMORY;
4325 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4332 /*********************************************************************
4334 * Function : create_fake_referrer
4336 * Description : Helper for client_referrer to create a fake referrer
4337 * based on a string supplied by the user.
4340 * 1 : header = Pointer to header pointer
4341 * 2 : hosthost = Referrer to fake
4343 * Returns : JB_ERR_OK in case of success, or
4344 * JB_ERR_MEMORY in case of memory problems.
4346 *********************************************************************/
4347 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4349 assert(NULL == *header);
4351 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4353 log_error(LOG_LEVEL_HEADER,
4354 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4356 *header = strdup("Referer: ");
4357 string_append(header, fake_referrer);
4359 if (NULL == *header)
4361 return JB_ERR_MEMORY;
4364 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4371 /*********************************************************************
4373 * Function : handle_conditional_hide_referrer_parameter
4375 * Description : Helper for client_referrer to crunch or forge
4376 * the referrer header if the host has changed.
4379 * 1 : header = Pointer to header pointer
4380 * 2 : host = The target host (may include the port)
4381 * 3 : parameter_conditional_block = Boolean to signal
4382 * if we're in conditional-block mode. If not set,
4383 * we're in conditional-forge mode.
4385 * Returns : JB_ERR_OK in case of success, or
4386 * JB_ERR_MEMORY in case of memory problems.
4388 *********************************************************************/
4389 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4390 const char *host, const int parameter_conditional_block)
4392 char *referer = strdup(*header);
4393 const size_t hostlenght = strlen(host);
4395 if (NULL == referer)
4398 return JB_ERR_MEMORY;
4401 /* referer begins with 'Referer: http[s]://' */
4402 if (hostlenght < (strlen(referer)-17))
4405 * Shorten referer to make sure the referer is blocked
4406 * if www.example.org/www.example.com-shall-see-the-referer/
4407 * links to www.example.com/
4409 referer[hostlenght+17] = '\0';
4411 if (NULL == strstr(referer, host))
4413 /* Host has changed */
4414 if (parameter_conditional_block)
4416 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4423 return create_forged_referrer(header, host);