1 const char parsers_rcs[] = "$Id: parsers.c,v 1.135 2008/05/21 20:12:10 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.135 2008/05/21 20:12:10 fabiankeil
48 * The whole point of strclean() is to modify the
49 * first parameter, so don't mark it immutable,
50 * even though the compiler lets us get away with it.
52 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
53 * As the wafer actions are gone, we can stop including encode.h.
55 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
56 * Ditch cast from (char **) to (char **).
58 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
59 * Streamline sed()'s prototype and declare
60 * the header parse and add structures static.
62 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
63 * Factor update_server_headers() out of sed(), ditch the
64 * first_run hack and make server_patterns_light static.
66 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
67 * Wrap memmove() calls in string_move()
68 * to document the purpose in one place.
70 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
71 * Normalize linear header white space.
73 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
74 * If a header is split across multiple lines,
75 * merge them to a single line before parsing them.
77 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
78 * Don't provide get_header() with the whole client state
79 * structure when it only needs access to csp->iob.
81 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
82 * Change content_filters_enabled()'s parameter from
83 * csp->action to action so it can be also used in the
84 * CGI code. Don't bother checking if there are filters
85 * loaded, as that's somewhat besides the point.
87 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
88 * Provide get_http_time() with the buffer size so it doesn't
89 * have to blindly assume that the buffer is big enough.
91 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
92 * Don't pass the whole csp structure to flush_socket()
93 * when it only needs a file descriptor and a buffer.
95 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
96 * Remove send-wafer and send-vanilla-wafer actions.
98 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
99 * Remove inspect-jpegs action.
101 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
102 * Let client_range() also handle Request-Range headers
103 * which apparently are still supported by many servers.
105 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
106 * Improve the warning messages that get logged if the action files
107 * "enable" filters but no filters of that type have been loaded.
109 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
110 * In server_content_type():
111 * - Don't require leading white space when detecting image content types.
112 * - Change '... not replaced ...' message to sound less crazy if the text
113 * type actually is 'text/plain'.
114 * - Mark the 'text/plain == binary data' assumption for removal.
115 * - Remove a bunch of trailing white space.
117 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
118 * Minor server_content_disposition() changes:
119 * - Don't regenerate the header name all lower-case.
120 * - Some white space fixes.
121 * - Remove useless log message in case of ENOMEM.
123 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
124 * Garbage-collect the code to add a X-Forwarded-For
125 * header as it seems to be mostly used by accident.
127 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
128 * Fix a crash on mingw32 with some Last Modified times in the future.
130 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
131 * Remove a "can't happen" error block which, over
132 * time, mutated into a "guaranteed to happen" block.
134 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
135 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
136 * - Use shiny new content_filters_enabled() in client_range().
138 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
139 * I forgot about Poland.
141 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
142 * Remove Range and If-Range headers if content filtering is enabled.
144 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
145 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
146 * client_cookie_adder() to make sure send-vanilla-wafer can be
147 * controlled through tags (and thus regression-tested).
149 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
150 * - Remove "scanning headers for" log message again.
151 * - Some more whitespace fixes.
153 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
154 * Refactor client_referrer() and add conditional-forge parameter.
156 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
157 * A bunch of whitespace fixes, pointy hat to me.
159 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
160 * Fix possible memory corruption in server_http, make sure it's not
161 * executed for ordinary server headers and mark some problems for later.
163 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
164 * Let content-type-overwrite{} honour force-text-mode again.
166 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
167 * - Add prototpyes for the header parsers and make them static.
168 * - Comment out client_accept_encoding_adder() which isn't used right now.
170 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
171 * Move the ACTION_FORCE_TEXT_MODE check out of
172 * server_content_type(). Signal other functions
173 * whether or not a content type has been declared.
174 * Part of the fix for BR#1750917.
176 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
177 * Change sed() to return a jb_err in preparation for forward-override{}.
179 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
180 * Adjust "X-Filter: No" to disable dedicated header filters.
182 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
183 * Streamline client_cookie_adder().
185 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
186 * Make sure filters with dynamic jobs actually use them.
188 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
189 * - Introduce dynamic pcrs jobs that can resolve variables.
190 * - Remove unnecessary update_action_bits_for_all_tags() call.
192 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
193 * - Make tagging based on tags set by earlier taggers
194 * of the same kind possible.
195 * - Log whether or not new tags cause action bits updates
196 * (in which case a matching tag-pattern section exists).
197 * - Log if the user tries to set a tag that is already set.
199 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
200 * Introduce tags as alternative way to specify which
201 * actions apply to a request. At the moment tags can be
202 * created based on client and server headers.
204 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
205 * Log a warning if the content is compressed, filtering is
206 * enabled and Privoxy was compiled without zlib support.
209 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
210 * - Fix warnings when compiled with glibc.
211 * - Don't use crumble() for cookie crunching.
212 * - Move cookie time parsing into parse_header_time().
213 * - Let parse_header_time() return a jb_err code
214 * instead of a pointer that can only be used to
215 * check for NULL anyway.
217 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
218 * - Add better protection against malicious gzip headers.
219 * - Stop logging the first hundred bytes of decompressed content.
220 * It looks like it's working and there is always debug 16.
221 * - Log the content size after decompression in decompress_iob()
222 * instead of pcrs_filter_response().
224 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
225 * - Use dedicated header filter actions instead of abusing "filter".
226 * Replace "filter-client-headers" and "filter-client-headers"
227 * with "server-header-filter" and "client-header-filter".
228 * - Remove filter_client_header() and filter_client_header(),
229 * filter_header() now checks the shiny new
230 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
232 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
233 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
234 * - Handle "Cookie:" and "Connection:" headers a bit smarter
235 * (don't crunch them just to recreate them later on).
236 * - Add another non-standard time format for the cookie
237 * expiration date detection.
238 * - Fix a valgrind warning.
240 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
241 * Improve cookie expiration date detection.
243 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
244 * Don't run server_content_length() the first time
245 * sed() parses server headers; only adjust the
246 * Content-Length header if the page was modified.
248 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
249 * Fix log messages regarding the cookie time format
250 * (cookie and request URL were mixed up).
252 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
253 * - Let decompress_iob()
254 * - not corrupt the content if decompression fails
255 * early. (the first byte(s) were lost).
256 * - use pointer arithmetics with defined outcome for
258 * - Use a different kludge to remember a failed decompression.
260 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
261 * Search for Max-Forwards headers case-insensitive,
262 * don't generate the "501 unsupported" message for invalid
263 * Max-Forwards values and don't increase negative ones.
265 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
266 * - Let server_set_cookie() check the expiration date
267 * of cookies and don't touch the ones that are already
268 * expired. Fixes problems with low quality web applications
269 * as described in BR 932612.
271 * - Adjust comment in client_max_forwards to reality;
272 * remove invalid Max-Forwards headers.
274 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
275 * Stop filter_header() from unintentionally removing
276 * empty header lines that were enlisted by the continue
279 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
280 * - Repeat the request URL before logging any headers.
281 * Makes reading the log easier in case of simultaneous requests.
282 * - If there are more than one Content-Type headers in one request,
283 * use the first one and remove the others.
284 * - Remove "newval" variable in server_content_type().
285 * It's only used once.
287 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
288 * Correct a cast, check inflateEnd() exit code
289 * to see if we have to, replace sprintf calls
292 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
293 * Integrate a modified version of Wil Mahan's
294 * zlib patch (PR #895531).
296 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
297 * Skip empty filter files in filter_header()
298 * but don't ignore the ones that come afterwards.
299 * Fixes BR 1619208, this time for real.
301 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
302 * Reverted parts of my last commit
303 * to keep error handling working.
305 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
306 * Fixed gcc43 conversion warnings.
308 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
309 * Bringing back the "useless" localtime() call
310 * I removed in revision 1.67. On some platforms
311 * it's necessary to prevent time zone offsets.
313 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
314 * Rebuild request URL in get_destination_from_headers()
315 * to make sure redirect{pcrs command} works as expected
316 * for intercepted requests.
318 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
319 * Added get_destination_from_headers().
321 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
322 * Make pthread mutex locking more generic. Instead of
323 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
324 * and use mutex locking unless there is an _r function
325 * available. Better safe than sorry.
327 * Fixes "./configure --disable-pthread" and should result
328 * in less threading-related problems on pthread-using platforms,
329 * but it still doesn't fix BR#1122404.
331 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
332 * The special header "X-Filter: No" now disables
333 * header filtering as well.
335 * Revision 1.73 2006/09/23 13:26:38 roro
336 * Replace TABs by spaces in source code.
338 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
339 * Don't print a log message every time filter_headers is
340 * entered or left. It only creates noise without any real
343 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
344 * Fix +hide-if-modified-since{-n}.
346 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
347 * Have hide-if-modified-since interpret the random
348 * range value as minutes instead of hours. Allows
349 * more fine-grained configuration.
351 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
352 * Always have parse_header_time return a pointer
353 * that actual makes sense, even though we currently
354 * only need it to detect problems.
356 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
357 * Added config option enable-remote-http-toggle
358 * to specify if Privoxy should recognize special
359 * headers (currently only X-Filter) to change its
360 * behaviour. Disabled by default.
362 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
363 * After filtering de-chunked instances, remove
364 * "Transfer-Encoding" header entirely instead of changing
365 * it to "Transfer-Encoding: identity", which is invalid.
366 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
368 * Don't use localtime in parse_header_time. An empty time struct
369 * is good enough, it gets overwritten by strptime anyway.
371 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
372 * Use gmtime_r if available, fallback to gmtime with mutex
373 * protection for MacOSX and use vanilla gmtime for the rest.
375 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
376 * Changed client_referrer to use the right type (size_t) for
377 * hostlenght and to shorten the temporary referrer string with
378 * '\0' instead of adding a useless line break.
380 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
381 * - Back to timegm() using GnuPG's replacement if necessary.
382 * Using mktime() and localtime() could add a on hour offset if
383 * the randomize factor was big enough to lead to a summer/wintertime
386 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
388 * - Moved randomization code into pick_from_range().
390 * - Changed parse_header_time definition.
391 * time_t isn't guaranteed to be signed and
392 * if it isn't, -1 isn't available as error code.
393 * Changed some variable types in client_if_modified_since()
394 * because of the same reason.
396 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
397 * OS/2 compilation compatibility fixups
399 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
400 * Changed include from strptime.c to strptime.h
402 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
403 * Split filter-headers{} into filter-client-headers{}
404 * and filter-server-headers{}.
405 * Added parse_header_time() to share some code.
406 * Replaced timegm() with mktime().
408 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
409 * Windows service integration
411 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
412 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
414 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
415 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
416 * with what was really the latest development (the v_3_0_branch branch)
418 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
419 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
421 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
422 * Add the ability to check jpeg images for invalid
423 * lengths of comment blocks. Defensive strategy
424 * against the exploit:
425 * Microsoft Security Bulletin MS04-028
426 * Buffer Overrun in JPEG Processing (GDI+) Could
427 * Allow Code Execution (833987)
428 * Enabled with +inspect-jpegs in actions files.
430 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
431 * Excluded text/plain objects from filtering. This fixes a
432 * couple of client-crashing, download corruption and
433 * Privoxy performance issues, whose root cause lies in
434 * web servers labelling content of unknown type as text/plain.
436 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
437 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
439 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
440 * Completing the previous change
442 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
443 * Added temporary workaround for bug in PHP < 4.2.3
445 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
446 * 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.
448 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
449 * Fix typo: supressed -> suppressed
451 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
452 * Improved cookie logging
454 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
455 * Added basic support for OPTIONS and TRACE HTTP methods:
456 * - New parser function client_max_forwards which decrements
457 * the Max-Forwards HTTP header field of OPTIONS and TRACE
458 * requests by one before forwarding
459 * - New parser function client_host which extracts the host
460 * and port information from the HTTP header field if the
461 * request URI was not absolute
462 * - Don't crumble and re-add the Host: header, but only generate
463 * and append if missing
465 * Revision 1.56 2002/05/12 15:34:22 jongfoster
466 * Fixing typo in a comment
468 * Revision 1.55 2002/05/08 16:01:07 oes
469 * Optimized add_to_iob:
470 * - Use realloc instead of malloc(), memcpy(), free()
471 * - Expand to powers of two if possible, to get
472 * O(log n) reallocs instead of O(n).
473 * - Moved check for buffer limit here from chat
474 * - Report failure via returncode
476 * Revision 1.54 2002/04/02 15:03:16 oes
477 * Tiny code cosmetics
479 * Revision 1.53 2002/03/26 22:29:55 swa
480 * we have a new homepage!
482 * Revision 1.52 2002/03/24 13:25:43 swa
483 * name change related issues
485 * Revision 1.51 2002/03/13 00:27:05 jongfoster
488 * Revision 1.50 2002/03/12 01:45:35 oes
489 * More verbose logging
491 * Revision 1.49 2002/03/09 20:03:52 jongfoster
492 * - Making various functions return int rather than size_t.
493 * (Undoing a recent change). Since size_t is unsigned on
494 * Windows, functions like read_socket that return -1 on
495 * error cannot return a size_t.
497 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
498 * crashes, and also frequently caused JB to jump to 100%
499 * CPU and stay there. (Because it thought it had just
500 * read ((unsigned)-1) == 4Gb of data...)
502 * - The signature of write_socket has changed, it now simply
503 * returns success=0/failure=nonzero.
505 * - Trying to get rid of a few warnings --with-debug on
506 * Windows, I've introduced a new type "jb_socket". This is
507 * used for the socket file descriptors. On Windows, this
508 * is SOCKET (a typedef for unsigned). Everywhere else, it's
509 * an int. The error value can't be -1 any more, so it's
510 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
511 * Windows it maps to the #define INVALID_SOCKET.)
513 * - The signature of bind_port has changed.
515 * Revision 1.48 2002/03/07 03:46:53 oes
516 * Fixed compiler warnings etc
518 * Revision 1.47 2002/02/20 23:15:13 jongfoster
519 * Parsing functions now handle out-of-memory gracefully by returning
522 * Revision 1.46 2002/01/17 21:03:47 jongfoster
523 * Moving all our URL and URL pattern parsing code to urlmatch.c.
525 * Revision 1.45 2002/01/09 14:33:03 oes
526 * Added support for localtime_r.
528 * Revision 1.44 2001/12/14 01:22:54 steudten
529 * Remove 'user:pass@' from 'proto://user:pass@host' for the
530 * new added header 'Host: ..'. (See Req ID 491818)
532 * Revision 1.43 2001/11/23 00:26:38 jongfoster
533 * Fixing two really stupid errors in my previous commit
535 * Revision 1.42 2001/11/22 21:59:30 jongfoster
536 * Adding code to handle +no-cookies-keep
538 * Revision 1.41 2001/11/05 23:43:05 steudten
539 * Add time+date to log files.
541 * Revision 1.40 2001/10/26 20:13:09 jongfoster
542 * ctype.h is needed in Windows, too.
544 * Revision 1.39 2001/10/26 17:40:04 oes
545 * Introduced get_header_value()
546 * Removed http->user_agent, csp->referrer and csp->accept_types
547 * Removed client_accept()
549 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
550 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
551 * threads to call select() simultaneously. So, it's time to do a real, live,
552 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
553 * (native). Both versions will work, but using __OS2__ offers multi-threading.
555 * Revision 1.37 2001/10/23 21:36:02 jongfoster
556 * Documenting sed()'s error behaviou (doc change only)
558 * Revision 1.36 2001/10/13 12:51:51 joergs
559 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
560 * force-load), instead crumble Host: and add it (again) in client_host_adder
561 * (in case we get a HTTP/1.0 request without Host: header and forward it to
562 * a HTTP/1.1 server/proxy).
564 * Revision 1.35 2001/10/09 22:39:21 jongfoster
565 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
568 * Revision 1.34 2001/10/07 18:50:55 oes
569 * Added server_content_encoding, renamed server_transfer_encoding
571 * Revision 1.33 2001/10/07 18:04:49 oes
572 * Changed server_http11 to server_http and its pattern to "HTTP".
573 * Additional functionality: it now saves the HTTP status into
574 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
576 * Revision 1.32 2001/10/07 15:43:28 oes
577 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
578 * client_te and client_accept_encoding_adder, triggered by the new
579 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
580 * changed to allow only identity and chunked, and the TE header is
581 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
583 * parse_http_request no longer does anything than parsing. The rewriting
584 * of http->cmd and version mangling are gone. It now also recognizes
585 * the put and delete methods and saves the url in http->url. Removed
588 * renamed content_type and content_length to have the server_ prefix
590 * server_content_type now only works if csp->content_type != CT_TABOO
592 * added server_transfer_encoding, which
593 * - Sets CT_TABOO to prohibit filtering if encoding compresses
594 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
595 * - Change from "chunked" to "identity" if body was chunked
596 * but has been de-chunked for filtering.
598 * added server_content_md5 which crunches any Content-MD5 headers
599 * if the body was modified.
601 * made server_http11 conditional on +downgrade action
603 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
605 * Revision 1.31 2001/10/05 14:25:02 oes
606 * Crumble Keep-Alive from Server
608 * Revision 1.30 2001/09/29 12:56:03 joergs
609 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
611 * Revision 1.29 2001/09/24 21:09:24 jongfoster
612 * Fixing 2 memory leaks that Guy spotted, where the paramater to
613 * enlist() was not being free()d.
615 * Revision 1.28 2001/09/22 16:32:28 jongfoster
616 * Removing unused #includes.
618 * Revision 1.27 2001/09/20 15:45:25 steudten
620 * add casting from size_t to int for printf()
621 * remove local variable shadow s2
623 * Revision 1.26 2001/09/16 17:05:14 jongfoster
624 * Removing unused #include showarg.h
626 * Revision 1.25 2001/09/16 13:21:27 jongfoster
627 * Changes to use new list functions.
629 * Revision 1.24 2001/09/13 23:05:50 jongfoster
630 * Changing the string paramater to the header parsers a "const".
632 * Revision 1.23 2001/09/12 18:08:19 steudten
634 * In parse_http_request() header rewriting miss the host value, so
635 * from http://www.mydomain.com the result was just " / " not
636 * http://www.mydomain.com/ in case we forward.
638 * Revision 1.22 2001/09/10 10:58:53 oes
639 * Silenced compiler warnings
641 * Revision 1.21 2001/07/31 14:46:00 oes
642 * - Persistant connections now suppressed
643 * - sed() no longer appends empty header to csp->headers
645 * Revision 1.20 2001/07/30 22:08:36 jongfoster
646 * Tidying up #defines:
647 * - All feature #defines are now of the form FEATURE_xxx
648 * - Permanently turned off WIN_GUI_EDIT
649 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
651 * Revision 1.19 2001/07/25 17:21:54 oes
652 * client_uagent now saves copy of User-Agent: header value
654 * Revision 1.18 2001/07/13 14:02:46 oes
655 * - Included fix to repair broken HTTP requests that
656 * don't contain a path, not even '/'.
657 * - Removed all #ifdef PCRS
658 * - content_type now always inspected and classified as
659 * text, gif or other.
660 * - formatting / comments
662 * Revision 1.17 2001/06/29 21:45:41 oes
663 * Indentation, CRLF->LF, Tab-> Space
665 * Revision 1.16 2001/06/29 13:32:42 oes
667 * - Adapted free_http_request
668 * - Removed logentry from cancelled commit
670 * Revision 1.15 2001/06/03 19:12:38 oes
671 * deleted const struct interceptors
673 * Revision 1.14 2001/06/01 18:49:17 jongfoster
674 * Replaced "list_share" with "list" - the tiny memory gain was not
675 * worth the extra complexity.
677 * Revision 1.13 2001/05/31 21:30:33 jongfoster
678 * Removed list code - it's now in list.[ch]
679 * Renamed "permission" to "action", and changed many features
680 * to use the actions file rather than the global config.
682 * Revision 1.12 2001/05/31 17:33:13 oes
686 * Revision 1.11 2001/05/29 20:11:19 joergs
687 * '/ * inside comment' warning removed.
689 * Revision 1.10 2001/05/29 09:50:24 jongfoster
690 * Unified blocklist/imagelist/permissionslist.
691 * File format is still under discussion, but the internal changes
694 * Also modified interceptor behaviour:
695 * - We now intercept all URLs beginning with one of the following
696 * prefixes (and *only* these prefixes):
698 * * http://ijbswa.sf.net/config/
699 * * http://ijbswa.sourceforge.net/config/
700 * - New interceptors "home page" - go to http://i.j.b/ to see it.
701 * - Internal changes so that intercepted and fast redirect pages
702 * are not replaced with an image.
703 * - Interceptors now have the option to send a binary page direct
704 * to the client. (i.e. ijb-send-banner uses this)
705 * - Implemented show-url-info interceptor. (Which is why I needed
706 * the above interceptors changes - a typical URL is
707 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
708 * The previous mechanism would not have intercepted that, and
709 * if it had been intercepted then it then it would have replaced
712 * Revision 1.9 2001/05/28 17:26:33 jongfoster
713 * Fixing segfault if last header was crunched.
714 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
715 * can use the cross-platform sprintf() instead.)
717 * Revision 1.8 2001/05/27 22:17:04 oes
719 * - re_process_buffer no longer writes the modified buffer
720 * to the client, which was very ugly. It now returns the
721 * buffer, which it is then written by chat.
723 * - content_length now adjusts the Content-Length: header
724 * for modified documents rather than crunch()ing it.
725 * (Length info in csp->content_length, which is 0 for
726 * unmodified documents)
728 * - For this to work, sed() is called twice when filtering.
730 * Revision 1.7 2001/05/27 13:19:06 oes
731 * Patched Joergs solution for the content-length in.
733 * Revision 1.6 2001/05/26 13:39:32 jongfoster
734 * Only crunches Content-Length header if applying RE filtering.
735 * Without this fix, Microsoft Windows Update wouldn't work.
737 * Revision 1.5 2001/05/26 00:28:36 jongfoster
738 * Automatic reloading of config file.
739 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
740 * Most of the global variables have been moved to a new
741 * struct configuration_spec, accessed through csp->config->globalname
742 * Most of the globals remaining are used by the Win32 GUI.
744 * Revision 1.4 2001/05/22 18:46:04 oes
746 * - Enabled filtering banners by size rather than URL
747 * by adding patterns that replace all standard banner
748 * sizes with the "Junkbuster" gif to the re_filterfile
750 * - Enabled filtering WebBugs by providing a pattern
751 * which kills all 1x1 images
753 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
754 * which is selected by the (nonstandard and therefore
755 * capital) letter 'U' in the option string.
756 * It causes the quantifiers to be ungreedy by default.
757 * Appending a ? turns back to greedy (!).
759 * - Added a new interceptor ijb-send-banner, which
760 * sends back the "Junkbuster" gif. Without imagelist or
761 * MSIE detection support, or if tinygif = 1, or the
762 * URL isn't recognized as an imageurl, a lame HTML
763 * explanation is sent instead.
765 * - Added new feature, which permits blocking remote
766 * script redirects and firing back a local redirect
768 * The feature is conditionally compiled, i.e. it
769 * can be disabled with --disable-fast-redirects,
770 * plus it must be activated by a "fast-redirects"
771 * line in the config file, has its own log level
772 * and of course wants to be displayed by show-proxy-args
773 * Note: Boy, all the #ifdefs in 1001 locations and
774 * all the fumbling with configure.in and acconfig.h
775 * were *way* more work than the feature itself :-(
777 * - Because a generic redirect template was needed for
778 * this, tinygif = 3 now uses the same.
780 * - Moved GIFs, and other static HTTP response templates
785 * - Removed some >400 CRs again (Jon, you really worked
788 * Revision 1.3 2001/05/20 01:21:20 jongfoster
789 * Version 2.9.4 checkin.
790 * - Merged popupfile and cookiefile, and added control over PCRS
791 * filtering, in new "permissionsfile".
792 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
793 * file error you now get a message box (in the Win32 GUI) rather
794 * than the program exiting with no explanation.
795 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
797 * - Removed tabs from "config"
798 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
799 * - Bumped up version number.
801 * Revision 1.2 2001/05/17 23:02:36 oes
802 * - Made referrer option accept 'L' as a substitute for '§'
804 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
805 * Initial import of version 2.9.3 source tree
808 *********************************************************************/
815 #include <sys/types.h>
825 * Convince GNU's libc to provide a strptime prototype.
828 #endif /*__GLIBC__ */
835 #if !defined(_WIN32) && !defined(__OS2__)
841 #ifdef FEATURE_PTHREAD
843 /* jcc.h is for mutex semapores only */
844 #endif /* def FEATURE_PTHREAD */
849 #include "jbsockets.h"
850 #include "miscutil.h"
855 #ifndef HAVE_STRPTIME
856 #include "strptime.h"
859 const char parsers_h_rcs[] = PARSERS_H_VERSION;
861 /* Fix a problem with Solaris. There should be no effect on other
863 * Solaris's isspace() is a macro which uses its argument directly
864 * as an array index. Therefore we need to make sure that high-bit
865 * characters generate +ve values, and ideally we also want to make
866 * the argument match the declared parameter type of "int".
868 * Why did they write a character function that can't take a simple
869 * "char" argument? Doh!
871 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
872 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
874 static char *get_header_line(struct iob *iob);
875 static jb_err scan_headers(struct client_state *csp);
876 static jb_err header_tagger(struct client_state *csp, char *header);
877 static jb_err parse_header_time(const char *header_time, time_t *result);
879 static jb_err crumble (struct client_state *csp, char **header);
880 static jb_err connection (struct client_state *csp, char **header);
881 static jb_err filter_header (struct client_state *csp, char **header);
882 static jb_err client_referrer (struct client_state *csp, char **header);
883 static jb_err client_uagent (struct client_state *csp, char **header);
884 static jb_err client_ua (struct client_state *csp, char **header);
885 static jb_err client_from (struct client_state *csp, char **header);
886 static jb_err client_send_cookie (struct client_state *csp, char **header);
887 static jb_err client_x_forwarded (struct client_state *csp, char **header);
888 static jb_err client_accept_encoding (struct client_state *csp, char **header);
889 static jb_err client_te (struct client_state *csp, char **header);
890 static jb_err client_max_forwards (struct client_state *csp, char **header);
891 static jb_err client_host (struct client_state *csp, char **header);
892 static jb_err client_if_modified_since (struct client_state *csp, char **header);
893 static jb_err client_accept_language (struct client_state *csp, char **header);
894 static jb_err client_if_none_match (struct client_state *csp, char **header);
895 static jb_err crunch_client_header (struct client_state *csp, char **header);
896 static jb_err client_x_filter (struct client_state *csp, char **header);
897 static jb_err client_range (struct client_state *csp, char **header);
898 static jb_err server_set_cookie (struct client_state *csp, char **header);
899 static jb_err server_content_type (struct client_state *csp, char **header);
900 static jb_err server_content_length (struct client_state *csp, char **header);
901 static jb_err server_content_md5 (struct client_state *csp, char **header);
902 static jb_err server_content_encoding (struct client_state *csp, char **header);
903 static jb_err server_transfer_coding (struct client_state *csp, char **header);
904 static jb_err server_http (struct client_state *csp, char **header);
905 static jb_err crunch_server_header (struct client_state *csp, char **header);
906 static jb_err server_last_modified (struct client_state *csp, char **header);
907 static jb_err server_content_disposition(struct client_state *csp, char **header);
909 static jb_err client_host_adder (struct client_state *csp);
910 static jb_err client_xtra_adder (struct client_state *csp);
911 static jb_err connection_close_adder (struct client_state *csp);
913 static jb_err create_forged_referrer(char **header, const char *hostport);
914 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
915 static jb_err handle_conditional_hide_referrer_parameter(char **header,
916 const char *host, const int parameter_conditional_block);
919 * List of functions to run on a list of headers.
923 /** The header prefix to match */
926 /** The length of the prefix to match */
929 /** The function to apply to this line */
930 const parser_func_ptr parser;
933 static const struct parsers client_patterns[] = {
934 { "referer:", 8, client_referrer },
935 { "user-agent:", 11, client_uagent },
936 { "ua-", 3, client_ua },
937 { "from:", 5, client_from },
938 { "cookie:", 7, client_send_cookie },
939 { "x-forwarded-for:", 16, client_x_forwarded },
940 { "Accept-Encoding:", 16, client_accept_encoding },
941 { "TE:", 3, client_te },
942 { "Host:", 5, client_host },
943 { "if-modified-since:", 18, client_if_modified_since },
944 { "Keep-Alive:", 11, crumble },
945 { "connection:", 11, connection },
946 { "proxy-connection:", 17, crumble },
947 { "max-forwards:", 13, client_max_forwards },
948 { "Accept-Language:", 16, client_accept_language },
949 { "if-none-match:", 14, client_if_none_match },
950 { "Range:", 6, client_range },
951 { "Request-Range:", 14, client_range },
952 { "If-Range:", 9, client_range },
953 { "X-Filter:", 9, client_x_filter },
954 { "*", 0, crunch_client_header },
955 { "*", 0, filter_header },
959 static const struct parsers server_patterns[] = {
960 { "HTTP/", 5, server_http },
961 { "set-cookie:", 11, server_set_cookie },
962 { "connection:", 11, connection },
963 { "Content-Type:", 13, server_content_type },
964 { "Content-MD5:", 12, server_content_md5 },
965 { "Content-Encoding:", 17, server_content_encoding },
966 { "Transfer-Encoding:", 18, server_transfer_coding },
967 { "Keep-Alive:", 11, crumble },
968 { "content-disposition:", 20, server_content_disposition },
969 { "Last-Modified:", 14, server_last_modified },
970 { "*", 0, crunch_server_header },
971 { "*", 0, filter_header },
975 static const add_header_func_ptr add_client_headers[] = {
978 /* Temporarily disabled: client_accept_encoding_adder, */
979 connection_close_adder,
983 static const add_header_func_ptr add_server_headers[] = {
984 connection_close_adder,
988 /*********************************************************************
990 * Function : flush_socket
992 * Description : Write any pending "buffered" content.
995 * 1 : fd = file descriptor of the socket to read
996 * 2 : iob = The I/O buffer to flush, usually csp->iob.
998 * Returns : On success, the number of bytes written are returned (zero
999 * indicates nothing was written). On error, -1 is returned,
1000 * and errno is set appropriately. If count is zero and the
1001 * file descriptor refers to a regular file, 0 will be
1002 * returned without causing any other effect. For a special
1003 * file, the results are not portable.
1005 *********************************************************************/
1006 int flush_socket(jb_socket fd, struct iob *iob)
1008 int len = iob->eod - iob->cur;
1015 if (write_socket(fd, iob->cur, (size_t)len))
1019 iob->eod = iob->cur = iob->buf;
1025 /*********************************************************************
1027 * Function : add_to_iob
1029 * Description : Add content to the buffered page, expanding the
1030 * buffer if necessary.
1033 * 1 : csp = Current client state (buffers, headers, etc...)
1034 * 2 : buf = holds the content to be added to the page
1035 * 3 : n = number of bytes to be added
1037 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1038 * or buffer limit reached.
1040 *********************************************************************/
1041 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1043 struct iob *iob = csp->iob;
1044 size_t used, offset, need, want;
1047 if (n <= 0) return JB_ERR_OK;
1049 used = (size_t)(iob->eod - iob->buf);
1050 offset = (size_t)(iob->cur - iob->buf);
1051 need = used + (size_t)n + 1;
1054 * If the buffer can't hold the new data, extend it first.
1055 * Use the next power of two if possible, else use the actual need.
1057 if (need > csp->config->buffer_limit)
1059 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1060 return JB_ERR_MEMORY;
1063 if (need > iob->size)
1065 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1067 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1071 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1077 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1078 return JB_ERR_MEMORY;
1081 /* Update the iob pointers */
1082 iob->cur = p + offset;
1083 iob->eod = p + used;
1087 /* copy the new data into the iob buffer */
1088 memcpy(iob->eod, buf, (size_t)n);
1090 /* point to the end of the data */
1093 /* null terminate == cheap insurance */
1102 /*********************************************************************
1104 * Function : decompress_iob
1106 * Description : Decompress buffered page, expanding the
1107 * buffer as necessary. csp->iob->cur
1108 * should point to the the beginning of the
1109 * compressed data block.
1112 * 1 : csp = Current client state (buffers, headers, etc...)
1114 * Returns : JB_ERR_OK on success,
1115 * JB_ERR_MEMORY if out-of-memory limit reached, and
1116 * JB_ERR_COMPRESS if error decompressing buffer.
1118 *********************************************************************/
1119 jb_err decompress_iob(struct client_state *csp)
1121 char *buf; /* new, uncompressed buffer */
1122 char *cur; /* Current iob position (to keep the original
1123 * iob->cur unmodified if we return early) */
1124 size_t bufsize; /* allocated size of the new buffer */
1125 size_t old_size; /* Content size before decompression */
1126 size_t skip_size; /* Number of bytes at the beginning of the iob
1127 that we should NOT decompress. */
1128 int status; /* return status of the inflate() call */
1129 z_stream zstr; /* used by calls to zlib */
1131 assert(csp->iob->cur - csp->iob->buf > 0);
1132 assert(csp->iob->eod - csp->iob->cur > 0);
1134 bufsize = csp->iob->size;
1135 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1136 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1138 cur = csp->iob->cur;
1143 * This is to protect the parsing of gzipped data,
1144 * but it should(?) be valid for deflated data also.
1146 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1147 return JB_ERR_COMPRESS;
1150 if (csp->content_type & CT_GZIP)
1153 * Our task is slightly complicated by the facts that data
1154 * compressed by gzip does not include a zlib header, and
1155 * that there is no easily accessible interface in zlib to
1156 * handle a gzip header. We strip off the gzip header by
1157 * hand, and later inform zlib not to expect a header.
1161 * Strip off the gzip header. Please see RFC 1952 for more
1162 * explanation of the appropriate fields.
1164 if ((*cur++ != (char)0x1f)
1165 || (*cur++ != (char)0x8b)
1166 || (*cur++ != Z_DEFLATED))
1168 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1169 return JB_ERR_COMPRESS;
1175 * XXX: These magic numbers should be replaced
1176 * with macros to give a better idea what they do.
1180 /* The gzip header has reserved bits set; bail out. */
1181 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1182 return JB_ERR_COMPRESS;
1186 /* Skip extra fields if necessary. */
1190 * Skip a given number of bytes, specified
1191 * as a 16-bit little-endian value.
1194 * XXX: This code used to be:
1196 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1198 * which I had to change into:
1200 * cur += *cur++ + (*cur++ << 8);
1202 * at which point gcc43 finally noticed that the value
1203 * of cur is undefined (it depends on which of the
1204 * summands is evaluated first).
1206 * I haven't come across a site where this
1207 * code is actually executed yet, but I hope
1211 skip_bytes = *cur++;
1212 skip_bytes = *cur++ << 8;
1214 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1217 * The number of bytes to skip should be positive
1218 * and we'd like to stay in the buffer.
1220 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1222 log_error(LOG_LEVEL_ERROR,
1223 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1225 return JB_ERR_COMPRESS;
1227 log_error(LOG_LEVEL_INFO,
1228 "Skipping %d bytes for gzip compression. Does this sound right?",
1233 /* Skip the filename if necessary. */
1236 /* A null-terminated string is supposed to follow. */
1237 while (*cur++ && (cur < csp->iob->eod));
1241 /* Skip the comment if necessary. */
1244 /* A null-terminated string is supposed to follow. */
1245 while (*cur++ && (cur < csp->iob->eod));
1248 /* Skip the CRC if necessary. */
1254 if (cur >= csp->iob->eod)
1257 * If the current position pointer reached or passed
1258 * the buffer end, we were obviously tricked to skip
1261 log_error(LOG_LEVEL_ERROR,
1262 "Malformed gzip header detected. Aborting decompression.");
1263 return JB_ERR_COMPRESS;
1267 else if (csp->content_type & CT_DEFLATE)
1270 * XXX: The debug level should be lowered
1271 * before the next stable release.
1273 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1275 * In theory (that is, according to RFC 1950), deflate-compressed
1276 * data should begin with a two-byte zlib header and have an
1277 * adler32 checksum at the end. It seems that in practice only
1278 * the raw compressed data is sent. Note that this means that
1279 * we are not RFC 1950-compliant here, but the advantage is that
1280 * this actually works. :)
1282 * We add a dummy null byte to tell zlib where the data ends,
1283 * and later inform it not to expect a header.
1285 * Fortunately, add_to_iob() has thoughtfully null-terminated
1286 * the buffer; we can just increment the end pointer to include
1293 log_error(LOG_LEVEL_ERROR,
1294 "Unable to determine compression format for decompression");
1295 return JB_ERR_COMPRESS;
1298 /* Set up the fields required by zlib. */
1299 zstr.next_in = (Bytef *)cur;
1300 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1301 zstr.zalloc = Z_NULL;
1302 zstr.zfree = Z_NULL;
1303 zstr.opaque = Z_NULL;
1306 * Passing -MAX_WBITS to inflateInit2 tells the library
1307 * that there is no zlib header.
1309 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1311 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1312 return JB_ERR_COMPRESS;
1316 * Next, we allocate new storage for the inflated data.
1317 * We don't modify the existing iob yet, so in case there
1318 * is error in decompression we can recover gracefully.
1320 buf = zalloc(bufsize);
1323 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1324 return JB_ERR_MEMORY;
1327 assert(bufsize >= skip_size);
1328 memcpy(buf, csp->iob->buf, skip_size);
1329 zstr.avail_out = bufsize - skip_size;
1330 zstr.next_out = (Bytef *)buf + skip_size;
1332 /* Try to decompress the whole stream in one shot. */
1333 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1335 /* We need to allocate more memory for the output buffer. */
1337 char *tmpbuf; /* used for realloc'ing the buffer */
1338 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1341 * If zlib wants more data then there's a problem, because
1342 * the complete compressed file should have been buffered.
1344 if (0 == zstr.avail_in)
1346 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1347 return JB_ERR_COMPRESS;
1351 * If we tried the limit and still didn't have enough
1352 * memory, just give up.
1354 if (bufsize == csp->config->buffer_limit)
1356 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1357 return JB_ERR_MEMORY;
1360 /* Try doubling the buffer size each time. */
1363 /* Don't exceed the buffer limit. */
1364 if (bufsize > csp->config->buffer_limit)
1366 bufsize = csp->config->buffer_limit;
1369 /* Try to allocate the new buffer. */
1370 tmpbuf = realloc(buf, bufsize);
1373 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1375 return JB_ERR_MEMORY;
1379 char *oldnext_out = (char *)zstr.next_out;
1382 * Update the fields for inflate() to use the new
1383 * buffer, which may be in a location different from
1386 zstr.avail_out += bufsize - oldbufsize;
1387 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1390 * Compare with an uglier method of calculating these values
1391 * that doesn't require the extra oldbufsize variable.
1393 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1394 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1395 assert(zstr.avail_out > 0);
1401 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1403 log_error(LOG_LEVEL_ERROR,
1404 "Inconsistent stream state after decompression: %s", zstr.msg);
1406 * XXX: Intentionally no return.
1408 * According to zlib.h, Z_STREAM_ERROR is returned
1409 * "if the stream state was inconsistent".
1411 * I assume in this case inflate()'s status
1412 * would also be something different than Z_STREAM_END
1413 * so this check should be redundant, but lets see.
1417 if (status != Z_STREAM_END)
1419 /* We failed to decompress the stream. */
1420 log_error(LOG_LEVEL_ERROR,
1421 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1422 return JB_ERR_COMPRESS;
1426 * Finally, we can actually update the iob, since the
1427 * decompression was successful. First, free the old
1430 freez(csp->iob->buf);
1432 /* Now, update the iob to use the new buffer. */
1433 csp->iob->buf = buf;
1434 csp->iob->cur = csp->iob->buf + skip_size;
1435 csp->iob->eod = (char *)zstr.next_out;
1436 csp->iob->size = bufsize;
1439 * Make sure the new uncompressed iob obeys some minimal
1440 * consistency conditions.
1442 if ((csp->iob->buf < csp->iob->cur)
1443 && (csp->iob->cur <= csp->iob->eod)
1444 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1446 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1449 log_error(LOG_LEVEL_RE_FILTER,
1450 "Decompression successful. Old size: %d, new size: %d.",
1451 old_size, new_size);
1455 /* zlib thinks this is OK, so lets do the same. */
1456 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1461 /* It seems that zlib did something weird. */
1462 log_error(LOG_LEVEL_ERROR,
1463 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1464 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1465 csp->iob->eod, csp->iob->buf + csp->iob->size);
1466 return JB_ERR_COMPRESS;
1472 #endif /* defined(FEATURE_ZLIB) */
1475 /*********************************************************************
1477 * Function : string_move
1479 * Description : memmove wrapper to move the last part of a string
1480 * towards the beginning, overwriting the part in
1481 * the middle. strlcpy() can't be used here as the
1485 * 1 : dst = Destination to overwrite
1486 * 2 : src = Source to move.
1490 *********************************************************************/
1491 static void string_move(char *dst, char *src)
1495 /* +1 to copy the terminating nul as well. */
1496 memmove(dst, src, strlen(src)+1);
1500 /*********************************************************************
1502 * Function : normalize_lws
1504 * Description : Reduces unquoted linear white space in headers
1505 * to a single space in accordance with RFC 2616 2.2.
1506 * This simplifies parsing and filtering later on.
1508 * XXX: Remove log messages before
1509 * the next stable release?
1512 * 1 : header = A header with linear white space to reduce.
1516 *********************************************************************/
1517 static void normalize_lws(char *header)
1523 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1527 while (ijb_isspace(*q))
1531 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1532 string_move(p+1, q);
1537 log_error(LOG_LEVEL_HEADER,
1538 "Converting tab to space in '%s'", header);
1543 char *end_of_token = strstr(p+1, "\"");
1545 if (NULL != end_of_token)
1547 /* Don't mess with quoted text. */
1552 log_error(LOG_LEVEL_HEADER,
1553 "Ignoring single quote in '%s'", header);
1559 p = strchr(header, ':');
1560 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1563 * There's still space before the colon.
1566 string_move(p-1, p);
1571 /*********************************************************************
1573 * Function : get_header
1575 * Description : This (odd) routine will parse the csp->iob
1576 * to get the next complete header.
1579 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1581 * Returns : Any one of the following:
1583 * 1) a pointer to a dynamically allocated string that contains a header line
1584 * 2) NULL indicating that the end of the header was reached
1585 * 3) "" indicating that the end of the iob was reached before finding
1586 * a complete header line.
1588 *********************************************************************/
1589 char *get_header(struct iob *iob)
1593 header = get_header_line(iob);
1595 if ((header == NULL) || (*header == '\0'))
1598 * No complete header read yet, tell the client.
1603 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1606 * Header spans multiple lines, append the next one.
1608 char *continued_header;
1610 continued_header = get_header_line(iob);
1611 if ((continued_header == NULL) || (*continued_header == '\0'))
1614 * No complete header read yet, return what we got.
1615 * XXX: Should "unread" header instead.
1617 log_error(LOG_LEVEL_INFO,
1618 "Failed to read a multi-line header properly: '%s'",
1623 if (JB_ERR_OK != string_join(&header, continued_header))
1625 log_error(LOG_LEVEL_FATAL,
1626 "Out of memory while appending multiple headers.");
1630 /* XXX: remove before next stable release. */
1631 log_error(LOG_LEVEL_HEADER,
1632 "Merged multiple header lines to: '%s'",
1637 normalize_lws(header);
1644 /*********************************************************************
1646 * Function : get_header_line
1648 * Description : This (odd) routine will parse the csp->iob
1649 * to get the next header line.
1652 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1654 * Returns : Any one of the following:
1656 * 1) a pointer to a dynamically allocated string that contains a header line
1657 * 2) NULL indicating that the end of the header was reached
1658 * 3) "" indicating that the end of the iob was reached before finding
1659 * a complete header line.
1661 *********************************************************************/
1662 static char *get_header_line(struct iob *iob)
1666 if ((iob->cur == NULL)
1667 || ((p = strchr(iob->cur, '\n')) == NULL))
1669 return(""); /* couldn't find a complete header */
1674 ret = strdup(iob->cur);
1677 /* FIXME No way to handle error properly */
1678 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1683 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1685 /* is this a blank line (i.e. the end of the header) ? */
1697 /*********************************************************************
1699 * Function : get_header_value
1701 * Description : Get the value of a given header from a chained list
1702 * of header lines or return NULL if no such header is
1703 * present in the list.
1706 * 1 : header_list = pointer to list
1707 * 2 : header_name = string with name of header to look for.
1708 * Trailing colon required, capitalization
1711 * Returns : NULL if not found, else value of header
1713 *********************************************************************/
1714 char *get_header_value(const struct list *header_list, const char *header_name)
1716 struct list_entry *cur_entry;
1720 assert(header_list);
1721 assert(header_name);
1722 length = strlen(header_name);
1724 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1728 if (!strncmpic(cur_entry->str, header_name, length))
1731 * Found: return pointer to start of value
1733 ret = (char *) (cur_entry->str + length);
1734 while (*ret && ijb_isspace(*ret)) ret++;
1748 /*********************************************************************
1750 * Function : scan_headers
1752 * Description : Scans headers, applies tags and updates action bits.
1755 * 1 : csp = Current client state (buffers, headers, etc...)
1757 * Returns : JB_ERR_OK
1759 *********************************************************************/
1760 static jb_err scan_headers(struct client_state *csp)
1762 struct list_entry *h; /* Header */
1763 jb_err err = JB_ERR_OK;
1765 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1767 /* Header crunch()ed in previous run? -> ignore */
1768 if (h->str == NULL) continue;
1769 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1770 err = header_tagger(csp, h->str);
1777 /*********************************************************************
1781 * Description : add, delete or modify lines in the HTTP header streams.
1782 * On entry, it receives a linked list of headers space
1783 * that was allocated dynamically (both the list nodes
1784 * and the header contents).
1786 * As a side effect it frees the space used by the original
1790 * 1 : csp = Current client state (buffers, headers, etc...)
1791 * 2 : filter_server_headers = Boolean to switch between
1792 * server and header filtering.
1794 * Returns : JB_ERR_OK in case off success, or
1795 * JB_ERR_MEMORY on out-of-memory error.
1797 *********************************************************************/
1798 jb_err sed(struct client_state *csp, int filter_server_headers)
1800 /* XXX: use more descriptive names. */
1801 struct list_entry *p;
1802 const struct parsers *v;
1803 const add_header_func_ptr *f;
1804 jb_err err = JB_ERR_OK;
1806 if (filter_server_headers)
1808 v = server_patterns;
1809 f = add_server_headers;
1813 v = client_patterns;
1814 f = add_client_headers;
1819 while ((err == JB_ERR_OK) && (v->str != NULL))
1821 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1823 /* Header crunch()ed in previous run? -> ignore */
1824 if (p->str == NULL) continue;
1826 /* Does the current parser handle this header? */
1827 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1828 (v->len == CHECK_EVERY_HEADER_REMAINING))
1830 err = v->parser(csp, &(p->str));
1836 /* place additional headers on the csp->headers list */
1837 while ((err == JB_ERR_OK) && (*f))
1847 /*********************************************************************
1849 * Function : update_server_headers
1851 * Description : Updates server headers after the body has been modified.
1854 * 1 : csp = Current client state (buffers, headers, etc...)
1856 * Returns : JB_ERR_OK in case off success, or
1857 * JB_ERR_MEMORY on out-of-memory error.
1859 *********************************************************************/
1860 jb_err update_server_headers(struct client_state *csp)
1862 jb_err err = JB_ERR_OK;
1864 static const struct parsers server_patterns_light[] = {
1865 { "Content-Length:", 15, server_content_length },
1866 { "Transfer-Encoding:", 18, server_transfer_coding },
1868 { "Content-Encoding:", 17, server_content_encoding },
1869 #endif /* def FEATURE_ZLIB */
1873 if (strncmpic(csp->http->cmd, "HEAD", 4))
1875 const struct parsers *v;
1876 struct list_entry *p;
1878 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1880 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1882 /* Header crunch()ed in previous run? -> ignore */
1883 if (p->str == NULL) continue;
1885 /* Does the current parser handle this header? */
1886 if (strncmpic(p->str, v->str, v->len) == 0)
1888 err = v->parser(csp, (char **)&(p->str));
1898 /*********************************************************************
1900 * Function : header_tagger
1902 * Description : Executes all text substitutions from applying
1903 * tag actions and saves the result as tag.
1905 * XXX: Shares enough code with filter_header() and
1906 * pcrs_filter_response() to warrant some helper functions.
1909 * 1 : csp = Current client state (buffers, headers, etc...)
1910 * 2 : header = Header that is used as tagger input
1912 * Returns : JB_ERR_OK on success and always succeeds
1914 *********************************************************************/
1915 static jb_err header_tagger(struct client_state *csp, char *header)
1917 int wanted_filter_type;
1918 int multi_action_index;
1922 struct file_list *fl;
1923 struct re_filterfile_spec *b;
1924 struct list_entry *tag_name;
1926 int found_filters = 0;
1927 const size_t header_length = strlen(header);
1929 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1931 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1932 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1936 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1937 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1940 /* Check if there are any filters */
1941 for (i = 0; i < MAX_AF_FILES; i++)
1954 if (0 == found_filters)
1956 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1957 "tagging enabled, but no taggers available.");
1961 for (i = 0; i < MAX_AF_FILES; i++)
1964 if ((NULL == fl) || (NULL == fl->f))
1967 * Either there are no filter files
1968 * left, or this filter file just
1969 * contains no valid filters.
1971 * Continue to be sure we don't miss
1972 * valid filter files that are chained
1973 * after empty or invalid ones.
1978 /* For all filters, */
1979 for (b = fl->f; b; b = b->next)
1981 if (b->type != wanted_filter_type)
1983 /* skip the ones we don't care about, */
1986 /* leaving only taggers that could apply, of which we use the ones, */
1987 for (tag_name = csp->action->multi[multi_action_index]->first;
1988 NULL != tag_name; tag_name = tag_name->next)
1990 /* that do apply, and */
1991 if (strcmp(b->name, tag_name->str) == 0)
1993 char *modified_tag = NULL;
1995 size_t size = header_length;
1996 pcrs_job *joblist = b->joblist;
1998 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2000 if (NULL == joblist)
2002 log_error(LOG_LEVEL_RE_FILTER,
2003 "Tagger %s has empty joblist. Nothing to do.", b->name);
2007 /* execute their pcrs_joblist on the header. */
2008 for (job = joblist; NULL != job; job = job->next)
2010 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2014 /* Success, continue with the modified version. */
2023 /* Tagger doesn't match */
2026 /* Regex failure, log it but continue anyway. */
2027 log_error(LOG_LEVEL_ERROR,
2028 "Problems with tagger \'%s\' and header \'%s\': %s",
2029 b->name, *header, pcrs_strerror(hits));
2031 freez(modified_tag);
2035 if (b->dynamic) pcrs_free_joblist(joblist);
2037 /* If this tagger matched */
2043 * There is to technical limitation which makes
2044 * it impossible to use empty tags, but I assume
2045 * no one would do it intentionally.
2048 log_error(LOG_LEVEL_INFO,
2049 "Tagger \'%s\' created an empty tag. Ignored.",
2054 if (!list_contains_item(csp->tags, tag))
2056 if (JB_ERR_OK != enlist(csp->tags, tag))
2058 log_error(LOG_LEVEL_ERROR,
2059 "Insufficient memory to add tag \'%s\', "
2060 "based on tagger \'%s\' and header \'%s\'",
2061 tag, b->name, *header);
2065 char *action_message;
2067 * update the action bits right away, to make
2068 * tagging based on tags set by earlier taggers
2069 * of the same kind possible.
2071 if (update_action_bits_for_tag(csp, tag))
2073 action_message = "Action bits updated accordingly.";
2077 action_message = "No action bits update necessary.";
2080 log_error(LOG_LEVEL_HEADER,
2081 "Tagger \'%s\' added tag \'%s\'. %s",
2082 b->name, tag, action_message);
2087 /* XXX: Is this log-worthy? */
2088 log_error(LOG_LEVEL_HEADER,
2089 "Tagger \'%s\' didn't add tag \'%s\'. "
2090 "Tag already present", b->name, tag);
2093 } /* if the tagger matched */
2094 } /* if the tagger applies */
2095 } /* for every tagger that could apply */
2096 } /* for all filters */
2097 } /* for all filter files */
2102 /* here begins the family of parser functions that reformat header lines */
2104 /*********************************************************************
2106 * Function : filter_header
2108 * Description : Executes all text substitutions from all applying
2109 * +(server|client)-header-filter actions on the header.
2110 * Most of the code was copied from pcrs_filter_response,
2111 * including the rather short variable names
2114 * 1 : csp = Current client state (buffers, headers, etc...)
2115 * 2 : header = On input, pointer to header to modify.
2116 * On output, pointer to the modified header, or NULL
2117 * to remove the header. This function frees the
2118 * original string if necessary.
2120 * Returns : JB_ERR_OK on success and always succeeds
2122 *********************************************************************/
2123 static jb_err filter_header(struct client_state *csp, char **header)
2127 size_t size = strlen(*header);
2129 char *newheader = NULL;
2132 struct file_list *fl;
2133 struct re_filterfile_spec *b;
2134 struct list_entry *filtername;
2136 int i, found_filters = 0;
2137 int wanted_filter_type;
2138 int multi_action_index;
2140 if (csp->flags & CSP_FLAG_NO_FILTERING)
2145 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2147 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2148 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2152 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2153 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2157 * Need to check the set of re_filterfiles...
2159 for (i = 0; i < MAX_AF_FILES; i++)
2172 if (0 == found_filters)
2174 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2175 "header filtering enabled, but no matching filters available.");
2179 for (i = 0; i < MAX_AF_FILES; i++)
2182 if ((NULL == fl) || (NULL == fl->f))
2185 * Either there are no filter files
2186 * left, or this filter file just
2187 * contains no valid filters.
2189 * Continue to be sure we don't miss
2190 * valid filter files that are chained
2191 * after empty or invalid ones.
2196 * For all applying +filter actions, look if a filter by that
2197 * name exists and if yes, execute its pcrs_joblist on the
2200 for (b = fl->f; b; b = b->next)
2202 if (b->type != wanted_filter_type)
2204 /* Skip other filter types */
2208 for (filtername = csp->action->multi[multi_action_index]->first;
2209 filtername ; filtername = filtername->next)
2211 if (strcmp(b->name, filtername->str) == 0)
2213 int current_hits = 0;
2214 pcrs_job *joblist = b->joblist;
2216 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2218 if (NULL == joblist)
2220 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2224 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2225 *header, size, b->name);
2227 /* Apply all jobs from the joblist */
2228 for (job = joblist; NULL != job; job = job->next)
2230 matches = pcrs_execute(job, *header, size, &newheader, &size);
2233 current_hits += matches;
2234 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2236 *header = newheader;
2238 else if ( 0 == matches )
2240 /* Filter doesn't change header */
2246 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2247 *header, b->name, pcrs_strerror(matches));
2248 if (newheader != NULL)
2250 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2256 if (b->dynamic) pcrs_free_joblist(joblist);
2258 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2259 hits += current_hits;
2266 * Additionally checking for hits is important because if
2267 * the continue hack is triggered, server headers can
2268 * arrive empty to separate multiple heads from each other.
2270 if ((0 == size) && hits)
2272 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2280 /*********************************************************************
2282 * Function : connection
2284 * Description : Makes sure that the value of the Connection: header
2285 * is "close" and signals connection_close_adder
2289 * 1 : csp = Current client state (buffers, headers, etc...)
2290 * 2 : header = On input, pointer to header to modify.
2291 * On output, pointer to the modified header, or NULL
2292 * to remove the header. This function frees the
2293 * original string if necessary.
2295 * Returns : JB_ERR_OK on success, or
2296 * JB_ERR_MEMORY on out-of-memory error.
2298 *********************************************************************/
2299 static jb_err connection(struct client_state *csp, char **header)
2301 char *old_header = *header;
2303 /* Do we have a 'Connection: close' header? */
2304 if (strcmpic(*header, "Connection: close"))
2306 /* No, create one */
2307 *header = strdup("Connection: close");
2310 return JB_ERR_MEMORY;
2312 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2316 /* Signal connection_close_adder() to return early. */
2317 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2319 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2323 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2330 /*********************************************************************
2332 * Function : crumble
2334 * Description : This is called if a header matches a pattern to "crunch"
2337 * 1 : csp = Current client state (buffers, headers, etc...)
2338 * 2 : header = On input, pointer to header to modify.
2339 * On output, pointer to the modified header, or NULL
2340 * to remove the header. This function frees the
2341 * original string if necessary.
2343 * Returns : JB_ERR_OK on success, or
2344 * JB_ERR_MEMORY on out-of-memory error.
2346 *********************************************************************/
2347 static jb_err crumble(struct client_state *csp, char **header)
2349 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2355 /*********************************************************************
2357 * Function : crunch_server_header
2359 * Description : Crunch server header if it matches a string supplied by the
2360 * user. Called from `sed'.
2363 * 1 : csp = Current client state (buffers, headers, etc...)
2364 * 2 : header = On input, pointer to header to modify.
2365 * On output, pointer to the modified header, or NULL
2366 * to remove the header. This function frees the
2367 * original string if necessary.
2369 * Returns : JB_ERR_OK on success and always succeeds
2371 *********************************************************************/
2372 static jb_err crunch_server_header(struct client_state *csp, char **header)
2374 const char *crunch_pattern;
2376 /* Do we feel like crunching? */
2377 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2379 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2381 /* Is the current header the lucky one? */
2382 if (strstr(*header, crunch_pattern))
2384 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2393 /*********************************************************************
2395 * Function : server_content_type
2397 * Description : Set the content-type for filterable types (text/.*,
2398 * .*xml.*, javascript and image/gif) unless filtering has been
2399 * forbidden (CT_TABOO) while parsing earlier headers.
2400 * NOTE: Since text/plain is commonly used by web servers
2401 * for files whose correct type is unknown, we don't
2402 * set CT_TEXT for it.
2405 * 1 : csp = Current client state (buffers, headers, etc...)
2406 * 2 : header = On input, pointer to header to modify.
2407 * On output, pointer to the modified header, or NULL
2408 * to remove the header. This function frees the
2409 * original string if necessary.
2411 * Returns : JB_ERR_OK on success, or
2412 * JB_ERR_MEMORY on out-of-memory error.
2414 *********************************************************************/
2415 static jb_err server_content_type(struct client_state *csp, char **header)
2417 /* Remove header if it isn't the first Content-Type header */
2418 if ((csp->content_type & CT_DECLARED))
2421 * Another, slightly slower, way to see if
2422 * we already parsed another Content-Type header.
2424 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2426 log_error(LOG_LEVEL_ERROR,
2427 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2435 * Signal that the Content-Type has been set.
2437 csp->content_type |= CT_DECLARED;
2439 if (!(csp->content_type & CT_TABOO))
2442 * XXX: The assumption that text/plain is a sign of
2443 * binary data seems to be somewhat unreasonable nowadays
2444 * and should be dropped after 3.0.8 is out.
2446 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2447 || strstr(*header, "xml")
2448 || strstr(*header, "application/x-javascript"))
2450 csp->content_type |= CT_TEXT;
2452 else if (strstr(*header, "image/gif"))
2454 csp->content_type |= CT_GIF;
2459 * Are we messing with the content type?
2461 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2464 * Make sure the user doesn't accidently
2465 * change the content type of binary documents.
2467 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2470 *header = strdup("Content-Type: ");
2471 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2475 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2476 return JB_ERR_MEMORY;
2478 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2482 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2483 "It doesn't look like a content type that should be filtered. "
2484 "Enable force-text-mode if you know what you're doing.", *header);
2492 /*********************************************************************
2494 * Function : server_transfer_coding
2496 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2497 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2498 * - Remove header if body was chunked but has been
2499 * de-chunked for filtering.
2502 * 1 : csp = Current client state (buffers, headers, etc...)
2503 * 2 : header = On input, pointer to header to modify.
2504 * On output, pointer to the modified header, or NULL
2505 * to remove the header. This function frees the
2506 * original string if necessary.
2508 * Returns : JB_ERR_OK on success, or
2509 * JB_ERR_MEMORY on out-of-memory error.
2511 *********************************************************************/
2512 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2515 * Turn off pcrs and gif filtering if body compressed
2517 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2521 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2523 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2524 csp->http->cmd, *header);
2525 #endif /* def FEATURE_ZLIB */
2526 csp->content_type = CT_TABOO;
2530 * Raise flag if body chunked
2532 if (strstr(*header, "chunked"))
2534 csp->flags |= CSP_FLAG_CHUNKED;
2537 * If the body was modified, it has been de-chunked first
2538 * and the header must be removed.
2540 * FIXME: If there is more than one transfer encoding,
2541 * only the "chunked" part should be removed here.
2543 if (csp->flags & CSP_FLAG_MODIFIED)
2545 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2554 /*********************************************************************
2556 * Function : server_content_encoding
2558 * Description : This function is run twice for each request,
2559 * unless FEATURE_ZLIB and filtering are disabled.
2561 * The first run is used to check if the content
2562 * is compressed, if FEATURE_ZLIB is disabled
2563 * filtering is then disabled as well, if FEATURE_ZLIB
2564 * is enabled the content is marked for decompression.
2566 * The second run is used to remove the Content-Encoding
2567 * header if the decompression was successful.
2570 * 1 : csp = Current client state (buffers, headers, etc...)
2571 * 2 : header = On input, pointer to header to modify.
2572 * On output, pointer to the modified header, or NULL
2573 * to remove the header. This function frees the
2574 * original string if necessary.
2576 * Returns : JB_ERR_OK on success, or
2577 * JB_ERR_MEMORY on out-of-memory error.
2579 *********************************************************************/
2580 static jb_err server_content_encoding(struct client_state *csp, char **header)
2583 if ((csp->flags & CSP_FLAG_MODIFIED)
2584 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2587 * We successfully decompressed the content,
2588 * and have to clean the header now, so the
2589 * client no longer expects compressed data..
2591 * XXX: There is a difference between cleaning
2592 * and removing it completely.
2594 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2597 else if (strstr(*header, "gzip"))
2599 /* Mark for gzip decompression */
2600 csp->content_type |= CT_GZIP;
2602 else if (strstr(*header, "deflate"))
2604 /* Mark for zlib decompression */
2605 csp->content_type |= CT_DEFLATE;
2607 else if (strstr(*header, "compress"))
2610 * We can't decompress this; therefore we can't filter
2613 csp->content_type |= CT_TABOO;
2615 #else /* !defined(FEATURE_ZLIB) */
2616 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2619 * Body is compressed, turn off pcrs and gif filtering.
2621 csp->content_type |= CT_TABOO;
2624 * Log a warning if the user expects the content to be filtered.
2626 if ((csp->rlist != NULL) &&
2627 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2629 log_error(LOG_LEVEL_INFO,
2630 "Compressed content detected, content filtering disabled. "
2631 "Consider recompiling Privoxy with zlib support or "
2632 "enable the prevent-compression action.");
2635 #endif /* defined(FEATURE_ZLIB) */
2642 /*********************************************************************
2644 * Function : server_content_length
2646 * Description : Adjust Content-Length header if we modified
2650 * 1 : csp = Current client state (buffers, headers, etc...)
2651 * 2 : header = On input, pointer to header to modify.
2652 * On output, pointer to the modified header, or NULL
2653 * to remove the header. This function frees the
2654 * original string if necessary.
2656 * Returns : JB_ERR_OK on success, or
2657 * JB_ERR_MEMORY on out-of-memory error.
2659 *********************************************************************/
2660 static jb_err server_content_length(struct client_state *csp, char **header)
2662 const size_t max_header_length = 80;
2664 /* Regenerate header if the content was modified. */
2665 if (csp->flags & CSP_FLAG_MODIFIED)
2668 *header = (char *) zalloc(max_header_length);
2669 if (*header == NULL)
2671 return JB_ERR_MEMORY;
2674 snprintf(*header, max_header_length, "Content-Length: %d",
2675 (int)csp->content_length);
2676 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2677 (int)csp->content_length);
2684 /*********************************************************************
2686 * Function : server_content_md5
2688 * Description : Crumble any Content-MD5 headers if the document was
2689 * modified. FIXME: Should we re-compute instead?
2692 * 1 : csp = Current client state (buffers, headers, etc...)
2693 * 2 : header = On input, pointer to header to modify.
2694 * On output, pointer to the modified header, or NULL
2695 * to remove the header. This function frees the
2696 * original string if necessary.
2698 * Returns : JB_ERR_OK on success, or
2699 * JB_ERR_MEMORY on out-of-memory error.
2701 *********************************************************************/
2702 static jb_err server_content_md5(struct client_state *csp, char **header)
2704 if (csp->flags & CSP_FLAG_MODIFIED)
2706 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2714 /*********************************************************************
2716 * Function : server_content_disposition
2718 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2719 * Called from `sed'.
2722 * 1 : csp = Current client state (buffers, headers, etc...)
2723 * 2 : header = On input, pointer to header to modify.
2724 * On output, pointer to the modified header, or NULL
2725 * to remove the header. This function frees the
2726 * original string if necessary.
2728 * Returns : JB_ERR_OK on success, or
2729 * JB_ERR_MEMORY on out-of-memory error.
2731 *********************************************************************/
2732 static jb_err server_content_disposition(struct client_state *csp, char **header)
2737 * Are we messing with the Content-Disposition header?
2739 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2745 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2747 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2750 * Blocking content-disposition header
2752 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2759 * Replacing Content-Disposition header
2762 *header = strdup("Content-Disposition: ");
2763 string_append(header, newval);
2765 if (*header != NULL)
2767 log_error(LOG_LEVEL_HEADER,
2768 "Content-Disposition header crunched and replaced with: %s", *header);
2771 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2775 /*********************************************************************
2777 * Function : server_last_modified
2779 * Description : Changes Last-Modified header to the actual date
2780 * to help hide-if-modified-since.
2781 * Called from `sed'.
2784 * 1 : csp = Current client state (buffers, headers, etc...)
2785 * 2 : header = On input, pointer to header to modify.
2786 * On output, pointer to the modified header, or NULL
2787 * to remove the header. This function frees the
2788 * original string if necessary.
2790 * Returns : JB_ERR_OK on success, or
2791 * JB_ERR_MEMORY on out-of-memory error.
2793 *********************************************************************/
2794 static jb_err server_last_modified(struct client_state *csp, char **header)
2797 char buf[BUFFER_SIZE];
2800 #ifdef HAVE_GMTIME_R
2803 struct tm *timeptr = NULL;
2804 time_t now, last_modified;
2806 long int days, hours, minutes, seconds;
2809 * Are we messing with the Last-Modified header?
2811 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2817 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2819 if (0 == strcmpic(newval, "block") )
2822 * Blocking Last-Modified header. Useless but why not.
2824 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2828 else if (0 == strcmpic(newval, "reset-to-request-time"))
2831 * Setting Last-Modified Header to now.
2833 get_http_time(0, buf, sizeof(buf));
2835 *header = strdup("Last-Modified: ");
2836 string_append(header, buf);
2838 if (*header == NULL)
2840 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2844 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2847 else if (0 == strcmpic(newval, "randomize"))
2849 const char *header_time = *header + sizeof("Last-Modified:");
2851 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2853 #ifdef HAVE_GMTIME_R
2854 timeptr = gmtime_r(&now, &gmt);
2855 #elif FEATURE_PTHREAD
2856 pthread_mutex_lock(&gmtime_mutex);
2857 timeptr = gmtime(&now);
2858 pthread_mutex_unlock(&gmtime_mutex);
2860 timeptr = gmtime(&now);
2862 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2864 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2869 rtime = (long int)difftime(now, last_modified);
2878 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2880 rtime = pick_from_range(rtime);
2881 if (negative) rtime *= -1;
2882 last_modified += rtime;
2883 #ifdef HAVE_GMTIME_R
2884 timeptr = gmtime_r(&last_modified, &gmt);
2885 #elif FEATURE_PTHREAD
2886 pthread_mutex_lock(&gmtime_mutex);
2887 timeptr = gmtime(&last_modified);
2888 pthread_mutex_unlock(&gmtime_mutex);
2890 timeptr = gmtime(&last_modified);
2892 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2894 *header = strdup("Last-Modified: ");
2895 string_append(header, newheader);
2897 if (*header == NULL)
2899 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2900 return JB_ERR_MEMORY;
2903 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2905 days = rtime / (3600 * 24);
2906 hours = rtime / 3600 % 24;
2907 minutes = rtime / 60 % 60;
2908 seconds = rtime % 60;
2910 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2911 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2912 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2917 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2926 /*********************************************************************
2928 * Function : client_accept_encoding
2930 * Description : Rewrite the client's Accept-Encoding header so that
2931 * if doesn't allow compression, if the action applies.
2932 * Note: For HTTP/1.0 the absence of the header is enough.
2935 * 1 : csp = Current client state (buffers, headers, etc...)
2936 * 2 : header = On input, pointer to header to modify.
2937 * On output, pointer to the modified header, or NULL
2938 * to remove the header. This function frees the
2939 * original string if necessary.
2941 * Returns : JB_ERR_OK on success, or
2942 * JB_ERR_MEMORY on out-of-memory error.
2944 *********************************************************************/
2945 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2947 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2949 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2953 /* Temporarily disable the correct behaviour to
2954 * work around a PHP bug.
2956 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2958 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2959 * if (*header == NULL)
2961 * return JB_ERR_MEMORY;
2972 /*********************************************************************
2974 * Function : client_te
2976 * Description : Rewrite the client's TE header so that
2977 * if doesn't allow compression, if the action applies.
2980 * 1 : csp = Current client state (buffers, headers, etc...)
2981 * 2 : header = On input, pointer to header to modify.
2982 * On output, pointer to the modified header, or NULL
2983 * to remove the header. This function frees the
2984 * original string if necessary.
2986 * Returns : JB_ERR_OK on success, or
2987 * JB_ERR_MEMORY on out-of-memory error.
2989 *********************************************************************/
2990 static jb_err client_te(struct client_state *csp, char **header)
2992 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2995 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3002 /*********************************************************************
3004 * Function : client_referrer
3006 * Description : Handle the "referer" config setting properly.
3007 * Called from `sed'.
3010 * 1 : csp = Current client state (buffers, headers, etc...)
3011 * 2 : header = On input, pointer to header to modify.
3012 * On output, pointer to the modified header, or NULL
3013 * to remove the header. This function frees the
3014 * original string if necessary.
3016 * Returns : JB_ERR_OK on success, or
3017 * JB_ERR_MEMORY on out-of-memory error.
3019 *********************************************************************/
3020 static jb_err client_referrer(struct client_state *csp, char **header)
3022 const char *parameter;
3023 /* booleans for parameters we have to check multiple times */
3024 int parameter_conditional_block;
3025 int parameter_conditional_forge;
3027 #ifdef FEATURE_FORCE_LOAD
3029 * Since the referrer can include the prefix even
3030 * if the request itself is non-forced, we must
3031 * clean it unconditionally.
3033 * XXX: strclean is too broad
3035 strclean(*header, FORCE_PREFIX);
3036 #endif /* def FEATURE_FORCE_LOAD */
3038 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3040 /* Nothing left to do */
3044 parameter = csp->action->string[ACTION_STRING_REFERER];
3045 assert(parameter != NULL);
3046 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3047 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3049 if (!parameter_conditional_block && !parameter_conditional_forge)
3052 * As conditional-block and conditional-forge are the only
3053 * parameters that rely on the original referrer, we can
3054 * remove it now for all the others.
3059 if (0 == strcmpic(parameter, "block"))
3061 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3064 else if (parameter_conditional_block || parameter_conditional_forge)
3066 return handle_conditional_hide_referrer_parameter(header,
3067 csp->http->hostport, parameter_conditional_block);
3069 else if (0 == strcmpic(parameter, "forge"))
3071 return create_forged_referrer(header, csp->http->hostport);
3075 /* interpret parameter as user-supplied referer to fake */
3076 return create_fake_referrer(header, parameter);
3081 /*********************************************************************
3083 * Function : client_accept_language
3085 * Description : Handle the "Accept-Language" config setting properly.
3086 * Called from `sed'.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * 2 : header = On input, pointer to header to modify.
3091 * On output, pointer to the modified header, or NULL
3092 * to remove the header. This function frees the
3093 * original string if necessary.
3095 * Returns : JB_ERR_OK on success, or
3096 * JB_ERR_MEMORY on out-of-memory error.
3098 *********************************************************************/
3099 static jb_err client_accept_language(struct client_state *csp, char **header)
3104 * Are we messing with the Accept-Language?
3106 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3108 /*I don't think so*/
3112 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3114 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3117 * Blocking Accept-Language header
3119 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3126 * Replacing Accept-Language header
3129 *header = strdup("Accept-Language: ");
3130 string_append(header, newval);
3132 if (*header == NULL)
3134 log_error(LOG_LEVEL_ERROR,
3135 "Insufficient memory. Accept-Language header crunched without replacement.");
3139 log_error(LOG_LEVEL_HEADER,
3140 "Accept-Language header crunched and replaced with: %s", *header);
3143 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3147 /*********************************************************************
3149 * Function : crunch_client_header
3151 * Description : Crunch client header if it matches a string supplied by the
3152 * user. Called from `sed'.
3155 * 1 : csp = Current client state (buffers, headers, etc...)
3156 * 2 : header = On input, pointer to header to modify.
3157 * On output, pointer to the modified header, or NULL
3158 * to remove the header. This function frees the
3159 * original string if necessary.
3161 * Returns : JB_ERR_OK on success and always succeeds
3163 *********************************************************************/
3164 static jb_err crunch_client_header(struct client_state *csp, char **header)
3166 const char *crunch_pattern;
3168 /* Do we feel like crunching? */
3169 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3171 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3173 /* Is the current header the lucky one? */
3174 if (strstr(*header, crunch_pattern))
3176 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3184 /*********************************************************************
3186 * Function : client_uagent
3188 * Description : Handle the "user-agent" config setting properly
3189 * and remember its original value to enable browser
3190 * bug workarounds. Called from `sed'.
3193 * 1 : csp = Current client state (buffers, headers, etc...)
3194 * 2 : header = On input, pointer to header to modify.
3195 * On output, pointer to the modified header, or NULL
3196 * to remove the header. This function frees the
3197 * original string if necessary.
3199 * Returns : JB_ERR_OK on success, or
3200 * JB_ERR_MEMORY on out-of-memory error.
3202 *********************************************************************/
3203 static jb_err client_uagent(struct client_state *csp, char **header)
3207 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3212 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3219 *header = strdup("User-Agent: ");
3220 string_append(header, newval);
3222 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3224 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3228 /*********************************************************************
3230 * Function : client_ua
3232 * Description : Handle "ua-" headers properly. Called from `sed'.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * 2 : header = On input, pointer to header to modify.
3237 * On output, pointer to the modified header, or NULL
3238 * to remove the header. This function frees the
3239 * original string if necessary.
3241 * Returns : JB_ERR_OK on success, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_ua(struct client_state *csp, char **header)
3247 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3249 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3257 /*********************************************************************
3259 * Function : client_from
3261 * Description : Handle the "from" config setting properly.
3262 * Called from `sed'.
3265 * 1 : csp = Current client state (buffers, headers, etc...)
3266 * 2 : header = On input, pointer to header to modify.
3267 * On output, pointer to the modified header, or NULL
3268 * to remove the header. This function frees the
3269 * original string if necessary.
3271 * Returns : JB_ERR_OK on success, or
3272 * JB_ERR_MEMORY on out-of-memory error.
3274 *********************************************************************/
3275 static jb_err client_from(struct client_state *csp, char **header)
3279 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3286 newval = csp->action->string[ACTION_STRING_FROM];
3289 * Are we blocking the e-mail address?
3291 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3293 log_error(LOG_LEVEL_HEADER, "crunched From!");
3297 log_error(LOG_LEVEL_HEADER, " modified");
3299 *header = strdup("From: ");
3300 string_append(header, newval);
3302 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3306 /*********************************************************************
3308 * Function : client_send_cookie
3310 * Description : Crunches the "cookie" header if necessary.
3311 * Called from `sed'.
3313 * XXX: Stupid name, doesn't send squat.
3316 * 1 : csp = Current client state (buffers, headers, etc...)
3317 * 2 : header = On input, pointer to header to modify.
3318 * On output, pointer to the modified header, or NULL
3319 * to remove the header. This function frees the
3320 * original string if necessary.
3322 * Returns : JB_ERR_OK on success, or
3323 * JB_ERR_MEMORY on out-of-memory error.
3325 *********************************************************************/
3326 static jb_err client_send_cookie(struct client_state *csp, char **header)
3328 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3330 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3338 /*********************************************************************
3340 * Function : client_x_forwarded
3342 * Description : Handle the "x-forwarded-for" config setting properly,
3343 * also used in the add_client_headers list. Called from `sed'.
3346 * 1 : csp = Current client state (buffers, headers, etc...)
3347 * 2 : header = On input, pointer to header to modify.
3348 * On output, pointer to the modified header, or NULL
3349 * to remove the header. This function frees the
3350 * original string if necessary.
3352 * Returns : JB_ERR_OK on success, or
3353 * JB_ERR_MEMORY on out-of-memory error.
3355 *********************************************************************/
3356 jb_err client_x_forwarded(struct client_state *csp, char **header)
3358 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3361 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3368 /*********************************************************************
3370 * Function : client_max_forwards
3372 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3373 * from the value of the Max-Forwards header field.
3376 * 1 : csp = Current client state (buffers, headers, etc...)
3377 * 2 : header = On input, pointer to header to modify.
3378 * On output, pointer to the modified header, or NULL
3379 * to remove the header. This function frees the
3380 * original string if necessary.
3382 * Returns : JB_ERR_OK on success, or
3383 * JB_ERR_MEMORY on out-of-memory error.
3385 *********************************************************************/
3386 static jb_err client_max_forwards(struct client_state *csp, char **header)
3390 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3391 (0 == strcmpic(csp->http->gpc, "options")))
3393 assert(*(*header+12) == ':');
3394 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3396 if (max_forwards > 0)
3398 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3399 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3400 csp->http->gpc, max_forwards);
3402 else if (max_forwards < 0)
3404 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3410 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3419 /*********************************************************************
3421 * Function : client_host
3423 * Description : If the request URI did not contain host and
3424 * port information, parse and evaluate the Host
3427 * Also, kill ill-formed HOST: headers as sent by
3428 * Apple's iTunes software when used with a proxy.
3431 * 1 : csp = Current client state (buffers, headers, etc...)
3432 * 2 : header = On input, pointer to header to modify.
3433 * On output, pointer to the modified header, or NULL
3434 * to remove the header. This function frees the
3435 * original string if necessary.
3437 * Returns : JB_ERR_OK on success, or
3438 * JB_ERR_MEMORY on out-of-memory error.
3440 *********************************************************************/
3441 static jb_err client_host(struct client_state *csp, char **header)
3446 * If the header field name is all upper-case, chances are that it's
3447 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3448 * not a problem -- they are regenerated later.
3450 if ((*header)[1] == 'O')
3452 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3457 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3458 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3461 if (NULL == (p = strdup((*header)+6)))
3463 return JB_ERR_MEMORY;
3466 if (NULL == (q = strdup(p)))
3469 return JB_ERR_MEMORY;
3472 freez(csp->http->hostport);
3473 csp->http->hostport = p;
3474 freez(csp->http->host);
3475 csp->http->host = q;
3476 q = strchr(csp->http->host, ':');
3479 /* Terminate hostname and evaluate port string */
3481 csp->http->port = atoi(q);
3485 csp->http->port = csp->http->ssl ? 443 : 80;
3488 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3489 csp->http->hostport, csp->http->host, csp->http->port);
3492 /* Signal client_host_adder() to return right away */
3493 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3499 /*********************************************************************
3501 * Function : client_if_modified_since
3503 * Description : Remove or modify the If-Modified-Since header.
3506 * 1 : csp = Current client state (buffers, headers, etc...)
3507 * 2 : header = On input, pointer to header to modify.
3508 * On output, pointer to the modified header, or NULL
3509 * to remove the header. This function frees the
3510 * original string if necessary.
3512 * Returns : JB_ERR_OK on success, or
3513 * JB_ERR_MEMORY on out-of-memory error.
3515 *********************************************************************/
3516 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3519 #ifdef HAVE_GMTIME_R
3522 struct tm *timeptr = NULL;
3526 long int hours, minutes, seconds;
3530 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3533 * The client got an error message because of a temporary problem,
3534 * the problem is gone and the client now tries to revalidate our
3535 * error message on the real server. The revalidation would always
3536 * end with the transmission of the whole document and there is
3537 * no need to expose the bogus If-Modified-Since header.
3539 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3542 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3544 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3546 if ((0 == strcmpic(newval, "block")))
3548 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3551 else /* add random value */
3553 const char *header_time = *header + sizeof("If-Modified-Since:");
3555 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3557 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3562 rtime = strtol(newval, &endptr, 0);
3565 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3566 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3573 rtime = pick_from_range(rtime);
3577 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3580 tm += rtime * (negative ? -1 : 1);
3581 #ifdef HAVE_GMTIME_R
3582 timeptr = gmtime_r(&tm, &gmt);
3583 #elif FEATURE_PTHREAD
3584 pthread_mutex_lock(&gmtime_mutex);
3585 timeptr = gmtime(&tm);
3586 pthread_mutex_unlock(&gmtime_mutex);
3588 timeptr = gmtime(&tm);
3590 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3593 *header = strdup("If-Modified-Since: ");
3594 string_append(header, newheader);
3596 if (*header == NULL)
3598 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3599 return JB_ERR_MEMORY;
3602 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3604 hours = rtime / 3600;
3605 minutes = rtime / 60 % 60;
3606 seconds = rtime % 60;
3608 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3609 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3610 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3620 /*********************************************************************
3622 * Function : client_if_none_match
3624 * Description : Remove the If-None-Match header.
3627 * 1 : csp = Current client state (buffers, headers, etc...)
3628 * 2 : header = On input, pointer to header to modify.
3629 * On output, pointer to the modified header, or NULL
3630 * to remove the header. This function frees the
3631 * original string if necessary.
3633 * Returns : JB_ERR_OK on success, or
3634 * JB_ERR_MEMORY on out-of-memory error.
3636 *********************************************************************/
3637 static jb_err client_if_none_match(struct client_state *csp, char **header)
3639 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3641 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3649 /*********************************************************************
3651 * Function : client_x_filter
3653 * Description : Disables filtering if the client set "X-Filter: No".
3654 * Called from `sed'.
3657 * 1 : csp = Current client state (buffers, headers, etc...)
3658 * 2 : header = On input, pointer to header to modify.
3659 * On output, pointer to the modified header, or NULL
3660 * to remove the header. This function frees the
3661 * original string if necessary.
3663 * Returns : JB_ERR_OK on success
3665 *********************************************************************/
3666 jb_err client_x_filter(struct client_state *csp, char **header)
3668 if ( 0 == strcmpic(*header, "X-Filter: No"))
3670 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3672 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3676 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3678 log_error(LOG_LEVEL_HEADER,
3679 "force-text-mode overruled the client's request to fetch without filtering!");
3683 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3684 csp->flags |= CSP_FLAG_NO_FILTERING;
3685 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3687 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3695 /*********************************************************************
3697 * Function : client_range
3699 * Description : Removes Range, Request-Range and If-Range headers if
3700 * content filtering is enabled. If the client's version
3701 * of the document has been altered by Privoxy, the server
3702 * could interpret the range differently than the client
3703 * intended in which case the user could end up with
3704 * corrupted content.
3707 * 1 : csp = Current client state (buffers, headers, etc...)
3708 * 2 : header = On input, pointer to header to modify.
3709 * On output, pointer to the modified header, or NULL
3710 * to remove the header. This function frees the
3711 * original string if necessary.
3713 * Returns : JB_ERR_OK
3715 *********************************************************************/
3716 static jb_err client_range(struct client_state *csp, char **header)
3718 if (content_filters_enabled(csp->action))
3720 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3721 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3728 /* the following functions add headers directly to the header list */
3730 /*********************************************************************
3732 * Function : client_host_adder
3734 * Description : Adds the Host: header field if it is missing.
3735 * Called from `sed'.
3738 * 1 : csp = Current client state (buffers, headers, etc...)
3740 * Returns : JB_ERR_OK on success, or
3741 * JB_ERR_MEMORY on out-of-memory error.
3743 *********************************************************************/
3744 static jb_err client_host_adder(struct client_state *csp)
3749 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3751 /* Header already set by the client, nothing to do. */
3755 if ( !csp->http->hostport || !*(csp->http->hostport))
3757 /* XXX: When does this happen and why is it OK? */
3758 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3763 * remove 'user:pass@' from 'proto://user:pass@host'
3765 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3771 p = csp->http->hostport;
3774 /* XXX: Just add it, we already made sure that it will be unique */
3775 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3776 err = enlist_unique_header(csp->headers, "Host", p);
3783 /*********************************************************************
3785 * Function : client_accept_encoding_adder
3787 * Description : Add an Accept-Encoding header to the client's request
3788 * that disables compression if the action applies, and
3789 * the header is not already there. Called from `sed'.
3790 * Note: For HTTP/1.0, the absence of the header is enough.
3793 * 1 : csp = Current client state (buffers, headers, etc...)
3795 * Returns : JB_ERR_OK on success, or
3796 * JB_ERR_MEMORY on out-of-memory error.
3798 *********************************************************************/
3799 static jb_err client_accept_encoding_adder(struct client_state *csp)
3801 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3802 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3804 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3812 /*********************************************************************
3814 * Function : client_xtra_adder
3816 * Description : Used in the add_client_headers list. Called from `sed'.
3819 * 1 : csp = Current client state (buffers, headers, etc...)
3821 * Returns : JB_ERR_OK on success, or
3822 * JB_ERR_MEMORY on out-of-memory error.
3824 *********************************************************************/
3825 static jb_err client_xtra_adder(struct client_state *csp)
3827 struct list_entry *lst;
3830 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3831 lst ; lst = lst->next)
3833 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3834 err = enlist(csp->headers, lst->str);
3846 /*********************************************************************
3848 * Function : connection_close_adder
3850 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3851 * support. Adds a "Connection: close" header to csp->headers
3852 * unless the header was already present. Called from `sed'.
3854 * FIXME: This whole function shouldn't be neccessary!
3857 * 1 : csp = Current client state (buffers, headers, etc...)
3859 * Returns : JB_ERR_OK on success, or
3860 * JB_ERR_MEMORY on out-of-memory error.
3862 *********************************************************************/
3863 static jb_err connection_close_adder(struct client_state *csp)
3865 const unsigned int flags = csp->flags;
3868 * Return right away if
3870 * - we're parsing server headers and the server header
3871 * "Connection: close" is already set, or if
3873 * - we're parsing client headers and the client header
3874 * "Connection: close" is already set.
3876 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3877 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3878 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3879 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3884 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3886 return enlist(csp->headers, "Connection: close");
3890 /*********************************************************************
3892 * Function : server_http
3894 * Description : - Save the HTTP Status into csp->http->status
3895 * - Set CT_TABOO to prevent filtering if the answer
3896 * is a partial range (HTTP status 206)
3897 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3901 * 1 : csp = Current client state (buffers, headers, etc...)
3902 * 2 : header = On input, pointer to header to modify.
3903 * On output, pointer to the modified header, or NULL
3904 * to remove the header. This function frees the
3905 * original string if necessary.
3907 * Returns : JB_ERR_OK on success, or
3908 * JB_ERR_MEMORY on out-of-memory error.
3910 *********************************************************************/
3911 static jb_err server_http(struct client_state *csp, char **header)
3913 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3914 if (csp->http->status == 206)
3916 csp->content_type = CT_TABOO;
3919 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3921 /* XXX: Should we do a real validity check here? */
3922 if (strlen(*header) > 8)
3925 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3930 * XXX: Should we block the request or
3931 * enlist a valid status code line here?
3933 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3934 "Downgrading to HTTP/1.0 impossible.");
3942 /*********************************************************************
3944 * Function : server_set_cookie
3946 * Description : Handle the server "cookie" header properly.
3947 * Log cookie to the jar file. Then "crunch",
3948 * accept or rewrite it to a session cookie.
3949 * Called from `sed'.
3951 * TODO: Allow the user to specify a new expiration
3952 * time to cause the cookie to expire even before the
3953 * browser is closed.
3956 * 1 : csp = Current client state (buffers, headers, etc...)
3957 * 2 : header = On input, pointer to header to modify.
3958 * On output, pointer to the modified header, or NULL
3959 * to remove the header. This function frees the
3960 * original string if necessary.
3962 * Returns : JB_ERR_OK on success, or
3963 * JB_ERR_MEMORY on out-of-memory error.
3965 *********************************************************************/
3966 static jb_err server_set_cookie(struct client_state *csp, char **header)
3973 #ifdef FEATURE_COOKIE_JAR
3974 if (csp->config->jar)
3977 * Write timestamp into outbuf.
3979 * Complex because not all OSs have tm_gmtoff or
3980 * the %z field in strftime()
3982 char tempbuf[ BUFFER_SIZE ];
3984 #ifdef HAVE_LOCALTIME_R
3985 tm_now = *localtime_r(&now, &tm_now);
3986 #elif FEATURE_PTHREAD
3987 pthread_mutex_lock(&localtime_mutex);
3988 tm_now = *localtime (&now);
3989 pthread_mutex_unlock(&localtime_mutex);
3991 tm_now = *localtime (&now);
3993 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3995 /* strlen("set-cookie: ") = 12 */
3996 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3998 #endif /* def FEATURE_COOKIE_JAR */
4000 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4002 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4005 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4007 /* Flag whether or not to log a message */
4010 /* A variable to store the tag we're working on */
4013 /* Skip "Set-Cookie:" (11 characters) in header */
4014 cur_tag = *header + 11;
4016 /* skip whitespace between "Set-Cookie:" and value */
4017 while (*cur_tag && ijb_isspace(*cur_tag))
4022 /* Loop through each tag in the cookie */
4026 char *next_tag = strchr(cur_tag, ';');
4027 if (next_tag != NULL)
4029 /* Skip the ';' character itself */
4032 /* skip whitespace ";" and start of tag */
4033 while (*next_tag && ijb_isspace(*next_tag))
4040 /* "Next tag" is the end of the string */
4041 next_tag = cur_tag + strlen(cur_tag);
4045 * Check the expiration date to see
4046 * if the cookie is still valid, if yes,
4047 * rewrite it to a session cookie.
4049 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4051 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4053 /* Did we detect the date properly? */
4054 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4057 * Nope, treat it as if it was still valid.
4059 * XXX: Should we remove the whole cookie instead?
4061 log_error(LOG_LEVEL_ERROR,
4062 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4063 string_move(cur_tag, next_tag);
4069 * Yes. Check if the cookie is still valid.
4071 * If the cookie is already expired it's probably
4072 * a delete cookie and even if it isn't, the browser
4073 * will discard it anyway.
4077 * XXX: timegm() isn't available on some AmigaOS
4078 * versions and our replacement doesn't work.
4080 * Our options are to either:
4082 * - disable session-cookies-only completely if timegm
4085 * - to simply remove all expired tags, like it has
4086 * been done until Privoxy 3.0.6 and to live with
4087 * the consequence that it can cause login/logout
4088 * problems on servers that don't validate their
4089 * input properly, or
4091 * - to replace it with mktime in which
4092 * case there is a slight chance of valid cookies
4093 * passing as already expired.
4095 * This is the way it's currently done and it's not
4096 * as bad as it sounds. If the missing GMT offset is
4097 * enough to change the result of the expiration check
4098 * the cookie will be only valid for a few hours
4099 * anyway, which in many cases will be shorter
4100 * than a browser session.
4102 if (cookie_time - now < 0)
4104 log_error(LOG_LEVEL_HEADER,
4105 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4106 /* Just in case some clown sets more then one expiration date */
4112 * Still valid, delete expiration date by copying
4113 * the rest of the string over it.
4115 string_move(cur_tag, next_tag);
4117 /* That changed the header, need to issue a log message */
4121 * Note that the next tag has now been moved to *cur_tag,
4122 * so we do not need to update the cur_tag pointer.
4130 /* Move on to next cookie tag */
4137 assert(NULL != *header);
4138 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4147 #ifdef FEATURE_FORCE_LOAD
4148 /*********************************************************************
4150 * Function : strclean
4152 * Description : In-Situ-Eliminate all occurances of substring in
4156 * 1 : string = string to clean
4157 * 2 : substring = substring to eliminate
4159 * Returns : Number of eliminations
4161 *********************************************************************/
4162 int strclean(char *string, const char *substring)
4168 len = strlen(substring);
4170 while((pos = strstr(string, substring)) != NULL)
4177 while (*p++ != '\0');
4184 #endif /* def FEATURE_FORCE_LOAD */
4187 /*********************************************************************
4189 * Function : parse_header_time
4191 * Description : Parses time formats used in HTTP header strings
4192 * to get the numerical respresentation.
4195 * 1 : header_time = HTTP header time as string.
4196 * 2 : result = storage for header_time in seconds
4198 * Returns : JB_ERR_OK if the time format was recognized, or
4199 * JB_ERR_PARSE otherwise.
4201 *********************************************************************/
4202 static jb_err parse_header_time(const char *header_time, time_t *result)
4207 * Zero out gmt to prevent time zone offsets.
4209 * While this is only necessary on some platforms
4210 * (mingw32 for example), I don't know how to
4211 * detect these automatically and doing it everywhere
4214 memset(&gmt, 0, sizeof(gmt));
4216 /* Tue, 02 Jun 2037 20:00:00 */
4217 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4218 /* Tue, 02-Jun-2037 20:00:00 */
4219 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4220 /* Tue, 02-Jun-37 20:00:00 */
4221 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4222 /* Tuesday, 02-Jun-2037 20:00:00 */
4223 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4224 /* Tuesday Jun 02 20:00:00 2037 */
4225 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4227 return JB_ERR_PARSE;
4230 *result = timegm(&gmt);
4237 /*********************************************************************
4239 * Function : get_destination_from_headers
4241 * Description : Parse the "Host:" header to get the request's destination.
4242 * Only needed if the client's request was forcefully
4243 * redirected into Privoxy.
4245 * Code mainly copied from client_host() which is currently
4246 * run too late for this purpose.
4249 * 1 : headers = List of headers (one of them hopefully being
4250 * the "Host:" header)
4251 * 2 : http = storage for the result (host, port and hostport).
4253 * Returns : JB_ERR_MEMORY in case of memory problems,
4254 * JB_ERR_PARSE if the host header couldn't be found,
4255 * JB_ERR_OK otherwise.
4257 *********************************************************************/
4258 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4264 host = get_header_value(headers, "Host:");
4268 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4269 return JB_ERR_PARSE;
4272 if (NULL == (p = strdup((host))))
4274 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4275 return JB_ERR_MEMORY;
4278 if (NULL == (q = strdup(p)))
4281 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4282 return JB_ERR_MEMORY;
4285 freez(http->hostport);
4289 q = strchr(http->host, ':');
4292 /* Terminate hostname and evaluate port string */
4294 http->port = atoi(q);
4298 http->port = http->ssl ? 443 : 80;
4301 /* Rebuild request URL */
4303 http->url = strdup(http->ssl ? "https://" : "http://");
4304 string_append(&http->url, http->hostport);
4305 string_append(&http->url, http->path);
4306 if (http->url == NULL)
4308 return JB_ERR_MEMORY;
4311 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4319 /*********************************************************************
4321 * Function : create_forged_referrer
4323 * Description : Helper for client_referrer to forge a referer as
4324 * 'http://[hostname:port/' to fool stupid
4325 * checks for in-site links
4328 * 1 : header = Pointer to header pointer
4329 * 2 : hostport = Host and optionally port as string
4331 * Returns : JB_ERR_OK in case of success, or
4332 * JB_ERR_MEMORY in case of memory problems.
4334 *********************************************************************/
4335 static jb_err create_forged_referrer(char **header, const char *hostport)
4337 assert(NULL == *header);
4339 *header = strdup("Referer: http://");
4340 string_append(header, hostport);
4341 string_append(header, "/");
4343 if (NULL == *header)
4345 return JB_ERR_MEMORY;
4348 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4355 /*********************************************************************
4357 * Function : create_fake_referrer
4359 * Description : Helper for client_referrer to create a fake referrer
4360 * based on a string supplied by the user.
4363 * 1 : header = Pointer to header pointer
4364 * 2 : hosthost = Referrer to fake
4366 * Returns : JB_ERR_OK in case of success, or
4367 * JB_ERR_MEMORY in case of memory problems.
4369 *********************************************************************/
4370 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4372 assert(NULL == *header);
4374 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4376 log_error(LOG_LEVEL_HEADER,
4377 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4379 *header = strdup("Referer: ");
4380 string_append(header, fake_referrer);
4382 if (NULL == *header)
4384 return JB_ERR_MEMORY;
4387 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4394 /*********************************************************************
4396 * Function : handle_conditional_hide_referrer_parameter
4398 * Description : Helper for client_referrer to crunch or forge
4399 * the referrer header if the host has changed.
4402 * 1 : header = Pointer to header pointer
4403 * 2 : host = The target host (may include the port)
4404 * 3 : parameter_conditional_block = Boolean to signal
4405 * if we're in conditional-block mode. If not set,
4406 * we're in conditional-forge mode.
4408 * Returns : JB_ERR_OK in case of success, or
4409 * JB_ERR_MEMORY in case of memory problems.
4411 *********************************************************************/
4412 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4413 const char *host, const int parameter_conditional_block)
4415 char *referer = strdup(*header);
4416 const size_t hostlenght = strlen(host);
4418 if (NULL == referer)
4421 return JB_ERR_MEMORY;
4424 /* referer begins with 'Referer: http[s]://' */
4425 if (hostlenght < (strlen(referer)-17))
4428 * Shorten referer to make sure the referer is blocked
4429 * if www.example.org/www.example.com-shall-see-the-referer/
4430 * links to www.example.com/
4432 referer[hostlenght+17] = '\0';
4434 if (NULL == strstr(referer, host))
4436 /* Host has changed */
4437 if (parameter_conditional_block)
4439 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4446 return create_forged_referrer(header, host);