1 const char parsers_rcs[] = "$Id: parsers.c,v 1.140 2008/09/12 17:51:43 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.140 2008/09/12 17:51:43 fabiankeil
48 * - A few style fixes.
49 * - Remove a pointless cast.
51 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
52 * Prepare for critical sections on Windows by adding a
53 * layer of indirection before the pthread mutex functions.
55 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
56 * Remove FEATURE_COOKIE_JAR.
58 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
59 * Remove questionable micro-optimizations
60 * whose usefulness has never been measured.
62 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
63 * s@Insufficent@Insufficient@
65 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
66 * The whole point of strclean() is to modify the
67 * first parameter, so don't mark it immutable,
68 * even though the compiler lets us get away with it.
70 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
71 * As the wafer actions are gone, we can stop including encode.h.
73 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
74 * Ditch cast from (char **) to (char **).
76 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
77 * Streamline sed()'s prototype and declare
78 * the header parse and add structures static.
80 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
81 * Factor update_server_headers() out of sed(), ditch the
82 * first_run hack and make server_patterns_light static.
84 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
85 * Wrap memmove() calls in string_move()
86 * to document the purpose in one place.
88 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
89 * Normalize linear header white space.
91 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
92 * If a header is split across multiple lines,
93 * merge them to a single line before parsing them.
95 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
96 * Don't provide get_header() with the whole client state
97 * structure when it only needs access to csp->iob.
99 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
100 * Change content_filters_enabled()'s parameter from
101 * csp->action to action so it can be also used in the
102 * CGI code. Don't bother checking if there are filters
103 * loaded, as that's somewhat besides the point.
105 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
106 * Provide get_http_time() with the buffer size so it doesn't
107 * have to blindly assume that the buffer is big enough.
109 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
110 * Don't pass the whole csp structure to flush_socket()
111 * when it only needs a file descriptor and a buffer.
113 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
114 * Remove send-wafer and send-vanilla-wafer actions.
116 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
117 * Remove inspect-jpegs action.
119 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
120 * Let client_range() also handle Request-Range headers
121 * which apparently are still supported by many servers.
123 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
124 * Improve the warning messages that get logged if the action files
125 * "enable" filters but no filters of that type have been loaded.
127 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
128 * In server_content_type():
129 * - Don't require leading white space when detecting image content types.
130 * - Change '... not replaced ...' message to sound less crazy if the text
131 * type actually is 'text/plain'.
132 * - Mark the 'text/plain == binary data' assumption for removal.
133 * - Remove a bunch of trailing white space.
135 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
136 * Minor server_content_disposition() changes:
137 * - Don't regenerate the header name all lower-case.
138 * - Some white space fixes.
139 * - Remove useless log message in case of ENOMEM.
141 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
142 * Garbage-collect the code to add a X-Forwarded-For
143 * header as it seems to be mostly used by accident.
145 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
146 * Fix a crash on mingw32 with some Last Modified times in the future.
148 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
149 * Remove a "can't happen" error block which, over
150 * time, mutated into a "guaranteed to happen" block.
152 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
153 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
154 * - Use shiny new content_filters_enabled() in client_range().
156 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
157 * I forgot about Poland.
159 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
160 * Remove Range and If-Range headers if content filtering is enabled.
162 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
163 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
164 * client_cookie_adder() to make sure send-vanilla-wafer can be
165 * controlled through tags (and thus regression-tested).
167 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
168 * - Remove "scanning headers for" log message again.
169 * - Some more whitespace fixes.
171 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
172 * Refactor client_referrer() and add conditional-forge parameter.
174 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
175 * A bunch of whitespace fixes, pointy hat to me.
177 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
178 * Fix possible memory corruption in server_http, make sure it's not
179 * executed for ordinary server headers and mark some problems for later.
181 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
182 * Let content-type-overwrite{} honour force-text-mode again.
184 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
185 * - Add prototpyes for the header parsers and make them static.
186 * - Comment out client_accept_encoding_adder() which isn't used right now.
188 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
189 * Move the ACTION_FORCE_TEXT_MODE check out of
190 * server_content_type(). Signal other functions
191 * whether or not a content type has been declared.
192 * Part of the fix for BR#1750917.
194 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
195 * Change sed() to return a jb_err in preparation for forward-override{}.
197 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
198 * Adjust "X-Filter: No" to disable dedicated header filters.
200 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
201 * Streamline client_cookie_adder().
203 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
204 * Make sure filters with dynamic jobs actually use them.
206 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
207 * - Introduce dynamic pcrs jobs that can resolve variables.
208 * - Remove unnecessary update_action_bits_for_all_tags() call.
210 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
211 * - Make tagging based on tags set by earlier taggers
212 * of the same kind possible.
213 * - Log whether or not new tags cause action bits updates
214 * (in which case a matching tag-pattern section exists).
215 * - Log if the user tries to set a tag that is already set.
217 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
218 * Introduce tags as alternative way to specify which
219 * actions apply to a request. At the moment tags can be
220 * created based on client and server headers.
222 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
223 * Log a warning if the content is compressed, filtering is
224 * enabled and Privoxy was compiled without zlib support.
227 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
228 * - Fix warnings when compiled with glibc.
229 * - Don't use crumble() for cookie crunching.
230 * - Move cookie time parsing into parse_header_time().
231 * - Let parse_header_time() return a jb_err code
232 * instead of a pointer that can only be used to
233 * check for NULL anyway.
235 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
236 * - Add better protection against malicious gzip headers.
237 * - Stop logging the first hundred bytes of decompressed content.
238 * It looks like it's working and there is always debug 16.
239 * - Log the content size after decompression in decompress_iob()
240 * instead of pcrs_filter_response().
242 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
243 * - Use dedicated header filter actions instead of abusing "filter".
244 * Replace "filter-client-headers" and "filter-client-headers"
245 * with "server-header-filter" and "client-header-filter".
246 * - Remove filter_client_header() and filter_client_header(),
247 * filter_header() now checks the shiny new
248 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
250 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
251 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
252 * - Handle "Cookie:" and "Connection:" headers a bit smarter
253 * (don't crunch them just to recreate them later on).
254 * - Add another non-standard time format for the cookie
255 * expiration date detection.
256 * - Fix a valgrind warning.
258 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
259 * Improve cookie expiration date detection.
261 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
262 * Don't run server_content_length() the first time
263 * sed() parses server headers; only adjust the
264 * Content-Length header if the page was modified.
266 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
267 * Fix log messages regarding the cookie time format
268 * (cookie and request URL were mixed up).
270 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
271 * - Let decompress_iob()
272 * - not corrupt the content if decompression fails
273 * early. (the first byte(s) were lost).
274 * - use pointer arithmetics with defined outcome for
276 * - Use a different kludge to remember a failed decompression.
278 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
279 * Search for Max-Forwards headers case-insensitive,
280 * don't generate the "501 unsupported" message for invalid
281 * Max-Forwards values and don't increase negative ones.
283 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
284 * - Let server_set_cookie() check the expiration date
285 * of cookies and don't touch the ones that are already
286 * expired. Fixes problems with low quality web applications
287 * as described in BR 932612.
289 * - Adjust comment in client_max_forwards to reality;
290 * remove invalid Max-Forwards headers.
292 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
293 * Stop filter_header() from unintentionally removing
294 * empty header lines that were enlisted by the continue
297 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
298 * - Repeat the request URL before logging any headers.
299 * Makes reading the log easier in case of simultaneous requests.
300 * - If there are more than one Content-Type headers in one request,
301 * use the first one and remove the others.
302 * - Remove "newval" variable in server_content_type().
303 * It's only used once.
305 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
306 * Correct a cast, check inflateEnd() exit code
307 * to see if we have to, replace sprintf calls
310 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
311 * Integrate a modified version of Wil Mahan's
312 * zlib patch (PR #895531).
314 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
315 * Skip empty filter files in filter_header()
316 * but don't ignore the ones that come afterwards.
317 * Fixes BR 1619208, this time for real.
319 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
320 * Reverted parts of my last commit
321 * to keep error handling working.
323 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
324 * Fixed gcc43 conversion warnings.
326 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
327 * Bringing back the "useless" localtime() call
328 * I removed in revision 1.67. On some platforms
329 * it's necessary to prevent time zone offsets.
331 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
332 * Rebuild request URL in get_destination_from_headers()
333 * to make sure redirect{pcrs command} works as expected
334 * for intercepted requests.
336 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
337 * Added get_destination_from_headers().
339 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
340 * Make pthread mutex locking more generic. Instead of
341 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
342 * and use mutex locking unless there is an _r function
343 * available. Better safe than sorry.
345 * Fixes "./configure --disable-pthread" and should result
346 * in less threading-related problems on pthread-using platforms,
347 * but it still doesn't fix BR#1122404.
349 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
350 * The special header "X-Filter: No" now disables
351 * header filtering as well.
353 * Revision 1.73 2006/09/23 13:26:38 roro
354 * Replace TABs by spaces in source code.
356 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
357 * Don't print a log message every time filter_headers is
358 * entered or left. It only creates noise without any real
361 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
362 * Fix +hide-if-modified-since{-n}.
364 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
365 * Have hide-if-modified-since interpret the random
366 * range value as minutes instead of hours. Allows
367 * more fine-grained configuration.
369 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
370 * Always have parse_header_time return a pointer
371 * that actual makes sense, even though we currently
372 * only need it to detect problems.
374 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
375 * Added config option enable-remote-http-toggle
376 * to specify if Privoxy should recognize special
377 * headers (currently only X-Filter) to change its
378 * behaviour. Disabled by default.
380 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
381 * After filtering de-chunked instances, remove
382 * "Transfer-Encoding" header entirely instead of changing
383 * it to "Transfer-Encoding: identity", which is invalid.
384 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
386 * Don't use localtime in parse_header_time. An empty time struct
387 * is good enough, it gets overwritten by strptime anyway.
389 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
390 * Use gmtime_r if available, fallback to gmtime with mutex
391 * protection for MacOSX and use vanilla gmtime for the rest.
393 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
394 * Changed client_referrer to use the right type (size_t) for
395 * hostlenght and to shorten the temporary referrer string with
396 * '\0' instead of adding a useless line break.
398 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
399 * - Back to timegm() using GnuPG's replacement if necessary.
400 * Using mktime() and localtime() could add a on hour offset if
401 * the randomize factor was big enough to lead to a summer/wintertime
404 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
406 * - Moved randomization code into pick_from_range().
408 * - Changed parse_header_time definition.
409 * time_t isn't guaranteed to be signed and
410 * if it isn't, -1 isn't available as error code.
411 * Changed some variable types in client_if_modified_since()
412 * because of the same reason.
414 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
415 * OS/2 compilation compatibility fixups
417 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
418 * Changed include from strptime.c to strptime.h
420 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
421 * Split filter-headers{} into filter-client-headers{}
422 * and filter-server-headers{}.
423 * Added parse_header_time() to share some code.
424 * Replaced timegm() with mktime().
426 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
427 * Windows service integration
429 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
430 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
432 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
433 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
434 * with what was really the latest development (the v_3_0_branch branch)
436 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
437 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
439 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
440 * Add the ability to check jpeg images for invalid
441 * lengths of comment blocks. Defensive strategy
442 * against the exploit:
443 * Microsoft Security Bulletin MS04-028
444 * Buffer Overrun in JPEG Processing (GDI+) Could
445 * Allow Code Execution (833987)
446 * Enabled with +inspect-jpegs in actions files.
448 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
449 * Excluded text/plain objects from filtering. This fixes a
450 * couple of client-crashing, download corruption and
451 * Privoxy performance issues, whose root cause lies in
452 * web servers labelling content of unknown type as text/plain.
454 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
455 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
457 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
458 * Completing the previous change
460 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
461 * Added temporary workaround for bug in PHP < 4.2.3
463 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
464 * 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.
466 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
467 * Fix typo: supressed -> suppressed
469 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
470 * Improved cookie logging
472 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
473 * Added basic support for OPTIONS and TRACE HTTP methods:
474 * - New parser function client_max_forwards which decrements
475 * the Max-Forwards HTTP header field of OPTIONS and TRACE
476 * requests by one before forwarding
477 * - New parser function client_host which extracts the host
478 * and port information from the HTTP header field if the
479 * request URI was not absolute
480 * - Don't crumble and re-add the Host: header, but only generate
481 * and append if missing
483 * Revision 1.56 2002/05/12 15:34:22 jongfoster
484 * Fixing typo in a comment
486 * Revision 1.55 2002/05/08 16:01:07 oes
487 * Optimized add_to_iob:
488 * - Use realloc instead of malloc(), memcpy(), free()
489 * - Expand to powers of two if possible, to get
490 * O(log n) reallocs instead of O(n).
491 * - Moved check for buffer limit here from chat
492 * - Report failure via returncode
494 * Revision 1.54 2002/04/02 15:03:16 oes
495 * Tiny code cosmetics
497 * Revision 1.53 2002/03/26 22:29:55 swa
498 * we have a new homepage!
500 * Revision 1.52 2002/03/24 13:25:43 swa
501 * name change related issues
503 * Revision 1.51 2002/03/13 00:27:05 jongfoster
506 * Revision 1.50 2002/03/12 01:45:35 oes
507 * More verbose logging
509 * Revision 1.49 2002/03/09 20:03:52 jongfoster
510 * - Making various functions return int rather than size_t.
511 * (Undoing a recent change). Since size_t is unsigned on
512 * Windows, functions like read_socket that return -1 on
513 * error cannot return a size_t.
515 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
516 * crashes, and also frequently caused JB to jump to 100%
517 * CPU and stay there. (Because it thought it had just
518 * read ((unsigned)-1) == 4Gb of data...)
520 * - The signature of write_socket has changed, it now simply
521 * returns success=0/failure=nonzero.
523 * - Trying to get rid of a few warnings --with-debug on
524 * Windows, I've introduced a new type "jb_socket". This is
525 * used for the socket file descriptors. On Windows, this
526 * is SOCKET (a typedef for unsigned). Everywhere else, it's
527 * an int. The error value can't be -1 any more, so it's
528 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
529 * Windows it maps to the #define INVALID_SOCKET.)
531 * - The signature of bind_port has changed.
533 * Revision 1.48 2002/03/07 03:46:53 oes
534 * Fixed compiler warnings etc
536 * Revision 1.47 2002/02/20 23:15:13 jongfoster
537 * Parsing functions now handle out-of-memory gracefully by returning
540 * Revision 1.46 2002/01/17 21:03:47 jongfoster
541 * Moving all our URL and URL pattern parsing code to urlmatch.c.
543 * Revision 1.45 2002/01/09 14:33:03 oes
544 * Added support for localtime_r.
546 * Revision 1.44 2001/12/14 01:22:54 steudten
547 * Remove 'user:pass@' from 'proto://user:pass@host' for the
548 * new added header 'Host: ..'. (See Req ID 491818)
550 * Revision 1.43 2001/11/23 00:26:38 jongfoster
551 * Fixing two really stupid errors in my previous commit
553 * Revision 1.42 2001/11/22 21:59:30 jongfoster
554 * Adding code to handle +no-cookies-keep
556 * Revision 1.41 2001/11/05 23:43:05 steudten
557 * Add time+date to log files.
559 * Revision 1.40 2001/10/26 20:13:09 jongfoster
560 * ctype.h is needed in Windows, too.
562 * Revision 1.39 2001/10/26 17:40:04 oes
563 * Introduced get_header_value()
564 * Removed http->user_agent, csp->referrer and csp->accept_types
565 * Removed client_accept()
567 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
568 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
569 * threads to call select() simultaneously. So, it's time to do a real, live,
570 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
571 * (native). Both versions will work, but using __OS2__ offers multi-threading.
573 * Revision 1.37 2001/10/23 21:36:02 jongfoster
574 * Documenting sed()'s error behaviou (doc change only)
576 * Revision 1.36 2001/10/13 12:51:51 joergs
577 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
578 * force-load), instead crumble Host: and add it (again) in client_host_adder
579 * (in case we get a HTTP/1.0 request without Host: header and forward it to
580 * a HTTP/1.1 server/proxy).
582 * Revision 1.35 2001/10/09 22:39:21 jongfoster
583 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
586 * Revision 1.34 2001/10/07 18:50:55 oes
587 * Added server_content_encoding, renamed server_transfer_encoding
589 * Revision 1.33 2001/10/07 18:04:49 oes
590 * Changed server_http11 to server_http and its pattern to "HTTP".
591 * Additional functionality: it now saves the HTTP status into
592 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
594 * Revision 1.32 2001/10/07 15:43:28 oes
595 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
596 * client_te and client_accept_encoding_adder, triggered by the new
597 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
598 * changed to allow only identity and chunked, and the TE header is
599 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
601 * parse_http_request no longer does anything than parsing. The rewriting
602 * of http->cmd and version mangling are gone. It now also recognizes
603 * the put and delete methods and saves the url in http->url. Removed
606 * renamed content_type and content_length to have the server_ prefix
608 * server_content_type now only works if csp->content_type != CT_TABOO
610 * added server_transfer_encoding, which
611 * - Sets CT_TABOO to prohibit filtering if encoding compresses
612 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
613 * - Change from "chunked" to "identity" if body was chunked
614 * but has been de-chunked for filtering.
616 * added server_content_md5 which crunches any Content-MD5 headers
617 * if the body was modified.
619 * made server_http11 conditional on +downgrade action
621 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
623 * Revision 1.31 2001/10/05 14:25:02 oes
624 * Crumble Keep-Alive from Server
626 * Revision 1.30 2001/09/29 12:56:03 joergs
627 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
629 * Revision 1.29 2001/09/24 21:09:24 jongfoster
630 * Fixing 2 memory leaks that Guy spotted, where the paramater to
631 * enlist() was not being free()d.
633 * Revision 1.28 2001/09/22 16:32:28 jongfoster
634 * Removing unused #includes.
636 * Revision 1.27 2001/09/20 15:45:25 steudten
638 * add casting from size_t to int for printf()
639 * remove local variable shadow s2
641 * Revision 1.26 2001/09/16 17:05:14 jongfoster
642 * Removing unused #include showarg.h
644 * Revision 1.25 2001/09/16 13:21:27 jongfoster
645 * Changes to use new list functions.
647 * Revision 1.24 2001/09/13 23:05:50 jongfoster
648 * Changing the string paramater to the header parsers a "const".
650 * Revision 1.23 2001/09/12 18:08:19 steudten
652 * In parse_http_request() header rewriting miss the host value, so
653 * from http://www.mydomain.com the result was just " / " not
654 * http://www.mydomain.com/ in case we forward.
656 * Revision 1.22 2001/09/10 10:58:53 oes
657 * Silenced compiler warnings
659 * Revision 1.21 2001/07/31 14:46:00 oes
660 * - Persistant connections now suppressed
661 * - sed() no longer appends empty header to csp->headers
663 * Revision 1.20 2001/07/30 22:08:36 jongfoster
664 * Tidying up #defines:
665 * - All feature #defines are now of the form FEATURE_xxx
666 * - Permanently turned off WIN_GUI_EDIT
667 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
669 * Revision 1.19 2001/07/25 17:21:54 oes
670 * client_uagent now saves copy of User-Agent: header value
672 * Revision 1.18 2001/07/13 14:02:46 oes
673 * - Included fix to repair broken HTTP requests that
674 * don't contain a path, not even '/'.
675 * - Removed all #ifdef PCRS
676 * - content_type now always inspected and classified as
677 * text, gif or other.
678 * - formatting / comments
680 * Revision 1.17 2001/06/29 21:45:41 oes
681 * Indentation, CRLF->LF, Tab-> Space
683 * Revision 1.16 2001/06/29 13:32:42 oes
685 * - Adapted free_http_request
686 * - Removed logentry from cancelled commit
688 * Revision 1.15 2001/06/03 19:12:38 oes
689 * deleted const struct interceptors
691 * Revision 1.14 2001/06/01 18:49:17 jongfoster
692 * Replaced "list_share" with "list" - the tiny memory gain was not
693 * worth the extra complexity.
695 * Revision 1.13 2001/05/31 21:30:33 jongfoster
696 * Removed list code - it's now in list.[ch]
697 * Renamed "permission" to "action", and changed many features
698 * to use the actions file rather than the global config.
700 * Revision 1.12 2001/05/31 17:33:13 oes
704 * Revision 1.11 2001/05/29 20:11:19 joergs
705 * '/ * inside comment' warning removed.
707 * Revision 1.10 2001/05/29 09:50:24 jongfoster
708 * Unified blocklist/imagelist/permissionslist.
709 * File format is still under discussion, but the internal changes
712 * Also modified interceptor behaviour:
713 * - We now intercept all URLs beginning with one of the following
714 * prefixes (and *only* these prefixes):
716 * * http://ijbswa.sf.net/config/
717 * * http://ijbswa.sourceforge.net/config/
718 * - New interceptors "home page" - go to http://i.j.b/ to see it.
719 * - Internal changes so that intercepted and fast redirect pages
720 * are not replaced with an image.
721 * - Interceptors now have the option to send a binary page direct
722 * to the client. (i.e. ijb-send-banner uses this)
723 * - Implemented show-url-info interceptor. (Which is why I needed
724 * the above interceptors changes - a typical URL is
725 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
726 * The previous mechanism would not have intercepted that, and
727 * if it had been intercepted then it then it would have replaced
730 * Revision 1.9 2001/05/28 17:26:33 jongfoster
731 * Fixing segfault if last header was crunched.
732 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
733 * can use the cross-platform sprintf() instead.)
735 * Revision 1.8 2001/05/27 22:17:04 oes
737 * - re_process_buffer no longer writes the modified buffer
738 * to the client, which was very ugly. It now returns the
739 * buffer, which it is then written by chat.
741 * - content_length now adjusts the Content-Length: header
742 * for modified documents rather than crunch()ing it.
743 * (Length info in csp->content_length, which is 0 for
744 * unmodified documents)
746 * - For this to work, sed() is called twice when filtering.
748 * Revision 1.7 2001/05/27 13:19:06 oes
749 * Patched Joergs solution for the content-length in.
751 * Revision 1.6 2001/05/26 13:39:32 jongfoster
752 * Only crunches Content-Length header if applying RE filtering.
753 * Without this fix, Microsoft Windows Update wouldn't work.
755 * Revision 1.5 2001/05/26 00:28:36 jongfoster
756 * Automatic reloading of config file.
757 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
758 * Most of the global variables have been moved to a new
759 * struct configuration_spec, accessed through csp->config->globalname
760 * Most of the globals remaining are used by the Win32 GUI.
762 * Revision 1.4 2001/05/22 18:46:04 oes
764 * - Enabled filtering banners by size rather than URL
765 * by adding patterns that replace all standard banner
766 * sizes with the "Junkbuster" gif to the re_filterfile
768 * - Enabled filtering WebBugs by providing a pattern
769 * which kills all 1x1 images
771 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
772 * which is selected by the (nonstandard and therefore
773 * capital) letter 'U' in the option string.
774 * It causes the quantifiers to be ungreedy by default.
775 * Appending a ? turns back to greedy (!).
777 * - Added a new interceptor ijb-send-banner, which
778 * sends back the "Junkbuster" gif. Without imagelist or
779 * MSIE detection support, or if tinygif = 1, or the
780 * URL isn't recognized as an imageurl, a lame HTML
781 * explanation is sent instead.
783 * - Added new feature, which permits blocking remote
784 * script redirects and firing back a local redirect
786 * The feature is conditionally compiled, i.e. it
787 * can be disabled with --disable-fast-redirects,
788 * plus it must be activated by a "fast-redirects"
789 * line in the config file, has its own log level
790 * and of course wants to be displayed by show-proxy-args
791 * Note: Boy, all the #ifdefs in 1001 locations and
792 * all the fumbling with configure.in and acconfig.h
793 * were *way* more work than the feature itself :-(
795 * - Because a generic redirect template was needed for
796 * this, tinygif = 3 now uses the same.
798 * - Moved GIFs, and other static HTTP response templates
803 * - Removed some >400 CRs again (Jon, you really worked
806 * Revision 1.3 2001/05/20 01:21:20 jongfoster
807 * Version 2.9.4 checkin.
808 * - Merged popupfile and cookiefile, and added control over PCRS
809 * filtering, in new "permissionsfile".
810 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
811 * file error you now get a message box (in the Win32 GUI) rather
812 * than the program exiting with no explanation.
813 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
815 * - Removed tabs from "config"
816 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
817 * - Bumped up version number.
819 * Revision 1.2 2001/05/17 23:02:36 oes
820 * - Made referrer option accept 'L' as a substitute for '§'
822 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
823 * Initial import of version 2.9.3 source tree
826 *********************************************************************/
833 #include <sys/types.h>
843 * Convince GNU's libc to provide a strptime prototype.
846 #endif /*__GLIBC__ */
853 #if !defined(_WIN32) && !defined(__OS2__)
859 #ifdef FEATURE_PTHREAD
861 /* jcc.h is for mutex semapores only */
862 #endif /* def FEATURE_PTHREAD */
867 #include "jbsockets.h"
868 #include "miscutil.h"
873 #ifndef HAVE_STRPTIME
874 #include "strptime.h"
877 const char parsers_h_rcs[] = PARSERS_H_VERSION;
879 /* Fix a problem with Solaris. There should be no effect on other
881 * Solaris's isspace() is a macro which uses its argument directly
882 * as an array index. Therefore we need to make sure that high-bit
883 * characters generate +ve values, and ideally we also want to make
884 * the argument match the declared parameter type of "int".
886 * Why did they write a character function that can't take a simple
887 * "char" argument? Doh!
889 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
890 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
892 static char *get_header_line(struct iob *iob);
893 static jb_err scan_headers(struct client_state *csp);
894 static jb_err header_tagger(struct client_state *csp, char *header);
895 static jb_err parse_header_time(const char *header_time, time_t *result);
897 static jb_err crumble (struct client_state *csp, char **header);
898 static jb_err connection (struct client_state *csp, char **header);
899 static jb_err filter_header (struct client_state *csp, char **header);
900 static jb_err client_referrer (struct client_state *csp, char **header);
901 static jb_err client_uagent (struct client_state *csp, char **header);
902 static jb_err client_ua (struct client_state *csp, char **header);
903 static jb_err client_from (struct client_state *csp, char **header);
904 static jb_err client_send_cookie (struct client_state *csp, char **header);
905 static jb_err client_x_forwarded (struct client_state *csp, char **header);
906 static jb_err client_accept_encoding (struct client_state *csp, char **header);
907 static jb_err client_te (struct client_state *csp, char **header);
908 static jb_err client_max_forwards (struct client_state *csp, char **header);
909 static jb_err client_host (struct client_state *csp, char **header);
910 static jb_err client_if_modified_since (struct client_state *csp, char **header);
911 static jb_err client_accept_language (struct client_state *csp, char **header);
912 static jb_err client_if_none_match (struct client_state *csp, char **header);
913 static jb_err crunch_client_header (struct client_state *csp, char **header);
914 static jb_err client_x_filter (struct client_state *csp, char **header);
915 static jb_err client_range (struct client_state *csp, char **header);
916 static jb_err server_set_cookie (struct client_state *csp, char **header);
917 static jb_err server_content_type (struct client_state *csp, char **header);
918 static jb_err server_content_length (struct client_state *csp, char **header);
919 static jb_err server_content_md5 (struct client_state *csp, char **header);
920 static jb_err server_content_encoding (struct client_state *csp, char **header);
921 static jb_err server_transfer_coding (struct client_state *csp, char **header);
922 static jb_err server_http (struct client_state *csp, char **header);
923 static jb_err crunch_server_header (struct client_state *csp, char **header);
924 static jb_err server_last_modified (struct client_state *csp, char **header);
925 static jb_err server_content_disposition(struct client_state *csp, char **header);
927 static jb_err client_host_adder (struct client_state *csp);
928 static jb_err client_xtra_adder (struct client_state *csp);
929 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
930 static jb_err connection_close_adder (struct client_state *csp);
932 static jb_err create_forged_referrer(char **header, const char *hostport);
933 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
934 static jb_err handle_conditional_hide_referrer_parameter(char **header,
935 const char *host, const int parameter_conditional_block);
938 * List of functions to run on a list of headers.
942 /** The header prefix to match */
945 /** The length of the prefix to match */
948 /** The function to apply to this line */
949 const parser_func_ptr parser;
952 static const struct parsers client_patterns[] = {
953 { "referer:", 8, client_referrer },
954 { "user-agent:", 11, client_uagent },
955 { "ua-", 3, client_ua },
956 { "from:", 5, client_from },
957 { "cookie:", 7, client_send_cookie },
958 { "x-forwarded-for:", 16, client_x_forwarded },
959 { "Accept-Encoding:", 16, client_accept_encoding },
960 { "TE:", 3, client_te },
961 { "Host:", 5, client_host },
962 { "if-modified-since:", 18, client_if_modified_since },
963 { "Keep-Alive:", 11, crumble },
964 { "connection:", 11, connection },
965 { "proxy-connection:", 17, crumble },
966 { "max-forwards:", 13, client_max_forwards },
967 { "Accept-Language:", 16, client_accept_language },
968 { "if-none-match:", 14, client_if_none_match },
969 { "Range:", 6, client_range },
970 { "Request-Range:", 14, client_range },
971 { "If-Range:", 9, client_range },
972 { "X-Filter:", 9, client_x_filter },
973 { "*", 0, crunch_client_header },
974 { "*", 0, filter_header },
978 static const struct parsers server_patterns[] = {
979 { "HTTP/", 5, server_http },
980 { "set-cookie:", 11, server_set_cookie },
981 { "connection:", 11, connection },
982 { "Content-Type:", 13, server_content_type },
983 { "Content-MD5:", 12, server_content_md5 },
984 { "Content-Encoding:", 17, server_content_encoding },
985 { "Transfer-Encoding:", 18, server_transfer_coding },
986 { "Keep-Alive:", 11, crumble },
987 { "content-disposition:", 20, server_content_disposition },
988 { "Last-Modified:", 14, server_last_modified },
989 { "*", 0, crunch_server_header },
990 { "*", 0, filter_header },
994 static const add_header_func_ptr add_client_headers[] = {
996 client_x_forwarded_for_adder,
998 /* Temporarily disabled: client_accept_encoding_adder, */
999 connection_close_adder,
1003 static const add_header_func_ptr add_server_headers[] = {
1004 connection_close_adder,
1008 /*********************************************************************
1010 * Function : flush_socket
1012 * Description : Write any pending "buffered" content.
1015 * 1 : fd = file descriptor of the socket to read
1016 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1018 * Returns : On success, the number of bytes written are returned (zero
1019 * indicates nothing was written). On error, -1 is returned,
1020 * and errno is set appropriately. If count is zero and the
1021 * file descriptor refers to a regular file, 0 will be
1022 * returned without causing any other effect. For a special
1023 * file, the results are not portable.
1025 *********************************************************************/
1026 int flush_socket(jb_socket fd, struct iob *iob)
1028 int len = iob->eod - iob->cur;
1035 if (write_socket(fd, iob->cur, (size_t)len))
1039 iob->eod = iob->cur = iob->buf;
1045 /*********************************************************************
1047 * Function : add_to_iob
1049 * Description : Add content to the buffered page, expanding the
1050 * buffer if necessary.
1053 * 1 : csp = Current client state (buffers, headers, etc...)
1054 * 2 : buf = holds the content to be added to the page
1055 * 3 : n = number of bytes to be added
1057 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1058 * or buffer limit reached.
1060 *********************************************************************/
1061 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1063 struct iob *iob = csp->iob;
1064 size_t used, offset, need, want;
1067 if (n <= 0) return JB_ERR_OK;
1069 used = (size_t)(iob->eod - iob->buf);
1070 offset = (size_t)(iob->cur - iob->buf);
1071 need = used + (size_t)n + 1;
1074 * If the buffer can't hold the new data, extend it first.
1075 * Use the next power of two if possible, else use the actual need.
1077 if (need > csp->config->buffer_limit)
1079 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1080 return JB_ERR_MEMORY;
1083 if (need > iob->size)
1085 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1087 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1091 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1097 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1098 return JB_ERR_MEMORY;
1101 /* Update the iob pointers */
1102 iob->cur = p + offset;
1103 iob->eod = p + used;
1107 /* copy the new data into the iob buffer */
1108 memcpy(iob->eod, buf, (size_t)n);
1110 /* point to the end of the data */
1113 /* null terminate == cheap insurance */
1122 /*********************************************************************
1124 * Function : decompress_iob
1126 * Description : Decompress buffered page, expanding the
1127 * buffer as necessary. csp->iob->cur
1128 * should point to the the beginning of the
1129 * compressed data block.
1132 * 1 : csp = Current client state (buffers, headers, etc...)
1134 * Returns : JB_ERR_OK on success,
1135 * JB_ERR_MEMORY if out-of-memory limit reached, and
1136 * JB_ERR_COMPRESS if error decompressing buffer.
1138 *********************************************************************/
1139 jb_err decompress_iob(struct client_state *csp)
1141 char *buf; /* new, uncompressed buffer */
1142 char *cur; /* Current iob position (to keep the original
1143 * iob->cur unmodified if we return early) */
1144 size_t bufsize; /* allocated size of the new buffer */
1145 size_t old_size; /* Content size before decompression */
1146 size_t skip_size; /* Number of bytes at the beginning of the iob
1147 that we should NOT decompress. */
1148 int status; /* return status of the inflate() call */
1149 z_stream zstr; /* used by calls to zlib */
1151 assert(csp->iob->cur - csp->iob->buf > 0);
1152 assert(csp->iob->eod - csp->iob->cur > 0);
1154 bufsize = csp->iob->size;
1155 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1156 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1158 cur = csp->iob->cur;
1163 * This is to protect the parsing of gzipped data,
1164 * but it should(?) be valid for deflated data also.
1166 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1167 return JB_ERR_COMPRESS;
1170 if (csp->content_type & CT_GZIP)
1173 * Our task is slightly complicated by the facts that data
1174 * compressed by gzip does not include a zlib header, and
1175 * that there is no easily accessible interface in zlib to
1176 * handle a gzip header. We strip off the gzip header by
1177 * hand, and later inform zlib not to expect a header.
1181 * Strip off the gzip header. Please see RFC 1952 for more
1182 * explanation of the appropriate fields.
1184 if ((*cur++ != (char)0x1f)
1185 || (*cur++ != (char)0x8b)
1186 || (*cur++ != Z_DEFLATED))
1188 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1189 return JB_ERR_COMPRESS;
1195 * XXX: These magic numbers should be replaced
1196 * with macros to give a better idea what they do.
1200 /* The gzip header has reserved bits set; bail out. */
1201 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1202 return JB_ERR_COMPRESS;
1206 /* Skip extra fields if necessary. */
1210 * Skip a given number of bytes, specified
1211 * as a 16-bit little-endian value.
1214 * XXX: This code used to be:
1216 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1218 * which I had to change into:
1220 * cur += *cur++ + (*cur++ << 8);
1222 * at which point gcc43 finally noticed that the value
1223 * of cur is undefined (it depends on which of the
1224 * summands is evaluated first).
1226 * I haven't come across a site where this
1227 * code is actually executed yet, but I hope
1231 skip_bytes = *cur++;
1232 skip_bytes = *cur++ << 8;
1234 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1237 * The number of bytes to skip should be positive
1238 * and we'd like to stay in the buffer.
1240 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1242 log_error(LOG_LEVEL_ERROR,
1243 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1245 return JB_ERR_COMPRESS;
1247 log_error(LOG_LEVEL_INFO,
1248 "Skipping %d bytes for gzip compression. Does this sound right?",
1253 /* Skip the filename if necessary. */
1256 /* A null-terminated string is supposed to follow. */
1257 while (*cur++ && (cur < csp->iob->eod));
1261 /* Skip the comment if necessary. */
1264 /* A null-terminated string is supposed to follow. */
1265 while (*cur++ && (cur < csp->iob->eod));
1268 /* Skip the CRC if necessary. */
1274 if (cur >= csp->iob->eod)
1277 * If the current position pointer reached or passed
1278 * the buffer end, we were obviously tricked to skip
1281 log_error(LOG_LEVEL_ERROR,
1282 "Malformed gzip header detected. Aborting decompression.");
1283 return JB_ERR_COMPRESS;
1287 else if (csp->content_type & CT_DEFLATE)
1290 * XXX: The debug level should be lowered
1291 * before the next stable release.
1293 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1295 * In theory (that is, according to RFC 1950), deflate-compressed
1296 * data should begin with a two-byte zlib header and have an
1297 * adler32 checksum at the end. It seems that in practice only
1298 * the raw compressed data is sent. Note that this means that
1299 * we are not RFC 1950-compliant here, but the advantage is that
1300 * this actually works. :)
1302 * We add a dummy null byte to tell zlib where the data ends,
1303 * and later inform it not to expect a header.
1305 * Fortunately, add_to_iob() has thoughtfully null-terminated
1306 * the buffer; we can just increment the end pointer to include
1313 log_error(LOG_LEVEL_ERROR,
1314 "Unable to determine compression format for decompression");
1315 return JB_ERR_COMPRESS;
1318 /* Set up the fields required by zlib. */
1319 zstr.next_in = (Bytef *)cur;
1320 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1321 zstr.zalloc = Z_NULL;
1322 zstr.zfree = Z_NULL;
1323 zstr.opaque = Z_NULL;
1326 * Passing -MAX_WBITS to inflateInit2 tells the library
1327 * that there is no zlib header.
1329 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1331 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1332 return JB_ERR_COMPRESS;
1336 * Next, we allocate new storage for the inflated data.
1337 * We don't modify the existing iob yet, so in case there
1338 * is error in decompression we can recover gracefully.
1340 buf = zalloc(bufsize);
1343 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1344 return JB_ERR_MEMORY;
1347 assert(bufsize >= skip_size);
1348 memcpy(buf, csp->iob->buf, skip_size);
1349 zstr.avail_out = bufsize - skip_size;
1350 zstr.next_out = (Bytef *)buf + skip_size;
1352 /* Try to decompress the whole stream in one shot. */
1353 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1355 /* We need to allocate more memory for the output buffer. */
1357 char *tmpbuf; /* used for realloc'ing the buffer */
1358 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1361 * If zlib wants more data then there's a problem, because
1362 * the complete compressed file should have been buffered.
1364 if (0 == zstr.avail_in)
1366 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1367 return JB_ERR_COMPRESS;
1371 * If we tried the limit and still didn't have enough
1372 * memory, just give up.
1374 if (bufsize == csp->config->buffer_limit)
1376 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1377 return JB_ERR_MEMORY;
1380 /* Try doubling the buffer size each time. */
1383 /* Don't exceed the buffer limit. */
1384 if (bufsize > csp->config->buffer_limit)
1386 bufsize = csp->config->buffer_limit;
1389 /* Try to allocate the new buffer. */
1390 tmpbuf = realloc(buf, bufsize);
1393 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1395 return JB_ERR_MEMORY;
1399 char *oldnext_out = (char *)zstr.next_out;
1402 * Update the fields for inflate() to use the new
1403 * buffer, which may be in a location different from
1406 zstr.avail_out += bufsize - oldbufsize;
1407 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1410 * Compare with an uglier method of calculating these values
1411 * that doesn't require the extra oldbufsize variable.
1413 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1414 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1415 assert(zstr.avail_out > 0);
1421 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1423 log_error(LOG_LEVEL_ERROR,
1424 "Inconsistent stream state after decompression: %s", zstr.msg);
1426 * XXX: Intentionally no return.
1428 * According to zlib.h, Z_STREAM_ERROR is returned
1429 * "if the stream state was inconsistent".
1431 * I assume in this case inflate()'s status
1432 * would also be something different than Z_STREAM_END
1433 * so this check should be redundant, but lets see.
1437 if (status != Z_STREAM_END)
1439 /* We failed to decompress the stream. */
1440 log_error(LOG_LEVEL_ERROR,
1441 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1442 return JB_ERR_COMPRESS;
1446 * Finally, we can actually update the iob, since the
1447 * decompression was successful. First, free the old
1450 freez(csp->iob->buf);
1452 /* Now, update the iob to use the new buffer. */
1453 csp->iob->buf = buf;
1454 csp->iob->cur = csp->iob->buf + skip_size;
1455 csp->iob->eod = (char *)zstr.next_out;
1456 csp->iob->size = bufsize;
1459 * Make sure the new uncompressed iob obeys some minimal
1460 * consistency conditions.
1462 if ((csp->iob->buf < csp->iob->cur)
1463 && (csp->iob->cur <= csp->iob->eod)
1464 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1466 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1469 log_error(LOG_LEVEL_RE_FILTER,
1470 "Decompression successful. Old size: %d, new size: %d.",
1471 old_size, new_size);
1475 /* zlib thinks this is OK, so lets do the same. */
1476 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1481 /* It seems that zlib did something weird. */
1482 log_error(LOG_LEVEL_ERROR,
1483 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1484 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1485 csp->iob->eod, csp->iob->buf + csp->iob->size);
1486 return JB_ERR_COMPRESS;
1492 #endif /* defined(FEATURE_ZLIB) */
1495 /*********************************************************************
1497 * Function : string_move
1499 * Description : memmove wrapper to move the last part of a string
1500 * towards the beginning, overwriting the part in
1501 * the middle. strlcpy() can't be used here as the
1505 * 1 : dst = Destination to overwrite
1506 * 2 : src = Source to move.
1510 *********************************************************************/
1511 static void string_move(char *dst, char *src)
1515 /* +1 to copy the terminating nul as well. */
1516 memmove(dst, src, strlen(src)+1);
1520 /*********************************************************************
1522 * Function : normalize_lws
1524 * Description : Reduces unquoted linear white space in headers
1525 * to a single space in accordance with RFC 2616 2.2.
1526 * This simplifies parsing and filtering later on.
1528 * XXX: Remove log messages before
1529 * the next stable release?
1532 * 1 : header = A header with linear white space to reduce.
1536 *********************************************************************/
1537 static void normalize_lws(char *header)
1543 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1547 while (ijb_isspace(*q))
1551 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1552 string_move(p+1, q);
1557 log_error(LOG_LEVEL_HEADER,
1558 "Converting tab to space in '%s'", header);
1563 char *end_of_token = strstr(p+1, "\"");
1565 if (NULL != end_of_token)
1567 /* Don't mess with quoted text. */
1572 log_error(LOG_LEVEL_HEADER,
1573 "Ignoring single quote in '%s'", header);
1579 p = strchr(header, ':');
1580 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1583 * There's still space before the colon.
1586 string_move(p-1, p);
1591 /*********************************************************************
1593 * Function : get_header
1595 * Description : This (odd) routine will parse the csp->iob
1596 * to get the next complete header.
1599 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1601 * Returns : Any one of the following:
1603 * 1) a pointer to a dynamically allocated string that contains a header line
1604 * 2) NULL indicating that the end of the header was reached
1605 * 3) "" indicating that the end of the iob was reached before finding
1606 * a complete header line.
1608 *********************************************************************/
1609 char *get_header(struct iob *iob)
1613 header = get_header_line(iob);
1615 if ((header == NULL) || (*header == '\0'))
1618 * No complete header read yet, tell the client.
1623 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1626 * Header spans multiple lines, append the next one.
1628 char *continued_header;
1630 continued_header = get_header_line(iob);
1631 if ((continued_header == NULL) || (*continued_header == '\0'))
1634 * No complete header read yet, return what we got.
1635 * XXX: Should "unread" header instead.
1637 log_error(LOG_LEVEL_INFO,
1638 "Failed to read a multi-line header properly: '%s'",
1643 if (JB_ERR_OK != string_join(&header, continued_header))
1645 log_error(LOG_LEVEL_FATAL,
1646 "Out of memory while appending multiple headers.");
1650 /* XXX: remove before next stable release. */
1651 log_error(LOG_LEVEL_HEADER,
1652 "Merged multiple header lines to: '%s'",
1657 normalize_lws(header);
1664 /*********************************************************************
1666 * Function : get_header_line
1668 * Description : This (odd) routine will parse the csp->iob
1669 * to get the next header line.
1672 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1674 * Returns : Any one of the following:
1676 * 1) a pointer to a dynamically allocated string that contains a header line
1677 * 2) NULL indicating that the end of the header was reached
1678 * 3) "" indicating that the end of the iob was reached before finding
1679 * a complete header line.
1681 *********************************************************************/
1682 static char *get_header_line(struct iob *iob)
1686 if ((iob->cur == NULL)
1687 || ((p = strchr(iob->cur, '\n')) == NULL))
1689 return(""); /* couldn't find a complete header */
1694 ret = strdup(iob->cur);
1697 /* FIXME No way to handle error properly */
1698 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1703 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1705 /* is this a blank line (i.e. the end of the header) ? */
1717 /*********************************************************************
1719 * Function : get_header_value
1721 * Description : Get the value of a given header from a chained list
1722 * of header lines or return NULL if no such header is
1723 * present in the list.
1726 * 1 : header_list = pointer to list
1727 * 2 : header_name = string with name of header to look for.
1728 * Trailing colon required, capitalization
1731 * Returns : NULL if not found, else value of header
1733 *********************************************************************/
1734 char *get_header_value(const struct list *header_list, const char *header_name)
1736 struct list_entry *cur_entry;
1740 assert(header_list);
1741 assert(header_name);
1742 length = strlen(header_name);
1744 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1748 if (!strncmpic(cur_entry->str, header_name, length))
1751 * Found: return pointer to start of value
1753 ret = cur_entry->str + length;
1754 while (*ret && ijb_isspace(*ret)) ret++;
1768 /*********************************************************************
1770 * Function : scan_headers
1772 * Description : Scans headers, applies tags and updates action bits.
1775 * 1 : csp = Current client state (buffers, headers, etc...)
1777 * Returns : JB_ERR_OK
1779 *********************************************************************/
1780 static jb_err scan_headers(struct client_state *csp)
1782 struct list_entry *h; /* Header */
1783 jb_err err = JB_ERR_OK;
1785 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1787 /* Header crunch()ed in previous run? -> ignore */
1788 if (h->str == NULL) continue;
1789 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1790 err = header_tagger(csp, h->str);
1797 /*********************************************************************
1801 * Description : add, delete or modify lines in the HTTP header streams.
1802 * On entry, it receives a linked list of headers space
1803 * that was allocated dynamically (both the list nodes
1804 * and the header contents).
1806 * As a side effect it frees the space used by the original
1810 * 1 : csp = Current client state (buffers, headers, etc...)
1811 * 2 : filter_server_headers = Boolean to switch between
1812 * server and header filtering.
1814 * Returns : JB_ERR_OK in case off success, or
1815 * JB_ERR_MEMORY on out-of-memory error.
1817 *********************************************************************/
1818 jb_err sed(struct client_state *csp, int filter_server_headers)
1820 /* XXX: use more descriptive names. */
1821 struct list_entry *p;
1822 const struct parsers *v;
1823 const add_header_func_ptr *f;
1824 jb_err err = JB_ERR_OK;
1826 if (filter_server_headers)
1828 v = server_patterns;
1829 f = add_server_headers;
1833 v = client_patterns;
1834 f = add_client_headers;
1839 while ((err == JB_ERR_OK) && (v->str != NULL))
1841 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1843 /* Header crunch()ed in previous run? -> ignore */
1844 if (p->str == NULL) continue;
1846 /* Does the current parser handle this header? */
1847 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1848 (v->len == CHECK_EVERY_HEADER_REMAINING))
1850 err = v->parser(csp, &(p->str));
1856 /* place additional headers on the csp->headers list */
1857 while ((err == JB_ERR_OK) && (*f))
1867 /*********************************************************************
1869 * Function : update_server_headers
1871 * Description : Updates server headers after the body has been modified.
1874 * 1 : csp = Current client state (buffers, headers, etc...)
1876 * Returns : JB_ERR_OK in case off success, or
1877 * JB_ERR_MEMORY on out-of-memory error.
1879 *********************************************************************/
1880 jb_err update_server_headers(struct client_state *csp)
1882 jb_err err = JB_ERR_OK;
1884 static const struct parsers server_patterns_light[] = {
1885 { "Content-Length:", 15, server_content_length },
1886 { "Transfer-Encoding:", 18, server_transfer_coding },
1888 { "Content-Encoding:", 17, server_content_encoding },
1889 #endif /* def FEATURE_ZLIB */
1893 if (strncmpic(csp->http->cmd, "HEAD", 4))
1895 const struct parsers *v;
1896 struct list_entry *p;
1898 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1900 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1902 /* Header crunch()ed in previous run? -> ignore */
1903 if (p->str == NULL) continue;
1905 /* Does the current parser handle this header? */
1906 if (strncmpic(p->str, v->str, v->len) == 0)
1908 err = v->parser(csp, (char **)&(p->str));
1918 /*********************************************************************
1920 * Function : header_tagger
1922 * Description : Executes all text substitutions from applying
1923 * tag actions and saves the result as tag.
1925 * XXX: Shares enough code with filter_header() and
1926 * pcrs_filter_response() to warrant some helper functions.
1929 * 1 : csp = Current client state (buffers, headers, etc...)
1930 * 2 : header = Header that is used as tagger input
1932 * Returns : JB_ERR_OK on success and always succeeds
1934 *********************************************************************/
1935 static jb_err header_tagger(struct client_state *csp, char *header)
1937 int wanted_filter_type;
1938 int multi_action_index;
1942 struct file_list *fl;
1943 struct re_filterfile_spec *b;
1944 struct list_entry *tag_name;
1946 int found_filters = 0;
1947 const size_t header_length = strlen(header);
1949 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1951 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1952 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1956 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1957 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1960 /* Check if there are any filters */
1961 for (i = 0; i < MAX_AF_FILES; i++)
1974 if (0 == found_filters)
1976 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1977 "tagging enabled, but no taggers available.");
1981 for (i = 0; i < MAX_AF_FILES; i++)
1984 if ((NULL == fl) || (NULL == fl->f))
1987 * Either there are no filter files
1988 * left, or this filter file just
1989 * contains no valid filters.
1991 * Continue to be sure we don't miss
1992 * valid filter files that are chained
1993 * after empty or invalid ones.
1998 /* For all filters, */
1999 for (b = fl->f; b; b = b->next)
2001 if (b->type != wanted_filter_type)
2003 /* skip the ones we don't care about, */
2006 /* leaving only taggers that could apply, of which we use the ones, */
2007 for (tag_name = csp->action->multi[multi_action_index]->first;
2008 NULL != tag_name; tag_name = tag_name->next)
2010 /* that do apply, and */
2011 if (strcmp(b->name, tag_name->str) == 0)
2013 char *modified_tag = NULL;
2015 size_t size = header_length;
2016 pcrs_job *joblist = b->joblist;
2018 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2020 if (NULL == joblist)
2022 log_error(LOG_LEVEL_RE_FILTER,
2023 "Tagger %s has empty joblist. Nothing to do.", b->name);
2027 /* execute their pcrs_joblist on the header. */
2028 for (job = joblist; NULL != job; job = job->next)
2030 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2034 /* Success, continue with the modified version. */
2043 /* Tagger doesn't match */
2046 /* Regex failure, log it but continue anyway. */
2047 log_error(LOG_LEVEL_ERROR,
2048 "Problems with tagger \'%s\' and header \'%s\': %s",
2049 b->name, *header, pcrs_strerror(hits));
2051 freez(modified_tag);
2055 if (b->dynamic) pcrs_free_joblist(joblist);
2057 /* If this tagger matched */
2063 * There is to technical limitation which makes
2064 * it impossible to use empty tags, but I assume
2065 * no one would do it intentionally.
2068 log_error(LOG_LEVEL_INFO,
2069 "Tagger \'%s\' created an empty tag. Ignored.",
2074 if (!list_contains_item(csp->tags, tag))
2076 if (JB_ERR_OK != enlist(csp->tags, tag))
2078 log_error(LOG_LEVEL_ERROR,
2079 "Insufficient memory to add tag \'%s\', "
2080 "based on tagger \'%s\' and header \'%s\'",
2081 tag, b->name, *header);
2085 char *action_message;
2087 * update the action bits right away, to make
2088 * tagging based on tags set by earlier taggers
2089 * of the same kind possible.
2091 if (update_action_bits_for_tag(csp, tag))
2093 action_message = "Action bits updated accordingly.";
2097 action_message = "No action bits update necessary.";
2100 log_error(LOG_LEVEL_HEADER,
2101 "Tagger \'%s\' added tag \'%s\'. %s",
2102 b->name, tag, action_message);
2107 /* XXX: Is this log-worthy? */
2108 log_error(LOG_LEVEL_HEADER,
2109 "Tagger \'%s\' didn't add tag \'%s\'. "
2110 "Tag already present", b->name, tag);
2113 } /* if the tagger matched */
2114 } /* if the tagger applies */
2115 } /* for every tagger that could apply */
2116 } /* for all filters */
2117 } /* for all filter files */
2122 /* here begins the family of parser functions that reformat header lines */
2124 /*********************************************************************
2126 * Function : filter_header
2128 * Description : Executes all text substitutions from all applying
2129 * +(server|client)-header-filter actions on the header.
2130 * Most of the code was copied from pcrs_filter_response,
2131 * including the rather short variable names
2134 * 1 : csp = Current client state (buffers, headers, etc...)
2135 * 2 : header = On input, pointer to header to modify.
2136 * On output, pointer to the modified header, or NULL
2137 * to remove the header. This function frees the
2138 * original string if necessary.
2140 * Returns : JB_ERR_OK on success and always succeeds
2142 *********************************************************************/
2143 static jb_err filter_header(struct client_state *csp, char **header)
2147 size_t size = strlen(*header);
2149 char *newheader = NULL;
2152 struct file_list *fl;
2153 struct re_filterfile_spec *b;
2154 struct list_entry *filtername;
2156 int i, found_filters = 0;
2157 int wanted_filter_type;
2158 int multi_action_index;
2160 if (csp->flags & CSP_FLAG_NO_FILTERING)
2165 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2167 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2168 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2172 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2173 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2177 * Need to check the set of re_filterfiles...
2179 for (i = 0; i < MAX_AF_FILES; i++)
2192 if (0 == found_filters)
2194 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2195 "header filtering enabled, but no matching filters available.");
2199 for (i = 0; i < MAX_AF_FILES; i++)
2202 if ((NULL == fl) || (NULL == fl->f))
2205 * Either there are no filter files
2206 * left, or this filter file just
2207 * contains no valid filters.
2209 * Continue to be sure we don't miss
2210 * valid filter files that are chained
2211 * after empty or invalid ones.
2216 * For all applying +filter actions, look if a filter by that
2217 * name exists and if yes, execute its pcrs_joblist on the
2220 for (b = fl->f; b; b = b->next)
2222 if (b->type != wanted_filter_type)
2224 /* Skip other filter types */
2228 for (filtername = csp->action->multi[multi_action_index]->first;
2229 filtername ; filtername = filtername->next)
2231 if (strcmp(b->name, filtername->str) == 0)
2233 int current_hits = 0;
2234 pcrs_job *joblist = b->joblist;
2236 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2238 if (NULL == joblist)
2240 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2244 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2245 *header, size, b->name);
2247 /* Apply all jobs from the joblist */
2248 for (job = joblist; NULL != job; job = job->next)
2250 matches = pcrs_execute(job, *header, size, &newheader, &size);
2253 current_hits += matches;
2254 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2256 *header = newheader;
2258 else if ( 0 == matches )
2260 /* Filter doesn't change header */
2266 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2267 *header, b->name, pcrs_strerror(matches));
2268 if (newheader != NULL)
2270 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2276 if (b->dynamic) pcrs_free_joblist(joblist);
2278 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2279 hits += current_hits;
2286 * Additionally checking for hits is important because if
2287 * the continue hack is triggered, server headers can
2288 * arrive empty to separate multiple heads from each other.
2290 if ((0 == size) && hits)
2292 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2300 /*********************************************************************
2302 * Function : connection
2304 * Description : Makes sure that the value of the Connection: header
2305 * is "close" and signals connection_close_adder
2309 * 1 : csp = Current client state (buffers, headers, etc...)
2310 * 2 : header = On input, pointer to header to modify.
2311 * On output, pointer to the modified header, or NULL
2312 * to remove the header. This function frees the
2313 * original string if necessary.
2315 * Returns : JB_ERR_OK on success, or
2316 * JB_ERR_MEMORY on out-of-memory error.
2318 *********************************************************************/
2319 static jb_err connection(struct client_state *csp, char **header)
2321 char *old_header = *header;
2323 /* Do we have a 'Connection: close' header? */
2324 if (strcmpic(*header, "Connection: close"))
2326 /* No, create one */
2327 *header = strdup("Connection: close");
2330 return JB_ERR_MEMORY;
2332 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2336 /* Signal connection_close_adder() to return early. */
2337 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2339 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2343 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2350 /*********************************************************************
2352 * Function : crumble
2354 * Description : This is called if a header matches a pattern to "crunch"
2357 * 1 : csp = Current client state (buffers, headers, etc...)
2358 * 2 : header = On input, pointer to header to modify.
2359 * On output, pointer to the modified header, or NULL
2360 * to remove the header. This function frees the
2361 * original string if necessary.
2363 * Returns : JB_ERR_OK on success, or
2364 * JB_ERR_MEMORY on out-of-memory error.
2366 *********************************************************************/
2367 static jb_err crumble(struct client_state *csp, char **header)
2369 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2375 /*********************************************************************
2377 * Function : crunch_server_header
2379 * Description : Crunch server header if it matches a string supplied by the
2380 * user. Called from `sed'.
2383 * 1 : csp = Current client state (buffers, headers, etc...)
2384 * 2 : header = On input, pointer to header to modify.
2385 * On output, pointer to the modified header, or NULL
2386 * to remove the header. This function frees the
2387 * original string if necessary.
2389 * Returns : JB_ERR_OK on success and always succeeds
2391 *********************************************************************/
2392 static jb_err crunch_server_header(struct client_state *csp, char **header)
2394 const char *crunch_pattern;
2396 /* Do we feel like crunching? */
2397 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2399 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2401 /* Is the current header the lucky one? */
2402 if (strstr(*header, crunch_pattern))
2404 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2413 /*********************************************************************
2415 * Function : server_content_type
2417 * Description : Set the content-type for filterable types (text/.*,
2418 * .*xml.*, javascript and image/gif) unless filtering has been
2419 * forbidden (CT_TABOO) while parsing earlier headers.
2420 * NOTE: Since text/plain is commonly used by web servers
2421 * for files whose correct type is unknown, we don't
2422 * set CT_TEXT for it.
2425 * 1 : csp = Current client state (buffers, headers, etc...)
2426 * 2 : header = On input, pointer to header to modify.
2427 * On output, pointer to the modified header, or NULL
2428 * to remove the header. This function frees the
2429 * original string if necessary.
2431 * Returns : JB_ERR_OK on success, or
2432 * JB_ERR_MEMORY on out-of-memory error.
2434 *********************************************************************/
2435 static jb_err server_content_type(struct client_state *csp, char **header)
2437 /* Remove header if it isn't the first Content-Type header */
2438 if ((csp->content_type & CT_DECLARED))
2441 * Another, slightly slower, way to see if
2442 * we already parsed another Content-Type header.
2444 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2446 log_error(LOG_LEVEL_ERROR,
2447 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2455 * Signal that the Content-Type has been set.
2457 csp->content_type |= CT_DECLARED;
2459 if (!(csp->content_type & CT_TABOO))
2462 * XXX: The assumption that text/plain is a sign of
2463 * binary data seems to be somewhat unreasonable nowadays
2464 * and should be dropped after 3.0.8 is out.
2466 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2467 || strstr(*header, "xml")
2468 || strstr(*header, "application/x-javascript"))
2470 csp->content_type |= CT_TEXT;
2472 else if (strstr(*header, "image/gif"))
2474 csp->content_type |= CT_GIF;
2479 * Are we messing with the content type?
2481 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2484 * Make sure the user doesn't accidently
2485 * change the content type of binary documents.
2487 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2490 *header = strdup("Content-Type: ");
2491 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2495 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2496 return JB_ERR_MEMORY;
2498 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2502 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2503 "It doesn't look like a content type that should be filtered. "
2504 "Enable force-text-mode if you know what you're doing.", *header);
2512 /*********************************************************************
2514 * Function : server_transfer_coding
2516 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2517 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2518 * - Remove header if body was chunked but has been
2519 * de-chunked for filtering.
2522 * 1 : csp = Current client state (buffers, headers, etc...)
2523 * 2 : header = On input, pointer to header to modify.
2524 * On output, pointer to the modified header, or NULL
2525 * to remove the header. This function frees the
2526 * original string if necessary.
2528 * Returns : JB_ERR_OK on success, or
2529 * JB_ERR_MEMORY on out-of-memory error.
2531 *********************************************************************/
2532 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2535 * Turn off pcrs and gif filtering if body compressed
2537 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2541 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2543 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2544 csp->http->cmd, *header);
2545 #endif /* def FEATURE_ZLIB */
2546 csp->content_type = CT_TABOO;
2550 * Raise flag if body chunked
2552 if (strstr(*header, "chunked"))
2554 csp->flags |= CSP_FLAG_CHUNKED;
2557 * If the body was modified, it has been de-chunked first
2558 * and the header must be removed.
2560 * FIXME: If there is more than one transfer encoding,
2561 * only the "chunked" part should be removed here.
2563 if (csp->flags & CSP_FLAG_MODIFIED)
2565 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2574 /*********************************************************************
2576 * Function : server_content_encoding
2578 * Description : This function is run twice for each request,
2579 * unless FEATURE_ZLIB and filtering are disabled.
2581 * The first run is used to check if the content
2582 * is compressed, if FEATURE_ZLIB is disabled
2583 * filtering is then disabled as well, if FEATURE_ZLIB
2584 * is enabled the content is marked for decompression.
2586 * The second run is used to remove the Content-Encoding
2587 * header if the decompression was successful.
2590 * 1 : csp = Current client state (buffers, headers, etc...)
2591 * 2 : header = On input, pointer to header to modify.
2592 * On output, pointer to the modified header, or NULL
2593 * to remove the header. This function frees the
2594 * original string if necessary.
2596 * Returns : JB_ERR_OK on success, or
2597 * JB_ERR_MEMORY on out-of-memory error.
2599 *********************************************************************/
2600 static jb_err server_content_encoding(struct client_state *csp, char **header)
2603 if ((csp->flags & CSP_FLAG_MODIFIED)
2604 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2607 * We successfully decompressed the content,
2608 * and have to clean the header now, so the
2609 * client no longer expects compressed data..
2611 * XXX: There is a difference between cleaning
2612 * and removing it completely.
2614 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2617 else if (strstr(*header, "gzip"))
2619 /* Mark for gzip decompression */
2620 csp->content_type |= CT_GZIP;
2622 else if (strstr(*header, "deflate"))
2624 /* Mark for zlib decompression */
2625 csp->content_type |= CT_DEFLATE;
2627 else if (strstr(*header, "compress"))
2630 * We can't decompress this; therefore we can't filter
2633 csp->content_type |= CT_TABOO;
2635 #else /* !defined(FEATURE_ZLIB) */
2636 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2639 * Body is compressed, turn off pcrs and gif filtering.
2641 csp->content_type |= CT_TABOO;
2644 * Log a warning if the user expects the content to be filtered.
2646 if ((csp->rlist != NULL) &&
2647 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2649 log_error(LOG_LEVEL_INFO,
2650 "Compressed content detected, content filtering disabled. "
2651 "Consider recompiling Privoxy with zlib support or "
2652 "enable the prevent-compression action.");
2655 #endif /* defined(FEATURE_ZLIB) */
2662 /*********************************************************************
2664 * Function : server_content_length
2666 * Description : Adjust Content-Length header if we modified
2670 * 1 : csp = Current client state (buffers, headers, etc...)
2671 * 2 : header = On input, pointer to header to modify.
2672 * On output, pointer to the modified header, or NULL
2673 * to remove the header. This function frees the
2674 * original string if necessary.
2676 * Returns : JB_ERR_OK on success, or
2677 * JB_ERR_MEMORY on out-of-memory error.
2679 *********************************************************************/
2680 static jb_err server_content_length(struct client_state *csp, char **header)
2682 const size_t max_header_length = 80;
2684 /* Regenerate header if the content was modified. */
2685 if (csp->flags & CSP_FLAG_MODIFIED)
2688 *header = (char *) zalloc(max_header_length);
2689 if (*header == NULL)
2691 return JB_ERR_MEMORY;
2694 snprintf(*header, max_header_length, "Content-Length: %d",
2695 (int)csp->content_length);
2696 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2697 (int)csp->content_length);
2704 /*********************************************************************
2706 * Function : server_content_md5
2708 * Description : Crumble any Content-MD5 headers if the document was
2709 * modified. FIXME: Should we re-compute instead?
2712 * 1 : csp = Current client state (buffers, headers, etc...)
2713 * 2 : header = On input, pointer to header to modify.
2714 * On output, pointer to the modified header, or NULL
2715 * to remove the header. This function frees the
2716 * original string if necessary.
2718 * Returns : JB_ERR_OK on success, or
2719 * JB_ERR_MEMORY on out-of-memory error.
2721 *********************************************************************/
2722 static jb_err server_content_md5(struct client_state *csp, char **header)
2724 if (csp->flags & CSP_FLAG_MODIFIED)
2726 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2734 /*********************************************************************
2736 * Function : server_content_disposition
2738 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2739 * Called from `sed'.
2742 * 1 : csp = Current client state (buffers, headers, etc...)
2743 * 2 : header = On input, pointer to header to modify.
2744 * On output, pointer to the modified header, or NULL
2745 * to remove the header. This function frees the
2746 * original string if necessary.
2748 * Returns : JB_ERR_OK on success, or
2749 * JB_ERR_MEMORY on out-of-memory error.
2751 *********************************************************************/
2752 static jb_err server_content_disposition(struct client_state *csp, char **header)
2757 * Are we messing with the Content-Disposition header?
2759 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2765 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2767 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2770 * Blocking content-disposition header
2772 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2779 * Replacing Content-Disposition header
2782 *header = strdup("Content-Disposition: ");
2783 string_append(header, newval);
2785 if (*header != NULL)
2787 log_error(LOG_LEVEL_HEADER,
2788 "Content-Disposition header crunched and replaced with: %s", *header);
2791 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2795 /*********************************************************************
2797 * Function : server_last_modified
2799 * Description : Changes Last-Modified header to the actual date
2800 * to help hide-if-modified-since.
2801 * Called from `sed'.
2804 * 1 : csp = Current client state (buffers, headers, etc...)
2805 * 2 : header = On input, pointer to header to modify.
2806 * On output, pointer to the modified header, or NULL
2807 * to remove the header. This function frees the
2808 * original string if necessary.
2810 * Returns : JB_ERR_OK on success, or
2811 * JB_ERR_MEMORY on out-of-memory error.
2813 *********************************************************************/
2814 static jb_err server_last_modified(struct client_state *csp, char **header)
2817 char buf[BUFFER_SIZE];
2820 #ifdef HAVE_GMTIME_R
2823 struct tm *timeptr = NULL;
2824 time_t now, last_modified;
2826 long int days, hours, minutes, seconds;
2829 * Are we messing with the Last-Modified header?
2831 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2837 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2839 if (0 == strcmpic(newval, "block") )
2842 * Blocking Last-Modified header. Useless but why not.
2844 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2848 else if (0 == strcmpic(newval, "reset-to-request-time"))
2851 * Setting Last-Modified Header to now.
2853 get_http_time(0, buf, sizeof(buf));
2855 *header = strdup("Last-Modified: ");
2856 string_append(header, buf);
2858 if (*header == NULL)
2860 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2864 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2867 else if (0 == strcmpic(newval, "randomize"))
2869 const char *header_time = *header + sizeof("Last-Modified:");
2871 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2873 #ifdef HAVE_GMTIME_R
2874 timeptr = gmtime_r(&now, &gmt);
2875 #elif FEATURE_PTHREAD
2876 privoxy_mutex_lock(&gmtime_mutex);
2877 timeptr = gmtime(&now);
2878 privoxy_mutex_unlock(&gmtime_mutex);
2880 timeptr = gmtime(&now);
2882 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2884 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2889 rtime = (long int)difftime(now, last_modified);
2898 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2900 rtime = pick_from_range(rtime);
2901 if (negative) rtime *= -1;
2902 last_modified += rtime;
2903 #ifdef HAVE_GMTIME_R
2904 timeptr = gmtime_r(&last_modified, &gmt);
2905 #elif FEATURE_PTHREAD
2906 privoxy_mutex_lock(&gmtime_mutex);
2907 timeptr = gmtime(&last_modified);
2908 privoxy_mutex_unlock(&gmtime_mutex);
2910 timeptr = gmtime(&last_modified);
2912 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2914 *header = strdup("Last-Modified: ");
2915 string_append(header, newheader);
2917 if (*header == NULL)
2919 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2920 return JB_ERR_MEMORY;
2923 days = rtime / (3600 * 24);
2924 hours = rtime / 3600 % 24;
2925 minutes = rtime / 60 % 60;
2926 seconds = rtime % 60;
2928 log_error(LOG_LEVEL_HEADER,
2929 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2930 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2931 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2935 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2944 /*********************************************************************
2946 * Function : client_accept_encoding
2948 * Description : Rewrite the client's Accept-Encoding header so that
2949 * if doesn't allow compression, if the action applies.
2950 * Note: For HTTP/1.0 the absence of the header is enough.
2953 * 1 : csp = Current client state (buffers, headers, etc...)
2954 * 2 : header = On input, pointer to header to modify.
2955 * On output, pointer to the modified header, or NULL
2956 * to remove the header. This function frees the
2957 * original string if necessary.
2959 * Returns : JB_ERR_OK on success, or
2960 * JB_ERR_MEMORY on out-of-memory error.
2962 *********************************************************************/
2963 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2965 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2967 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2971 /* Temporarily disable the correct behaviour to
2972 * work around a PHP bug.
2974 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2976 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2977 * if (*header == NULL)
2979 * return JB_ERR_MEMORY;
2990 /*********************************************************************
2992 * Function : client_te
2994 * Description : Rewrite the client's TE header so that
2995 * if doesn't allow compression, if the action applies.
2998 * 1 : csp = Current client state (buffers, headers, etc...)
2999 * 2 : header = On input, pointer to header to modify.
3000 * On output, pointer to the modified header, or NULL
3001 * to remove the header. This function frees the
3002 * original string if necessary.
3004 * Returns : JB_ERR_OK on success, or
3005 * JB_ERR_MEMORY on out-of-memory error.
3007 *********************************************************************/
3008 static jb_err client_te(struct client_state *csp, char **header)
3010 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3013 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3020 /*********************************************************************
3022 * Function : client_referrer
3024 * Description : Handle the "referer" config setting properly.
3025 * Called from `sed'.
3028 * 1 : csp = Current client state (buffers, headers, etc...)
3029 * 2 : header = On input, pointer to header to modify.
3030 * On output, pointer to the modified header, or NULL
3031 * to remove the header. This function frees the
3032 * original string if necessary.
3034 * Returns : JB_ERR_OK on success, or
3035 * JB_ERR_MEMORY on out-of-memory error.
3037 *********************************************************************/
3038 static jb_err client_referrer(struct client_state *csp, char **header)
3040 const char *parameter;
3041 /* booleans for parameters we have to check multiple times */
3042 int parameter_conditional_block;
3043 int parameter_conditional_forge;
3045 #ifdef FEATURE_FORCE_LOAD
3047 * Since the referrer can include the prefix even
3048 * if the request itself is non-forced, we must
3049 * clean it unconditionally.
3051 * XXX: strclean is too broad
3053 strclean(*header, FORCE_PREFIX);
3054 #endif /* def FEATURE_FORCE_LOAD */
3056 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3058 /* Nothing left to do */
3062 parameter = csp->action->string[ACTION_STRING_REFERER];
3063 assert(parameter != NULL);
3064 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3065 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3067 if (!parameter_conditional_block && !parameter_conditional_forge)
3070 * As conditional-block and conditional-forge are the only
3071 * parameters that rely on the original referrer, we can
3072 * remove it now for all the others.
3077 if (0 == strcmpic(parameter, "block"))
3079 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3082 else if (parameter_conditional_block || parameter_conditional_forge)
3084 return handle_conditional_hide_referrer_parameter(header,
3085 csp->http->hostport, parameter_conditional_block);
3087 else if (0 == strcmpic(parameter, "forge"))
3089 return create_forged_referrer(header, csp->http->hostport);
3093 /* interpret parameter as user-supplied referer to fake */
3094 return create_fake_referrer(header, parameter);
3099 /*********************************************************************
3101 * Function : client_accept_language
3103 * Description : Handle the "Accept-Language" config setting properly.
3104 * Called from `sed'.
3107 * 1 : csp = Current client state (buffers, headers, etc...)
3108 * 2 : header = On input, pointer to header to modify.
3109 * On output, pointer to the modified header, or NULL
3110 * to remove the header. This function frees the
3111 * original string if necessary.
3113 * Returns : JB_ERR_OK on success, or
3114 * JB_ERR_MEMORY on out-of-memory error.
3116 *********************************************************************/
3117 static jb_err client_accept_language(struct client_state *csp, char **header)
3122 * Are we messing with the Accept-Language?
3124 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3126 /*I don't think so*/
3130 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3132 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3135 * Blocking Accept-Language header
3137 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3144 * Replacing Accept-Language header
3147 *header = strdup("Accept-Language: ");
3148 string_append(header, newval);
3150 if (*header == NULL)
3152 log_error(LOG_LEVEL_ERROR,
3153 "Insufficient memory. Accept-Language header crunched without replacement.");
3157 log_error(LOG_LEVEL_HEADER,
3158 "Accept-Language header crunched and replaced with: %s", *header);
3161 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3165 /*********************************************************************
3167 * Function : crunch_client_header
3169 * Description : Crunch client header if it matches a string supplied by the
3170 * user. Called from `sed'.
3173 * 1 : csp = Current client state (buffers, headers, etc...)
3174 * 2 : header = On input, pointer to header to modify.
3175 * On output, pointer to the modified header, or NULL
3176 * to remove the header. This function frees the
3177 * original string if necessary.
3179 * Returns : JB_ERR_OK on success and always succeeds
3181 *********************************************************************/
3182 static jb_err crunch_client_header(struct client_state *csp, char **header)
3184 const char *crunch_pattern;
3186 /* Do we feel like crunching? */
3187 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3189 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3191 /* Is the current header the lucky one? */
3192 if (strstr(*header, crunch_pattern))
3194 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3202 /*********************************************************************
3204 * Function : client_uagent
3206 * Description : Handle the "user-agent" config setting properly
3207 * and remember its original value to enable browser
3208 * bug workarounds. Called from `sed'.
3211 * 1 : csp = Current client state (buffers, headers, etc...)
3212 * 2 : header = On input, pointer to header to modify.
3213 * On output, pointer to the modified header, or NULL
3214 * to remove the header. This function frees the
3215 * original string if necessary.
3217 * Returns : JB_ERR_OK on success, or
3218 * JB_ERR_MEMORY on out-of-memory error.
3220 *********************************************************************/
3221 static jb_err client_uagent(struct client_state *csp, char **header)
3225 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3230 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3237 *header = strdup("User-Agent: ");
3238 string_append(header, newval);
3240 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3242 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3246 /*********************************************************************
3248 * Function : client_ua
3250 * Description : Handle "ua-" headers properly. Called from `sed'.
3253 * 1 : csp = Current client state (buffers, headers, etc...)
3254 * 2 : header = On input, pointer to header to modify.
3255 * On output, pointer to the modified header, or NULL
3256 * to remove the header. This function frees the
3257 * original string if necessary.
3259 * Returns : JB_ERR_OK on success, or
3260 * JB_ERR_MEMORY on out-of-memory error.
3262 *********************************************************************/
3263 static jb_err client_ua(struct client_state *csp, char **header)
3265 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3267 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3275 /*********************************************************************
3277 * Function : client_from
3279 * Description : Handle the "from" config setting properly.
3280 * Called from `sed'.
3283 * 1 : csp = Current client state (buffers, headers, etc...)
3284 * 2 : header = On input, pointer to header to modify.
3285 * On output, pointer to the modified header, or NULL
3286 * to remove the header. This function frees the
3287 * original string if necessary.
3289 * Returns : JB_ERR_OK on success, or
3290 * JB_ERR_MEMORY on out-of-memory error.
3292 *********************************************************************/
3293 static jb_err client_from(struct client_state *csp, char **header)
3297 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3304 newval = csp->action->string[ACTION_STRING_FROM];
3307 * Are we blocking the e-mail address?
3309 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3311 log_error(LOG_LEVEL_HEADER, "crunched From!");
3315 log_error(LOG_LEVEL_HEADER, " modified");
3317 *header = strdup("From: ");
3318 string_append(header, newval);
3320 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3324 /*********************************************************************
3326 * Function : client_send_cookie
3328 * Description : Crunches the "cookie" header if necessary.
3329 * Called from `sed'.
3331 * XXX: Stupid name, doesn't send squat.
3334 * 1 : csp = Current client state (buffers, headers, etc...)
3335 * 2 : header = On input, pointer to header to modify.
3336 * On output, pointer to the modified header, or NULL
3337 * to remove the header. This function frees the
3338 * original string if necessary.
3340 * Returns : JB_ERR_OK on success, or
3341 * JB_ERR_MEMORY on out-of-memory error.
3343 *********************************************************************/
3344 static jb_err client_send_cookie(struct client_state *csp, char **header)
3346 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3348 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3356 /*********************************************************************
3358 * Function : client_x_forwarded
3360 * Description : Handle the "x-forwarded-for" config setting properly,
3361 * also used in the add_client_headers list. Called from `sed'.
3364 * 1 : csp = Current client state (buffers, headers, etc...)
3365 * 2 : header = On input, pointer to header to modify.
3366 * On output, pointer to the modified header, or NULL
3367 * to remove the header. This function frees the
3368 * original string if necessary.
3370 * Returns : JB_ERR_OK on success, or
3371 * JB_ERR_MEMORY on out-of-memory error.
3373 *********************************************************************/
3374 jb_err client_x_forwarded(struct client_state *csp, char **header)
3376 int block_header = (((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3377 || ((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR) &&
3378 (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "block"))));
3383 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3385 else if (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add"))
3387 /* Save it so we can re-add it later */
3388 freez(csp->x_forwarded_for);
3389 csp->x_forwarded_for = *header;
3392 * Always set *header = NULL, since this information
3393 * will be sent at the end of the header.
3402 /*********************************************************************
3404 * Function : client_max_forwards
3406 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3407 * from the value of the Max-Forwards header field.
3410 * 1 : csp = Current client state (buffers, headers, etc...)
3411 * 2 : header = On input, pointer to header to modify.
3412 * On output, pointer to the modified header, or NULL
3413 * to remove the header. This function frees the
3414 * original string if necessary.
3416 * Returns : JB_ERR_OK on success, or
3417 * JB_ERR_MEMORY on out-of-memory error.
3419 *********************************************************************/
3420 static jb_err client_max_forwards(struct client_state *csp, char **header)
3424 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3425 (0 == strcmpic(csp->http->gpc, "options")))
3427 assert(*(*header+12) == ':');
3428 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3430 if (max_forwards > 0)
3432 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3433 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3434 csp->http->gpc, max_forwards);
3436 else if (max_forwards < 0)
3438 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3444 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3453 /*********************************************************************
3455 * Function : client_host
3457 * Description : If the request URI did not contain host and
3458 * port information, parse and evaluate the Host
3461 * Also, kill ill-formed HOST: headers as sent by
3462 * Apple's iTunes software when used with a proxy.
3465 * 1 : csp = Current client state (buffers, headers, etc...)
3466 * 2 : header = On input, pointer to header to modify.
3467 * On output, pointer to the modified header, or NULL
3468 * to remove the header. This function frees the
3469 * original string if necessary.
3471 * Returns : JB_ERR_OK on success, or
3472 * JB_ERR_MEMORY on out-of-memory error.
3474 *********************************************************************/
3475 static jb_err client_host(struct client_state *csp, char **header)
3480 * If the header field name is all upper-case, chances are that it's
3481 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3482 * not a problem -- they are regenerated later.
3484 if ((*header)[1] == 'O')
3486 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3491 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3492 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3495 if (NULL == (p = strdup((*header)+6)))
3497 return JB_ERR_MEMORY;
3500 if (NULL == (q = strdup(p)))
3503 return JB_ERR_MEMORY;
3506 freez(csp->http->hostport);
3507 csp->http->hostport = p;
3508 freez(csp->http->host);
3509 csp->http->host = q;
3510 q = strchr(csp->http->host, ':');
3513 /* Terminate hostname and evaluate port string */
3515 csp->http->port = atoi(q);
3519 csp->http->port = csp->http->ssl ? 443 : 80;
3522 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3523 csp->http->hostport, csp->http->host, csp->http->port);
3526 /* Signal client_host_adder() to return right away */
3527 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3533 /*********************************************************************
3535 * Function : client_if_modified_since
3537 * Description : Remove or modify the If-Modified-Since header.
3540 * 1 : csp = Current client state (buffers, headers, etc...)
3541 * 2 : header = On input, pointer to header to modify.
3542 * On output, pointer to the modified header, or NULL
3543 * to remove the header. This function frees the
3544 * original string if necessary.
3546 * Returns : JB_ERR_OK on success, or
3547 * JB_ERR_MEMORY on out-of-memory error.
3549 *********************************************************************/
3550 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3553 #ifdef HAVE_GMTIME_R
3556 struct tm *timeptr = NULL;
3560 long int hours, minutes, seconds;
3564 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3567 * The client got an error message because of a temporary problem,
3568 * the problem is gone and the client now tries to revalidate our
3569 * error message on the real server. The revalidation would always
3570 * end with the transmission of the whole document and there is
3571 * no need to expose the bogus If-Modified-Since header.
3573 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3576 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3578 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3580 if ((0 == strcmpic(newval, "block")))
3582 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3585 else /* add random value */
3587 const char *header_time = *header + sizeof("If-Modified-Since:");
3589 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3591 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3596 rtime = strtol(newval, &endptr, 0);
3599 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3600 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3607 rtime = pick_from_range(rtime);
3611 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3614 tm += rtime * (negative ? -1 : 1);
3615 #ifdef HAVE_GMTIME_R
3616 timeptr = gmtime_r(&tm, &gmt);
3617 #elif FEATURE_PTHREAD
3618 privoxy_mutex_lock(&gmtime_mutex);
3619 timeptr = gmtime(&tm);
3620 privoxy_mutex_unlock(&gmtime_mutex);
3622 timeptr = gmtime(&tm);
3624 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3627 *header = strdup("If-Modified-Since: ");
3628 string_append(header, newheader);
3630 if (*header == NULL)
3632 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3633 return JB_ERR_MEMORY;
3636 hours = rtime / 3600;
3637 minutes = rtime / 60 % 60;
3638 seconds = rtime % 60;
3640 log_error(LOG_LEVEL_HEADER,
3641 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3642 *header, (negative) ? "subtracted" : "added", hours,
3643 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3644 seconds, (seconds == 1) ? ")" : "s)");
3653 /*********************************************************************
3655 * Function : client_if_none_match
3657 * Description : Remove the If-None-Match header.
3660 * 1 : csp = Current client state (buffers, headers, etc...)
3661 * 2 : header = On input, pointer to header to modify.
3662 * On output, pointer to the modified header, or NULL
3663 * to remove the header. This function frees the
3664 * original string if necessary.
3666 * Returns : JB_ERR_OK on success, or
3667 * JB_ERR_MEMORY on out-of-memory error.
3669 *********************************************************************/
3670 static jb_err client_if_none_match(struct client_state *csp, char **header)
3672 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3674 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3682 /*********************************************************************
3684 * Function : client_x_filter
3686 * Description : Disables filtering if the client set "X-Filter: No".
3687 * Called from `sed'.
3690 * 1 : csp = Current client state (buffers, headers, etc...)
3691 * 2 : header = On input, pointer to header to modify.
3692 * On output, pointer to the modified header, or NULL
3693 * to remove the header. This function frees the
3694 * original string if necessary.
3696 * Returns : JB_ERR_OK on success
3698 *********************************************************************/
3699 jb_err client_x_filter(struct client_state *csp, char **header)
3701 if ( 0 == strcmpic(*header, "X-Filter: No"))
3703 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3705 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3709 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3711 log_error(LOG_LEVEL_HEADER,
3712 "force-text-mode overruled the client's request to fetch without filtering!");
3716 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3717 csp->flags |= CSP_FLAG_NO_FILTERING;
3718 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3720 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3728 /*********************************************************************
3730 * Function : client_range
3732 * Description : Removes Range, Request-Range and If-Range headers if
3733 * content filtering is enabled. If the client's version
3734 * of the document has been altered by Privoxy, the server
3735 * could interpret the range differently than the client
3736 * intended in which case the user could end up with
3737 * corrupted content.
3740 * 1 : csp = Current client state (buffers, headers, etc...)
3741 * 2 : header = On input, pointer to header to modify.
3742 * On output, pointer to the modified header, or NULL
3743 * to remove the header. This function frees the
3744 * original string if necessary.
3746 * Returns : JB_ERR_OK
3748 *********************************************************************/
3749 static jb_err client_range(struct client_state *csp, char **header)
3751 if (content_filters_enabled(csp->action))
3753 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3754 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3761 /* the following functions add headers directly to the header list */
3763 /*********************************************************************
3765 * Function : client_host_adder
3767 * Description : Adds the Host: header field if it is missing.
3768 * Called from `sed'.
3771 * 1 : csp = Current client state (buffers, headers, etc...)
3773 * Returns : JB_ERR_OK on success, or
3774 * JB_ERR_MEMORY on out-of-memory error.
3776 *********************************************************************/
3777 static jb_err client_host_adder(struct client_state *csp)
3782 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3784 /* Header already set by the client, nothing to do. */
3788 if ( !csp->http->hostport || !*(csp->http->hostport))
3790 /* XXX: When does this happen and why is it OK? */
3791 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3796 * remove 'user:pass@' from 'proto://user:pass@host'
3798 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3804 p = csp->http->hostport;
3807 /* XXX: Just add it, we already made sure that it will be unique */
3808 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3809 err = enlist_unique_header(csp->headers, "Host", p);
3816 /*********************************************************************
3818 * Function : client_accept_encoding_adder
3820 * Description : Add an Accept-Encoding header to the client's request
3821 * that disables compression if the action applies, and
3822 * the header is not already there. Called from `sed'.
3823 * Note: For HTTP/1.0, the absence of the header is enough.
3826 * 1 : csp = Current client state (buffers, headers, etc...)
3828 * Returns : JB_ERR_OK on success, or
3829 * JB_ERR_MEMORY on out-of-memory error.
3831 *********************************************************************/
3832 static jb_err client_accept_encoding_adder(struct client_state *csp)
3834 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3835 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3837 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3845 /*********************************************************************
3847 * Function : client_xtra_adder
3849 * Description : Used in the add_client_headers list. Called from `sed'.
3852 * 1 : csp = Current client state (buffers, headers, etc...)
3854 * Returns : JB_ERR_OK on success, or
3855 * JB_ERR_MEMORY on out-of-memory error.
3857 *********************************************************************/
3858 static jb_err client_xtra_adder(struct client_state *csp)
3860 struct list_entry *lst;
3863 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3864 lst ; lst = lst->next)
3866 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3867 err = enlist(csp->headers, lst->str);
3879 /*********************************************************************
3881 * Function : client_x_forwarded_for_adder
3883 * Description : Used in the add_client_headers list. Called from `sed'.
3886 * 1 : csp = Current client state (buffers, headers, etc...)
3888 * Returns : JB_ERR_OK on success, or
3889 * JB_ERR_MEMORY on out-of-memory error.
3891 *********************************************************************/
3892 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3894 char *header = NULL;
3897 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR) &&
3898 (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add"))))
3903 if (csp->x_forwarded_for)
3905 header = strdup(csp->x_forwarded_for);
3906 string_append(&header, ", ");
3910 header = strdup("X-Forwarded-For: ");
3912 string_append(&header, csp->ip_addr_str);
3916 return JB_ERR_MEMORY;
3919 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3920 err = enlist(csp->headers, header);
3927 /*********************************************************************
3929 * Function : connection_close_adder
3931 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3932 * support. Adds a "Connection: close" header to csp->headers
3933 * unless the header was already present. Called from `sed'.
3935 * FIXME: This whole function shouldn't be neccessary!
3938 * 1 : csp = Current client state (buffers, headers, etc...)
3940 * Returns : JB_ERR_OK on success, or
3941 * JB_ERR_MEMORY on out-of-memory error.
3943 *********************************************************************/
3944 static jb_err connection_close_adder(struct client_state *csp)
3946 const unsigned int flags = csp->flags;
3949 * Return right away if
3951 * - we're parsing server headers and the server header
3952 * "Connection: close" is already set, or if
3954 * - we're parsing client headers and the client header
3955 * "Connection: close" is already set.
3957 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3958 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3959 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3960 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3965 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3967 return enlist(csp->headers, "Connection: close");
3971 /*********************************************************************
3973 * Function : server_http
3975 * Description : - Save the HTTP Status into csp->http->status
3976 * - Set CT_TABOO to prevent filtering if the answer
3977 * is a partial range (HTTP status 206)
3978 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3982 * 1 : csp = Current client state (buffers, headers, etc...)
3983 * 2 : header = On input, pointer to header to modify.
3984 * On output, pointer to the modified header, or NULL
3985 * to remove the header. This function frees the
3986 * original string if necessary.
3988 * Returns : JB_ERR_OK on success, or
3989 * JB_ERR_MEMORY on out-of-memory error.
3991 *********************************************************************/
3992 static jb_err server_http(struct client_state *csp, char **header)
3994 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3995 if (csp->http->status == 206)
3997 csp->content_type = CT_TABOO;
4000 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4002 /* XXX: Should we do a real validity check here? */
4003 if (strlen(*header) > 8)
4006 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4011 * XXX: Should we block the request or
4012 * enlist a valid status code line here?
4014 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4015 "Downgrading to HTTP/1.0 impossible.");
4023 /*********************************************************************
4025 * Function : server_set_cookie
4027 * Description : Handle the server "cookie" header properly.
4028 * Log cookie to the jar file. Then "crunch",
4029 * accept or rewrite it to a session cookie.
4030 * Called from `sed'.
4032 * TODO: Allow the user to specify a new expiration
4033 * time to cause the cookie to expire even before the
4034 * browser is closed.
4037 * 1 : csp = Current client state (buffers, headers, etc...)
4038 * 2 : header = On input, pointer to header to modify.
4039 * On output, pointer to the modified header, or NULL
4040 * to remove the header. This function frees the
4041 * original string if necessary.
4043 * Returns : JB_ERR_OK on success, or
4044 * JB_ERR_MEMORY on out-of-memory error.
4046 *********************************************************************/
4047 static jb_err server_set_cookie(struct client_state *csp, char **header)
4054 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4056 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4059 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4061 /* Flag whether or not to log a message */
4064 /* A variable to store the tag we're working on */
4067 /* Skip "Set-Cookie:" (11 characters) in header */
4068 cur_tag = *header + 11;
4070 /* skip whitespace between "Set-Cookie:" and value */
4071 while (*cur_tag && ijb_isspace(*cur_tag))
4076 /* Loop through each tag in the cookie */
4080 char *next_tag = strchr(cur_tag, ';');
4081 if (next_tag != NULL)
4083 /* Skip the ';' character itself */
4086 /* skip whitespace ";" and start of tag */
4087 while (*next_tag && ijb_isspace(*next_tag))
4094 /* "Next tag" is the end of the string */
4095 next_tag = cur_tag + strlen(cur_tag);
4099 * Check the expiration date to see
4100 * if the cookie is still valid, if yes,
4101 * rewrite it to a session cookie.
4103 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4105 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4107 /* Did we detect the date properly? */
4108 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4111 * Nope, treat it as if it was still valid.
4113 * XXX: Should we remove the whole cookie instead?
4115 log_error(LOG_LEVEL_ERROR,
4116 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4117 string_move(cur_tag, next_tag);
4123 * Yes. Check if the cookie is still valid.
4125 * If the cookie is already expired it's probably
4126 * a delete cookie and even if it isn't, the browser
4127 * will discard it anyway.
4131 * XXX: timegm() isn't available on some AmigaOS
4132 * versions and our replacement doesn't work.
4134 * Our options are to either:
4136 * - disable session-cookies-only completely if timegm
4139 * - to simply remove all expired tags, like it has
4140 * been done until Privoxy 3.0.6 and to live with
4141 * the consequence that it can cause login/logout
4142 * problems on servers that don't validate their
4143 * input properly, or
4145 * - to replace it with mktime in which
4146 * case there is a slight chance of valid cookies
4147 * passing as already expired.
4149 * This is the way it's currently done and it's not
4150 * as bad as it sounds. If the missing GMT offset is
4151 * enough to change the result of the expiration check
4152 * the cookie will be only valid for a few hours
4153 * anyway, which in many cases will be shorter
4154 * than a browser session.
4156 if (cookie_time - now < 0)
4158 log_error(LOG_LEVEL_HEADER,
4159 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4160 /* Just in case some clown sets more then one expiration date */
4166 * Still valid, delete expiration date by copying
4167 * the rest of the string over it.
4169 string_move(cur_tag, next_tag);
4171 /* That changed the header, need to issue a log message */
4175 * Note that the next tag has now been moved to *cur_tag,
4176 * so we do not need to update the cur_tag pointer.
4184 /* Move on to next cookie tag */
4191 assert(NULL != *header);
4192 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4201 #ifdef FEATURE_FORCE_LOAD
4202 /*********************************************************************
4204 * Function : strclean
4206 * Description : In-Situ-Eliminate all occurances of substring in
4210 * 1 : string = string to clean
4211 * 2 : substring = substring to eliminate
4213 * Returns : Number of eliminations
4215 *********************************************************************/
4216 int strclean(char *string, const char *substring)
4222 len = strlen(substring);
4224 while((pos = strstr(string, substring)) != NULL)
4231 while (*p++ != '\0');
4238 #endif /* def FEATURE_FORCE_LOAD */
4241 /*********************************************************************
4243 * Function : parse_header_time
4245 * Description : Parses time formats used in HTTP header strings
4246 * to get the numerical respresentation.
4249 * 1 : header_time = HTTP header time as string.
4250 * 2 : result = storage for header_time in seconds
4252 * Returns : JB_ERR_OK if the time format was recognized, or
4253 * JB_ERR_PARSE otherwise.
4255 *********************************************************************/
4256 static jb_err parse_header_time(const char *header_time, time_t *result)
4261 * Zero out gmt to prevent time zone offsets.
4263 * While this is only necessary on some platforms
4264 * (mingw32 for example), I don't know how to
4265 * detect these automatically and doing it everywhere
4268 memset(&gmt, 0, sizeof(gmt));
4270 /* Tue, 02 Jun 2037 20:00:00 */
4271 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4272 /* Tue, 02-Jun-2037 20:00:00 */
4273 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4274 /* Tue, 02-Jun-37 20:00:00 */
4275 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4276 /* Tuesday, 02-Jun-2037 20:00:00 */
4277 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4278 /* Tuesday Jun 02 20:00:00 2037 */
4279 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4281 return JB_ERR_PARSE;
4284 *result = timegm(&gmt);
4291 /*********************************************************************
4293 * Function : get_destination_from_headers
4295 * Description : Parse the "Host:" header to get the request's destination.
4296 * Only needed if the client's request was forcefully
4297 * redirected into Privoxy.
4299 * Code mainly copied from client_host() which is currently
4300 * run too late for this purpose.
4303 * 1 : headers = List of headers (one of them hopefully being
4304 * the "Host:" header)
4305 * 2 : http = storage for the result (host, port and hostport).
4307 * Returns : JB_ERR_MEMORY in case of memory problems,
4308 * JB_ERR_PARSE if the host header couldn't be found,
4309 * JB_ERR_OK otherwise.
4311 *********************************************************************/
4312 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4318 host = get_header_value(headers, "Host:");
4322 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4323 return JB_ERR_PARSE;
4326 if (NULL == (p = strdup((host))))
4328 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4329 return JB_ERR_MEMORY;
4332 if (NULL == (q = strdup(p)))
4335 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4336 return JB_ERR_MEMORY;
4339 freez(http->hostport);
4343 q = strchr(http->host, ':');
4346 /* Terminate hostname and evaluate port string */
4348 http->port = atoi(q);
4352 http->port = http->ssl ? 443 : 80;
4355 /* Rebuild request URL */
4357 http->url = strdup(http->ssl ? "https://" : "http://");
4358 string_append(&http->url, http->hostport);
4359 string_append(&http->url, http->path);
4360 if (http->url == NULL)
4362 return JB_ERR_MEMORY;
4365 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4373 /*********************************************************************
4375 * Function : create_forged_referrer
4377 * Description : Helper for client_referrer to forge a referer as
4378 * 'http://[hostname:port/' to fool stupid
4379 * checks for in-site links
4382 * 1 : header = Pointer to header pointer
4383 * 2 : hostport = Host and optionally port as string
4385 * Returns : JB_ERR_OK in case of success, or
4386 * JB_ERR_MEMORY in case of memory problems.
4388 *********************************************************************/
4389 static jb_err create_forged_referrer(char **header, const char *hostport)
4391 assert(NULL == *header);
4393 *header = strdup("Referer: http://");
4394 string_append(header, hostport);
4395 string_append(header, "/");
4397 if (NULL == *header)
4399 return JB_ERR_MEMORY;
4402 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4409 /*********************************************************************
4411 * Function : create_fake_referrer
4413 * Description : Helper for client_referrer to create a fake referrer
4414 * based on a string supplied by the user.
4417 * 1 : header = Pointer to header pointer
4418 * 2 : hosthost = Referrer to fake
4420 * Returns : JB_ERR_OK in case of success, or
4421 * JB_ERR_MEMORY in case of memory problems.
4423 *********************************************************************/
4424 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4426 assert(NULL == *header);
4428 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4430 log_error(LOG_LEVEL_HEADER,
4431 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4433 *header = strdup("Referer: ");
4434 string_append(header, fake_referrer);
4436 if (NULL == *header)
4438 return JB_ERR_MEMORY;
4441 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4448 /*********************************************************************
4450 * Function : handle_conditional_hide_referrer_parameter
4452 * Description : Helper for client_referrer to crunch or forge
4453 * the referrer header if the host has changed.
4456 * 1 : header = Pointer to header pointer
4457 * 2 : host = The target host (may include the port)
4458 * 3 : parameter_conditional_block = Boolean to signal
4459 * if we're in conditional-block mode. If not set,
4460 * we're in conditional-forge mode.
4462 * Returns : JB_ERR_OK in case of success, or
4463 * JB_ERR_MEMORY in case of memory problems.
4465 *********************************************************************/
4466 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4467 const char *host, const int parameter_conditional_block)
4469 char *referer = strdup(*header);
4470 const size_t hostlenght = strlen(host);
4472 if (NULL == referer)
4475 return JB_ERR_MEMORY;
4478 /* referer begins with 'Referer: http[s]://' */
4479 if (hostlenght < (strlen(referer)-17))
4482 * Shorten referer to make sure the referer is blocked
4483 * if www.example.org/www.example.com-shall-see-the-referer/
4484 * links to www.example.com/
4486 referer[hostlenght+17] = '\0';
4488 if (NULL == strstr(referer, host))
4490 /* Host has changed */
4491 if (parameter_conditional_block)
4493 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4500 return create_forged_referrer(header, host);