1 const char parsers_rcs[] = "$Id: parsers.c,v 1.133 2008/05/21 15:50:47 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.133 2008/05/21 15:50:47 fabiankeil
48 * Ditch cast from (char **) to (char **).
50 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
51 * Streamline sed()'s prototype and declare
52 * the header parse and add structures static.
54 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
55 * Factor update_server_headers() out of sed(), ditch the
56 * first_run hack and make server_patterns_light static.
58 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
59 * Wrap memmove() calls in string_move()
60 * to document the purpose in one place.
62 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
63 * Normalize linear header white space.
65 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
66 * If a header is split across multiple lines,
67 * merge them to a single line before parsing them.
69 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
70 * Don't provide get_header() with the whole client state
71 * structure when it only needs access to csp->iob.
73 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
74 * Change content_filters_enabled()'s parameter from
75 * csp->action to action so it can be also used in the
76 * CGI code. Don't bother checking if there are filters
77 * loaded, as that's somewhat besides the point.
79 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
80 * Provide get_http_time() with the buffer size so it doesn't
81 * have to blindly assume that the buffer is big enough.
83 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
84 * Don't pass the whole csp structure to flush_socket()
85 * when it only needs a file descriptor and a buffer.
87 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
88 * Remove send-wafer and send-vanilla-wafer actions.
90 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
91 * Remove inspect-jpegs action.
93 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
94 * Let client_range() also handle Request-Range headers
95 * which apparently are still supported by many servers.
97 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
98 * Improve the warning messages that get logged if the action files
99 * "enable" filters but no filters of that type have been loaded.
101 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
102 * In server_content_type():
103 * - Don't require leading white space when detecting image content types.
104 * - Change '... not replaced ...' message to sound less crazy if the text
105 * type actually is 'text/plain'.
106 * - Mark the 'text/plain == binary data' assumption for removal.
107 * - Remove a bunch of trailing white space.
109 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
110 * Minor server_content_disposition() changes:
111 * - Don't regenerate the header name all lower-case.
112 * - Some white space fixes.
113 * - Remove useless log message in case of ENOMEM.
115 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
116 * Garbage-collect the code to add a X-Forwarded-For
117 * header as it seems to be mostly used by accident.
119 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
120 * Fix a crash on mingw32 with some Last Modified times in the future.
122 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
123 * Remove a "can't happen" error block which, over
124 * time, mutated into a "guaranteed to happen" block.
126 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
127 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
128 * - Use shiny new content_filters_enabled() in client_range().
130 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
131 * I forgot about Poland.
133 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
134 * Remove Range and If-Range headers if content filtering is enabled.
136 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
137 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
138 * client_cookie_adder() to make sure send-vanilla-wafer can be
139 * controlled through tags (and thus regression-tested).
141 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
142 * - Remove "scanning headers for" log message again.
143 * - Some more whitespace fixes.
145 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
146 * Refactor client_referrer() and add conditional-forge parameter.
148 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
149 * A bunch of whitespace fixes, pointy hat to me.
151 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
152 * Fix possible memory corruption in server_http, make sure it's not
153 * executed for ordinary server headers and mark some problems for later.
155 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
156 * Let content-type-overwrite{} honour force-text-mode again.
158 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
159 * - Add prototpyes for the header parsers and make them static.
160 * - Comment out client_accept_encoding_adder() which isn't used right now.
162 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
163 * Move the ACTION_FORCE_TEXT_MODE check out of
164 * server_content_type(). Signal other functions
165 * whether or not a content type has been declared.
166 * Part of the fix for BR#1750917.
168 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
169 * Change sed() to return a jb_err in preparation for forward-override{}.
171 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
172 * Adjust "X-Filter: No" to disable dedicated header filters.
174 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
175 * Streamline client_cookie_adder().
177 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
178 * Make sure filters with dynamic jobs actually use them.
180 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
181 * - Introduce dynamic pcrs jobs that can resolve variables.
182 * - Remove unnecessary update_action_bits_for_all_tags() call.
184 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
185 * - Make tagging based on tags set by earlier taggers
186 * of the same kind possible.
187 * - Log whether or not new tags cause action bits updates
188 * (in which case a matching tag-pattern section exists).
189 * - Log if the user tries to set a tag that is already set.
191 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
192 * Introduce tags as alternative way to specify which
193 * actions apply to a request. At the moment tags can be
194 * created based on client and server headers.
196 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
197 * Log a warning if the content is compressed, filtering is
198 * enabled and Privoxy was compiled without zlib support.
201 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
202 * - Fix warnings when compiled with glibc.
203 * - Don't use crumble() for cookie crunching.
204 * - Move cookie time parsing into parse_header_time().
205 * - Let parse_header_time() return a jb_err code
206 * instead of a pointer that can only be used to
207 * check for NULL anyway.
209 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
210 * - Add better protection against malicious gzip headers.
211 * - Stop logging the first hundred bytes of decompressed content.
212 * It looks like it's working and there is always debug 16.
213 * - Log the content size after decompression in decompress_iob()
214 * instead of pcrs_filter_response().
216 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
217 * - Use dedicated header filter actions instead of abusing "filter".
218 * Replace "filter-client-headers" and "filter-client-headers"
219 * with "server-header-filter" and "client-header-filter".
220 * - Remove filter_client_header() and filter_client_header(),
221 * filter_header() now checks the shiny new
222 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
224 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
225 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
226 * - Handle "Cookie:" and "Connection:" headers a bit smarter
227 * (don't crunch them just to recreate them later on).
228 * - Add another non-standard time format for the cookie
229 * expiration date detection.
230 * - Fix a valgrind warning.
232 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
233 * Improve cookie expiration date detection.
235 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
236 * Don't run server_content_length() the first time
237 * sed() parses server headers; only adjust the
238 * Content-Length header if the page was modified.
240 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
241 * Fix log messages regarding the cookie time format
242 * (cookie and request URL were mixed up).
244 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
245 * - Let decompress_iob()
246 * - not corrupt the content if decompression fails
247 * early. (the first byte(s) were lost).
248 * - use pointer arithmetics with defined outcome for
250 * - Use a different kludge to remember a failed decompression.
252 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
253 * Search for Max-Forwards headers case-insensitive,
254 * don't generate the "501 unsupported" message for invalid
255 * Max-Forwards values and don't increase negative ones.
257 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
258 * - Let server_set_cookie() check the expiration date
259 * of cookies and don't touch the ones that are already
260 * expired. Fixes problems with low quality web applications
261 * as described in BR 932612.
263 * - Adjust comment in client_max_forwards to reality;
264 * remove invalid Max-Forwards headers.
266 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
267 * Stop filter_header() from unintentionally removing
268 * empty header lines that were enlisted by the continue
271 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
272 * - Repeat the request URL before logging any headers.
273 * Makes reading the log easier in case of simultaneous requests.
274 * - If there are more than one Content-Type headers in one request,
275 * use the first one and remove the others.
276 * - Remove "newval" variable in server_content_type().
277 * It's only used once.
279 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
280 * Correct a cast, check inflateEnd() exit code
281 * to see if we have to, replace sprintf calls
284 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
285 * Integrate a modified version of Wil Mahan's
286 * zlib patch (PR #895531).
288 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
289 * Skip empty filter files in filter_header()
290 * but don't ignore the ones that come afterwards.
291 * Fixes BR 1619208, this time for real.
293 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
294 * Reverted parts of my last commit
295 * to keep error handling working.
297 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
298 * Fixed gcc43 conversion warnings.
300 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
301 * Bringing back the "useless" localtime() call
302 * I removed in revision 1.67. On some platforms
303 * it's necessary to prevent time zone offsets.
305 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
306 * Rebuild request URL in get_destination_from_headers()
307 * to make sure redirect{pcrs command} works as expected
308 * for intercepted requests.
310 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
311 * Added get_destination_from_headers().
313 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
314 * Make pthread mutex locking more generic. Instead of
315 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
316 * and use mutex locking unless there is an _r function
317 * available. Better safe than sorry.
319 * Fixes "./configure --disable-pthread" and should result
320 * in less threading-related problems on pthread-using platforms,
321 * but it still doesn't fix BR#1122404.
323 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
324 * The special header "X-Filter: No" now disables
325 * header filtering as well.
327 * Revision 1.73 2006/09/23 13:26:38 roro
328 * Replace TABs by spaces in source code.
330 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
331 * Don't print a log message every time filter_headers is
332 * entered or left. It only creates noise without any real
335 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
336 * Fix +hide-if-modified-since{-n}.
338 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
339 * Have hide-if-modified-since interpret the random
340 * range value as minutes instead of hours. Allows
341 * more fine-grained configuration.
343 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
344 * Always have parse_header_time return a pointer
345 * that actual makes sense, even though we currently
346 * only need it to detect problems.
348 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
349 * Added config option enable-remote-http-toggle
350 * to specify if Privoxy should recognize special
351 * headers (currently only X-Filter) to change its
352 * behaviour. Disabled by default.
354 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
355 * After filtering de-chunked instances, remove
356 * "Transfer-Encoding" header entirely instead of changing
357 * it to "Transfer-Encoding: identity", which is invalid.
358 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
360 * Don't use localtime in parse_header_time. An empty time struct
361 * is good enough, it gets overwritten by strptime anyway.
363 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
364 * Use gmtime_r if available, fallback to gmtime with mutex
365 * protection for MacOSX and use vanilla gmtime for the rest.
367 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
368 * Changed client_referrer to use the right type (size_t) for
369 * hostlenght and to shorten the temporary referrer string with
370 * '\0' instead of adding a useless line break.
372 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
373 * - Back to timegm() using GnuPG's replacement if necessary.
374 * Using mktime() and localtime() could add a on hour offset if
375 * the randomize factor was big enough to lead to a summer/wintertime
378 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
380 * - Moved randomization code into pick_from_range().
382 * - Changed parse_header_time definition.
383 * time_t isn't guaranteed to be signed and
384 * if it isn't, -1 isn't available as error code.
385 * Changed some variable types in client_if_modified_since()
386 * because of the same reason.
388 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
389 * OS/2 compilation compatibility fixups
391 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
392 * Changed include from strptime.c to strptime.h
394 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
395 * Split filter-headers{} into filter-client-headers{}
396 * and filter-server-headers{}.
397 * Added parse_header_time() to share some code.
398 * Replaced timegm() with mktime().
400 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
401 * Windows service integration
403 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
404 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
406 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
407 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
408 * with what was really the latest development (the v_3_0_branch branch)
410 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
411 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
413 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
414 * Add the ability to check jpeg images for invalid
415 * lengths of comment blocks. Defensive strategy
416 * against the exploit:
417 * Microsoft Security Bulletin MS04-028
418 * Buffer Overrun in JPEG Processing (GDI+) Could
419 * Allow Code Execution (833987)
420 * Enabled with +inspect-jpegs in actions files.
422 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
423 * Excluded text/plain objects from filtering. This fixes a
424 * couple of client-crashing, download corruption and
425 * Privoxy performance issues, whose root cause lies in
426 * web servers labelling content of unknown type as text/plain.
428 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
429 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
431 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
432 * Completing the previous change
434 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
435 * Added temporary workaround for bug in PHP < 4.2.3
437 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
438 * 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.
440 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
441 * Fix typo: supressed -> suppressed
443 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
444 * Improved cookie logging
446 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
447 * Added basic support for OPTIONS and TRACE HTTP methods:
448 * - New parser function client_max_forwards which decrements
449 * the Max-Forwards HTTP header field of OPTIONS and TRACE
450 * requests by one before forwarding
451 * - New parser function client_host which extracts the host
452 * and port information from the HTTP header field if the
453 * request URI was not absolute
454 * - Don't crumble and re-add the Host: header, but only generate
455 * and append if missing
457 * Revision 1.56 2002/05/12 15:34:22 jongfoster
458 * Fixing typo in a comment
460 * Revision 1.55 2002/05/08 16:01:07 oes
461 * Optimized add_to_iob:
462 * - Use realloc instead of malloc(), memcpy(), free()
463 * - Expand to powers of two if possible, to get
464 * O(log n) reallocs instead of O(n).
465 * - Moved check for buffer limit here from chat
466 * - Report failure via returncode
468 * Revision 1.54 2002/04/02 15:03:16 oes
469 * Tiny code cosmetics
471 * Revision 1.53 2002/03/26 22:29:55 swa
472 * we have a new homepage!
474 * Revision 1.52 2002/03/24 13:25:43 swa
475 * name change related issues
477 * Revision 1.51 2002/03/13 00:27:05 jongfoster
480 * Revision 1.50 2002/03/12 01:45:35 oes
481 * More verbose logging
483 * Revision 1.49 2002/03/09 20:03:52 jongfoster
484 * - Making various functions return int rather than size_t.
485 * (Undoing a recent change). Since size_t is unsigned on
486 * Windows, functions like read_socket that return -1 on
487 * error cannot return a size_t.
489 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
490 * crashes, and also frequently caused JB to jump to 100%
491 * CPU and stay there. (Because it thought it had just
492 * read ((unsigned)-1) == 4Gb of data...)
494 * - The signature of write_socket has changed, it now simply
495 * returns success=0/failure=nonzero.
497 * - Trying to get rid of a few warnings --with-debug on
498 * Windows, I've introduced a new type "jb_socket". This is
499 * used for the socket file descriptors. On Windows, this
500 * is SOCKET (a typedef for unsigned). Everywhere else, it's
501 * an int. The error value can't be -1 any more, so it's
502 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
503 * Windows it maps to the #define INVALID_SOCKET.)
505 * - The signature of bind_port has changed.
507 * Revision 1.48 2002/03/07 03:46:53 oes
508 * Fixed compiler warnings etc
510 * Revision 1.47 2002/02/20 23:15:13 jongfoster
511 * Parsing functions now handle out-of-memory gracefully by returning
514 * Revision 1.46 2002/01/17 21:03:47 jongfoster
515 * Moving all our URL and URL pattern parsing code to urlmatch.c.
517 * Revision 1.45 2002/01/09 14:33:03 oes
518 * Added support for localtime_r.
520 * Revision 1.44 2001/12/14 01:22:54 steudten
521 * Remove 'user:pass@' from 'proto://user:pass@host' for the
522 * new added header 'Host: ..'. (See Req ID 491818)
524 * Revision 1.43 2001/11/23 00:26:38 jongfoster
525 * Fixing two really stupid errors in my previous commit
527 * Revision 1.42 2001/11/22 21:59:30 jongfoster
528 * Adding code to handle +no-cookies-keep
530 * Revision 1.41 2001/11/05 23:43:05 steudten
531 * Add time+date to log files.
533 * Revision 1.40 2001/10/26 20:13:09 jongfoster
534 * ctype.h is needed in Windows, too.
536 * Revision 1.39 2001/10/26 17:40:04 oes
537 * Introduced get_header_value()
538 * Removed http->user_agent, csp->referrer and csp->accept_types
539 * Removed client_accept()
541 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
542 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
543 * threads to call select() simultaneously. So, it's time to do a real, live,
544 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
545 * (native). Both versions will work, but using __OS2__ offers multi-threading.
547 * Revision 1.37 2001/10/23 21:36:02 jongfoster
548 * Documenting sed()'s error behaviou (doc change only)
550 * Revision 1.36 2001/10/13 12:51:51 joergs
551 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
552 * force-load), instead crumble Host: and add it (again) in client_host_adder
553 * (in case we get a HTTP/1.0 request without Host: header and forward it to
554 * a HTTP/1.1 server/proxy).
556 * Revision 1.35 2001/10/09 22:39:21 jongfoster
557 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
560 * Revision 1.34 2001/10/07 18:50:55 oes
561 * Added server_content_encoding, renamed server_transfer_encoding
563 * Revision 1.33 2001/10/07 18:04:49 oes
564 * Changed server_http11 to server_http and its pattern to "HTTP".
565 * Additional functionality: it now saves the HTTP status into
566 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
568 * Revision 1.32 2001/10/07 15:43:28 oes
569 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
570 * client_te and client_accept_encoding_adder, triggered by the new
571 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
572 * changed to allow only identity and chunked, and the TE header is
573 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
575 * parse_http_request no longer does anything than parsing. The rewriting
576 * of http->cmd and version mangling are gone. It now also recognizes
577 * the put and delete methods and saves the url in http->url. Removed
580 * renamed content_type and content_length to have the server_ prefix
582 * server_content_type now only works if csp->content_type != CT_TABOO
584 * added server_transfer_encoding, which
585 * - Sets CT_TABOO to prohibit filtering if encoding compresses
586 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
587 * - Change from "chunked" to "identity" if body was chunked
588 * but has been de-chunked for filtering.
590 * added server_content_md5 which crunches any Content-MD5 headers
591 * if the body was modified.
593 * made server_http11 conditional on +downgrade action
595 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
597 * Revision 1.31 2001/10/05 14:25:02 oes
598 * Crumble Keep-Alive from Server
600 * Revision 1.30 2001/09/29 12:56:03 joergs
601 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
603 * Revision 1.29 2001/09/24 21:09:24 jongfoster
604 * Fixing 2 memory leaks that Guy spotted, where the paramater to
605 * enlist() was not being free()d.
607 * Revision 1.28 2001/09/22 16:32:28 jongfoster
608 * Removing unused #includes.
610 * Revision 1.27 2001/09/20 15:45:25 steudten
612 * add casting from size_t to int for printf()
613 * remove local variable shadow s2
615 * Revision 1.26 2001/09/16 17:05:14 jongfoster
616 * Removing unused #include showarg.h
618 * Revision 1.25 2001/09/16 13:21:27 jongfoster
619 * Changes to use new list functions.
621 * Revision 1.24 2001/09/13 23:05:50 jongfoster
622 * Changing the string paramater to the header parsers a "const".
624 * Revision 1.23 2001/09/12 18:08:19 steudten
626 * In parse_http_request() header rewriting miss the host value, so
627 * from http://www.mydomain.com the result was just " / " not
628 * http://www.mydomain.com/ in case we forward.
630 * Revision 1.22 2001/09/10 10:58:53 oes
631 * Silenced compiler warnings
633 * Revision 1.21 2001/07/31 14:46:00 oes
634 * - Persistant connections now suppressed
635 * - sed() no longer appends empty header to csp->headers
637 * Revision 1.20 2001/07/30 22:08:36 jongfoster
638 * Tidying up #defines:
639 * - All feature #defines are now of the form FEATURE_xxx
640 * - Permanently turned off WIN_GUI_EDIT
641 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
643 * Revision 1.19 2001/07/25 17:21:54 oes
644 * client_uagent now saves copy of User-Agent: header value
646 * Revision 1.18 2001/07/13 14:02:46 oes
647 * - Included fix to repair broken HTTP requests that
648 * don't contain a path, not even '/'.
649 * - Removed all #ifdef PCRS
650 * - content_type now always inspected and classified as
651 * text, gif or other.
652 * - formatting / comments
654 * Revision 1.17 2001/06/29 21:45:41 oes
655 * Indentation, CRLF->LF, Tab-> Space
657 * Revision 1.16 2001/06/29 13:32:42 oes
659 * - Adapted free_http_request
660 * - Removed logentry from cancelled commit
662 * Revision 1.15 2001/06/03 19:12:38 oes
663 * deleted const struct interceptors
665 * Revision 1.14 2001/06/01 18:49:17 jongfoster
666 * Replaced "list_share" with "list" - the tiny memory gain was not
667 * worth the extra complexity.
669 * Revision 1.13 2001/05/31 21:30:33 jongfoster
670 * Removed list code - it's now in list.[ch]
671 * Renamed "permission" to "action", and changed many features
672 * to use the actions file rather than the global config.
674 * Revision 1.12 2001/05/31 17:33:13 oes
678 * Revision 1.11 2001/05/29 20:11:19 joergs
679 * '/ * inside comment' warning removed.
681 * Revision 1.10 2001/05/29 09:50:24 jongfoster
682 * Unified blocklist/imagelist/permissionslist.
683 * File format is still under discussion, but the internal changes
686 * Also modified interceptor behaviour:
687 * - We now intercept all URLs beginning with one of the following
688 * prefixes (and *only* these prefixes):
690 * * http://ijbswa.sf.net/config/
691 * * http://ijbswa.sourceforge.net/config/
692 * - New interceptors "home page" - go to http://i.j.b/ to see it.
693 * - Internal changes so that intercepted and fast redirect pages
694 * are not replaced with an image.
695 * - Interceptors now have the option to send a binary page direct
696 * to the client. (i.e. ijb-send-banner uses this)
697 * - Implemented show-url-info interceptor. (Which is why I needed
698 * the above interceptors changes - a typical URL is
699 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
700 * The previous mechanism would not have intercepted that, and
701 * if it had been intercepted then it then it would have replaced
704 * Revision 1.9 2001/05/28 17:26:33 jongfoster
705 * Fixing segfault if last header was crunched.
706 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
707 * can use the cross-platform sprintf() instead.)
709 * Revision 1.8 2001/05/27 22:17:04 oes
711 * - re_process_buffer no longer writes the modified buffer
712 * to the client, which was very ugly. It now returns the
713 * buffer, which it is then written by chat.
715 * - content_length now adjusts the Content-Length: header
716 * for modified documents rather than crunch()ing it.
717 * (Length info in csp->content_length, which is 0 for
718 * unmodified documents)
720 * - For this to work, sed() is called twice when filtering.
722 * Revision 1.7 2001/05/27 13:19:06 oes
723 * Patched Joergs solution for the content-length in.
725 * Revision 1.6 2001/05/26 13:39:32 jongfoster
726 * Only crunches Content-Length header if applying RE filtering.
727 * Without this fix, Microsoft Windows Update wouldn't work.
729 * Revision 1.5 2001/05/26 00:28:36 jongfoster
730 * Automatic reloading of config file.
731 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
732 * Most of the global variables have been moved to a new
733 * struct configuration_spec, accessed through csp->config->globalname
734 * Most of the globals remaining are used by the Win32 GUI.
736 * Revision 1.4 2001/05/22 18:46:04 oes
738 * - Enabled filtering banners by size rather than URL
739 * by adding patterns that replace all standard banner
740 * sizes with the "Junkbuster" gif to the re_filterfile
742 * - Enabled filtering WebBugs by providing a pattern
743 * which kills all 1x1 images
745 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
746 * which is selected by the (nonstandard and therefore
747 * capital) letter 'U' in the option string.
748 * It causes the quantifiers to be ungreedy by default.
749 * Appending a ? turns back to greedy (!).
751 * - Added a new interceptor ijb-send-banner, which
752 * sends back the "Junkbuster" gif. Without imagelist or
753 * MSIE detection support, or if tinygif = 1, or the
754 * URL isn't recognized as an imageurl, a lame HTML
755 * explanation is sent instead.
757 * - Added new feature, which permits blocking remote
758 * script redirects and firing back a local redirect
760 * The feature is conditionally compiled, i.e. it
761 * can be disabled with --disable-fast-redirects,
762 * plus it must be activated by a "fast-redirects"
763 * line in the config file, has its own log level
764 * and of course wants to be displayed by show-proxy-args
765 * Note: Boy, all the #ifdefs in 1001 locations and
766 * all the fumbling with configure.in and acconfig.h
767 * were *way* more work than the feature itself :-(
769 * - Because a generic redirect template was needed for
770 * this, tinygif = 3 now uses the same.
772 * - Moved GIFs, and other static HTTP response templates
777 * - Removed some >400 CRs again (Jon, you really worked
780 * Revision 1.3 2001/05/20 01:21:20 jongfoster
781 * Version 2.9.4 checkin.
782 * - Merged popupfile and cookiefile, and added control over PCRS
783 * filtering, in new "permissionsfile".
784 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
785 * file error you now get a message box (in the Win32 GUI) rather
786 * than the program exiting with no explanation.
787 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
789 * - Removed tabs from "config"
790 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
791 * - Bumped up version number.
793 * Revision 1.2 2001/05/17 23:02:36 oes
794 * - Made referrer option accept 'L' as a substitute for '§'
796 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
797 * Initial import of version 2.9.3 source tree
800 *********************************************************************/
807 #include <sys/types.h>
817 * Convince GNU's libc to provide a strptime prototype.
820 #endif /*__GLIBC__ */
827 #if !defined(_WIN32) && !defined(__OS2__)
833 #ifdef FEATURE_PTHREAD
835 /* jcc.h is for mutex semapores only */
836 #endif /* def FEATURE_PTHREAD */
841 #include "jbsockets.h"
842 #include "miscutil.h"
847 #ifndef HAVE_STRPTIME
848 #include "strptime.h"
851 const char parsers_h_rcs[] = PARSERS_H_VERSION;
853 /* Fix a problem with Solaris. There should be no effect on other
855 * Solaris's isspace() is a macro which uses its argument directly
856 * as an array index. Therefore we need to make sure that high-bit
857 * characters generate +ve values, and ideally we also want to make
858 * the argument match the declared parameter type of "int".
860 * Why did they write a character function that can't take a simple
861 * "char" argument? Doh!
863 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
864 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
866 static char *get_header_line(struct iob *iob);
867 static jb_err scan_headers(struct client_state *csp);
868 static jb_err header_tagger(struct client_state *csp, char *header);
869 static jb_err parse_header_time(const char *header_time, time_t *result);
871 static jb_err crumble (struct client_state *csp, char **header);
872 static jb_err connection (struct client_state *csp, char **header);
873 static jb_err filter_header (struct client_state *csp, char **header);
874 static jb_err client_referrer (struct client_state *csp, char **header);
875 static jb_err client_uagent (struct client_state *csp, char **header);
876 static jb_err client_ua (struct client_state *csp, char **header);
877 static jb_err client_from (struct client_state *csp, char **header);
878 static jb_err client_send_cookie (struct client_state *csp, char **header);
879 static jb_err client_x_forwarded (struct client_state *csp, char **header);
880 static jb_err client_accept_encoding (struct client_state *csp, char **header);
881 static jb_err client_te (struct client_state *csp, char **header);
882 static jb_err client_max_forwards (struct client_state *csp, char **header);
883 static jb_err client_host (struct client_state *csp, char **header);
884 static jb_err client_if_modified_since (struct client_state *csp, char **header);
885 static jb_err client_accept_language (struct client_state *csp, char **header);
886 static jb_err client_if_none_match (struct client_state *csp, char **header);
887 static jb_err crunch_client_header (struct client_state *csp, char **header);
888 static jb_err client_x_filter (struct client_state *csp, char **header);
889 static jb_err client_range (struct client_state *csp, char **header);
890 static jb_err server_set_cookie (struct client_state *csp, char **header);
891 static jb_err server_content_type (struct client_state *csp, char **header);
892 static jb_err server_content_length (struct client_state *csp, char **header);
893 static jb_err server_content_md5 (struct client_state *csp, char **header);
894 static jb_err server_content_encoding (struct client_state *csp, char **header);
895 static jb_err server_transfer_coding (struct client_state *csp, char **header);
896 static jb_err server_http (struct client_state *csp, char **header);
897 static jb_err crunch_server_header (struct client_state *csp, char **header);
898 static jb_err server_last_modified (struct client_state *csp, char **header);
899 static jb_err server_content_disposition(struct client_state *csp, char **header);
901 static jb_err client_host_adder (struct client_state *csp);
902 static jb_err client_xtra_adder (struct client_state *csp);
903 static jb_err connection_close_adder (struct client_state *csp);
905 static jb_err create_forged_referrer(char **header, const char *hostport);
906 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
907 static jb_err handle_conditional_hide_referrer_parameter(char **header,
908 const char *host, const int parameter_conditional_block);
911 * List of functions to run on a list of headers.
915 /** The header prefix to match */
918 /** The length of the prefix to match */
921 /** The function to apply to this line */
922 const parser_func_ptr parser;
925 static const struct parsers client_patterns[] = {
926 { "referer:", 8, client_referrer },
927 { "user-agent:", 11, client_uagent },
928 { "ua-", 3, client_ua },
929 { "from:", 5, client_from },
930 { "cookie:", 7, client_send_cookie },
931 { "x-forwarded-for:", 16, client_x_forwarded },
932 { "Accept-Encoding:", 16, client_accept_encoding },
933 { "TE:", 3, client_te },
934 { "Host:", 5, client_host },
935 { "if-modified-since:", 18, client_if_modified_since },
936 { "Keep-Alive:", 11, crumble },
937 { "connection:", 11, connection },
938 { "proxy-connection:", 17, crumble },
939 { "max-forwards:", 13, client_max_forwards },
940 { "Accept-Language:", 16, client_accept_language },
941 { "if-none-match:", 14, client_if_none_match },
942 { "Range:", 6, client_range },
943 { "Request-Range:", 14, client_range },
944 { "If-Range:", 9, client_range },
945 { "X-Filter:", 9, client_x_filter },
946 { "*", 0, crunch_client_header },
947 { "*", 0, filter_header },
951 static const struct parsers server_patterns[] = {
952 { "HTTP/", 5, server_http },
953 { "set-cookie:", 11, server_set_cookie },
954 { "connection:", 11, connection },
955 { "Content-Type:", 13, server_content_type },
956 { "Content-MD5:", 12, server_content_md5 },
957 { "Content-Encoding:", 17, server_content_encoding },
958 { "Transfer-Encoding:", 18, server_transfer_coding },
959 { "Keep-Alive:", 11, crumble },
960 { "content-disposition:", 20, server_content_disposition },
961 { "Last-Modified:", 14, server_last_modified },
962 { "*", 0, crunch_server_header },
963 { "*", 0, filter_header },
967 static const add_header_func_ptr add_client_headers[] = {
970 /* Temporarily disabled: client_accept_encoding_adder, */
971 connection_close_adder,
975 static const add_header_func_ptr add_server_headers[] = {
976 connection_close_adder,
980 /*********************************************************************
982 * Function : flush_socket
984 * Description : Write any pending "buffered" content.
987 * 1 : fd = file descriptor of the socket to read
988 * 2 : iob = The I/O buffer to flush, usually csp->iob.
990 * Returns : On success, the number of bytes written are returned (zero
991 * indicates nothing was written). On error, -1 is returned,
992 * and errno is set appropriately. If count is zero and the
993 * file descriptor refers to a regular file, 0 will be
994 * returned without causing any other effect. For a special
995 * file, the results are not portable.
997 *********************************************************************/
998 int flush_socket(jb_socket fd, struct iob *iob)
1000 int len = iob->eod - iob->cur;
1007 if (write_socket(fd, iob->cur, (size_t)len))
1011 iob->eod = iob->cur = iob->buf;
1017 /*********************************************************************
1019 * Function : add_to_iob
1021 * Description : Add content to the buffered page, expanding the
1022 * buffer if necessary.
1025 * 1 : csp = Current client state (buffers, headers, etc...)
1026 * 2 : buf = holds the content to be added to the page
1027 * 3 : n = number of bytes to be added
1029 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1030 * or buffer limit reached.
1032 *********************************************************************/
1033 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1035 struct iob *iob = csp->iob;
1036 size_t used, offset, need, want;
1039 if (n <= 0) return JB_ERR_OK;
1041 used = (size_t)(iob->eod - iob->buf);
1042 offset = (size_t)(iob->cur - iob->buf);
1043 need = used + (size_t)n + 1;
1046 * If the buffer can't hold the new data, extend it first.
1047 * Use the next power of two if possible, else use the actual need.
1049 if (need > csp->config->buffer_limit)
1051 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1052 return JB_ERR_MEMORY;
1055 if (need > iob->size)
1057 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1059 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1063 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1069 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1070 return JB_ERR_MEMORY;
1073 /* Update the iob pointers */
1074 iob->cur = p + offset;
1075 iob->eod = p + used;
1079 /* copy the new data into the iob buffer */
1080 memcpy(iob->eod, buf, (size_t)n);
1082 /* point to the end of the data */
1085 /* null terminate == cheap insurance */
1094 /*********************************************************************
1096 * Function : decompress_iob
1098 * Description : Decompress buffered page, expanding the
1099 * buffer as necessary. csp->iob->cur
1100 * should point to the the beginning of the
1101 * compressed data block.
1104 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * Returns : JB_ERR_OK on success,
1107 * JB_ERR_MEMORY if out-of-memory limit reached, and
1108 * JB_ERR_COMPRESS if error decompressing buffer.
1110 *********************************************************************/
1111 jb_err decompress_iob(struct client_state *csp)
1113 char *buf; /* new, uncompressed buffer */
1114 char *cur; /* Current iob position (to keep the original
1115 * iob->cur unmodified if we return early) */
1116 size_t bufsize; /* allocated size of the new buffer */
1117 size_t old_size; /* Content size before decompression */
1118 size_t skip_size; /* Number of bytes at the beginning of the iob
1119 that we should NOT decompress. */
1120 int status; /* return status of the inflate() call */
1121 z_stream zstr; /* used by calls to zlib */
1123 assert(csp->iob->cur - csp->iob->buf > 0);
1124 assert(csp->iob->eod - csp->iob->cur > 0);
1126 bufsize = csp->iob->size;
1127 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1128 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1130 cur = csp->iob->cur;
1135 * This is to protect the parsing of gzipped data,
1136 * but it should(?) be valid for deflated data also.
1138 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1139 return JB_ERR_COMPRESS;
1142 if (csp->content_type & CT_GZIP)
1145 * Our task is slightly complicated by the facts that data
1146 * compressed by gzip does not include a zlib header, and
1147 * that there is no easily accessible interface in zlib to
1148 * handle a gzip header. We strip off the gzip header by
1149 * hand, and later inform zlib not to expect a header.
1153 * Strip off the gzip header. Please see RFC 1952 for more
1154 * explanation of the appropriate fields.
1156 if ((*cur++ != (char)0x1f)
1157 || (*cur++ != (char)0x8b)
1158 || (*cur++ != Z_DEFLATED))
1160 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1161 return JB_ERR_COMPRESS;
1167 * XXX: These magic numbers should be replaced
1168 * with macros to give a better idea what they do.
1172 /* The gzip header has reserved bits set; bail out. */
1173 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1174 return JB_ERR_COMPRESS;
1178 /* Skip extra fields if necessary. */
1182 * Skip a given number of bytes, specified
1183 * as a 16-bit little-endian value.
1186 * XXX: This code used to be:
1188 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1190 * which I had to change into:
1192 * cur += *cur++ + (*cur++ << 8);
1194 * at which point gcc43 finally noticed that the value
1195 * of cur is undefined (it depends on which of the
1196 * summands is evaluated first).
1198 * I haven't come across a site where this
1199 * code is actually executed yet, but I hope
1203 skip_bytes = *cur++;
1204 skip_bytes = *cur++ << 8;
1206 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1209 * The number of bytes to skip should be positive
1210 * and we'd like to stay in the buffer.
1212 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1214 log_error(LOG_LEVEL_ERROR,
1215 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1217 return JB_ERR_COMPRESS;
1219 log_error(LOG_LEVEL_INFO,
1220 "Skipping %d bytes for gzip compression. Does this sound right?",
1225 /* Skip the filename if necessary. */
1228 /* A null-terminated string is supposed to follow. */
1229 while (*cur++ && (cur < csp->iob->eod));
1233 /* Skip the comment if necessary. */
1236 /* A null-terminated string is supposed to follow. */
1237 while (*cur++ && (cur < csp->iob->eod));
1240 /* Skip the CRC if necessary. */
1246 if (cur >= csp->iob->eod)
1249 * If the current position pointer reached or passed
1250 * the buffer end, we were obviously tricked to skip
1253 log_error(LOG_LEVEL_ERROR,
1254 "Malformed gzip header detected. Aborting decompression.");
1255 return JB_ERR_COMPRESS;
1259 else if (csp->content_type & CT_DEFLATE)
1262 * XXX: The debug level should be lowered
1263 * before the next stable release.
1265 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1267 * In theory (that is, according to RFC 1950), deflate-compressed
1268 * data should begin with a two-byte zlib header and have an
1269 * adler32 checksum at the end. It seems that in practice only
1270 * the raw compressed data is sent. Note that this means that
1271 * we are not RFC 1950-compliant here, but the advantage is that
1272 * this actually works. :)
1274 * We add a dummy null byte to tell zlib where the data ends,
1275 * and later inform it not to expect a header.
1277 * Fortunately, add_to_iob() has thoughtfully null-terminated
1278 * the buffer; we can just increment the end pointer to include
1285 log_error(LOG_LEVEL_ERROR,
1286 "Unable to determine compression format for decompression");
1287 return JB_ERR_COMPRESS;
1290 /* Set up the fields required by zlib. */
1291 zstr.next_in = (Bytef *)cur;
1292 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1293 zstr.zalloc = Z_NULL;
1294 zstr.zfree = Z_NULL;
1295 zstr.opaque = Z_NULL;
1298 * Passing -MAX_WBITS to inflateInit2 tells the library
1299 * that there is no zlib header.
1301 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1303 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1304 return JB_ERR_COMPRESS;
1308 * Next, we allocate new storage for the inflated data.
1309 * We don't modify the existing iob yet, so in case there
1310 * is error in decompression we can recover gracefully.
1312 buf = zalloc(bufsize);
1315 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1316 return JB_ERR_MEMORY;
1319 assert(bufsize >= skip_size);
1320 memcpy(buf, csp->iob->buf, skip_size);
1321 zstr.avail_out = bufsize - skip_size;
1322 zstr.next_out = (Bytef *)buf + skip_size;
1324 /* Try to decompress the whole stream in one shot. */
1325 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1327 /* We need to allocate more memory for the output buffer. */
1329 char *tmpbuf; /* used for realloc'ing the buffer */
1330 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1333 * If zlib wants more data then there's a problem, because
1334 * the complete compressed file should have been buffered.
1336 if (0 == zstr.avail_in)
1338 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1339 return JB_ERR_COMPRESS;
1343 * If we tried the limit and still didn't have enough
1344 * memory, just give up.
1346 if (bufsize == csp->config->buffer_limit)
1348 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1349 return JB_ERR_MEMORY;
1352 /* Try doubling the buffer size each time. */
1355 /* Don't exceed the buffer limit. */
1356 if (bufsize > csp->config->buffer_limit)
1358 bufsize = csp->config->buffer_limit;
1361 /* Try to allocate the new buffer. */
1362 tmpbuf = realloc(buf, bufsize);
1365 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1367 return JB_ERR_MEMORY;
1371 char *oldnext_out = (char *)zstr.next_out;
1374 * Update the fields for inflate() to use the new
1375 * buffer, which may be in a location different from
1378 zstr.avail_out += bufsize - oldbufsize;
1379 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1382 * Compare with an uglier method of calculating these values
1383 * that doesn't require the extra oldbufsize variable.
1385 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1386 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1387 assert(zstr.avail_out > 0);
1393 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1395 log_error(LOG_LEVEL_ERROR,
1396 "Inconsistent stream state after decompression: %s", zstr.msg);
1398 * XXX: Intentionally no return.
1400 * According to zlib.h, Z_STREAM_ERROR is returned
1401 * "if the stream state was inconsistent".
1403 * I assume in this case inflate()'s status
1404 * would also be something different than Z_STREAM_END
1405 * so this check should be redundant, but lets see.
1409 if (status != Z_STREAM_END)
1411 /* We failed to decompress the stream. */
1412 log_error(LOG_LEVEL_ERROR,
1413 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1414 return JB_ERR_COMPRESS;
1418 * Finally, we can actually update the iob, since the
1419 * decompression was successful. First, free the old
1422 freez(csp->iob->buf);
1424 /* Now, update the iob to use the new buffer. */
1425 csp->iob->buf = buf;
1426 csp->iob->cur = csp->iob->buf + skip_size;
1427 csp->iob->eod = (char *)zstr.next_out;
1428 csp->iob->size = bufsize;
1431 * Make sure the new uncompressed iob obeys some minimal
1432 * consistency conditions.
1434 if ((csp->iob->buf < csp->iob->cur)
1435 && (csp->iob->cur <= csp->iob->eod)
1436 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1438 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1441 log_error(LOG_LEVEL_RE_FILTER,
1442 "Decompression successful. Old size: %d, new size: %d.",
1443 old_size, new_size);
1447 /* zlib thinks this is OK, so lets do the same. */
1448 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1453 /* It seems that zlib did something weird. */
1454 log_error(LOG_LEVEL_ERROR,
1455 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1456 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1457 csp->iob->eod, csp->iob->buf + csp->iob->size);
1458 return JB_ERR_COMPRESS;
1464 #endif /* defined(FEATURE_ZLIB) */
1467 /*********************************************************************
1469 * Function : string_move
1471 * Description : memmove wrapper to move the last part of a string
1472 * towards the beginning, overwriting the part in
1473 * the middle. strlcpy() can't be used here as the
1477 * 1 : dst = Destination to overwrite
1478 * 2 : src = Source to move.
1482 *********************************************************************/
1483 static void string_move(char *dst, char *src)
1487 /* +1 to copy the terminating nul as well. */
1488 memmove(dst, src, strlen(src)+1);
1492 /*********************************************************************
1494 * Function : normalize_lws
1496 * Description : Reduces unquoted linear white space in headers
1497 * to a single space in accordance with RFC 2616 2.2.
1498 * This simplifies parsing and filtering later on.
1500 * XXX: Remove log messages before
1501 * the next stable release?
1504 * 1 : header = A header with linear white space to reduce.
1508 *********************************************************************/
1509 static void normalize_lws(char *header)
1515 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1519 while (ijb_isspace(*q))
1523 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1524 string_move(p+1, q);
1529 log_error(LOG_LEVEL_HEADER,
1530 "Converting tab to space in '%s'", header);
1535 char *end_of_token = strstr(p+1, "\"");
1537 if (NULL != end_of_token)
1539 /* Don't mess with quoted text. */
1544 log_error(LOG_LEVEL_HEADER,
1545 "Ignoring single quote in '%s'", header);
1551 p = strchr(header, ':');
1552 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1555 * There's still space before the colon.
1558 string_move(p-1, p);
1563 /*********************************************************************
1565 * Function : get_header
1567 * Description : This (odd) routine will parse the csp->iob
1568 * to get the next complete header.
1571 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1573 * Returns : Any one of the following:
1575 * 1) a pointer to a dynamically allocated string that contains a header line
1576 * 2) NULL indicating that the end of the header was reached
1577 * 3) "" indicating that the end of the iob was reached before finding
1578 * a complete header line.
1580 *********************************************************************/
1581 char *get_header(struct iob *iob)
1585 header = get_header_line(iob);
1587 if ((header == NULL) || (*header == '\0'))
1590 * No complete header read yet, tell the client.
1595 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1598 * Header spans multiple lines, append the next one.
1600 char *continued_header;
1602 continued_header = get_header_line(iob);
1603 if ((continued_header == NULL) || (*continued_header == '\0'))
1606 * No complete header read yet, return what we got.
1607 * XXX: Should "unread" header instead.
1609 log_error(LOG_LEVEL_INFO,
1610 "Failed to read a multi-line header properly: '%s'",
1615 if (JB_ERR_OK != string_join(&header, continued_header))
1617 log_error(LOG_LEVEL_FATAL,
1618 "Out of memory while appending multiple headers.");
1622 /* XXX: remove before next stable release. */
1623 log_error(LOG_LEVEL_HEADER,
1624 "Merged multiple header lines to: '%s'",
1629 normalize_lws(header);
1636 /*********************************************************************
1638 * Function : get_header_line
1640 * Description : This (odd) routine will parse the csp->iob
1641 * to get the next header line.
1644 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1646 * Returns : Any one of the following:
1648 * 1) a pointer to a dynamically allocated string that contains a header line
1649 * 2) NULL indicating that the end of the header was reached
1650 * 3) "" indicating that the end of the iob was reached before finding
1651 * a complete header line.
1653 *********************************************************************/
1654 static char *get_header_line(struct iob *iob)
1658 if ((iob->cur == NULL)
1659 || ((p = strchr(iob->cur, '\n')) == NULL))
1661 return(""); /* couldn't find a complete header */
1666 ret = strdup(iob->cur);
1669 /* FIXME No way to handle error properly */
1670 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1675 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1677 /* is this a blank line (i.e. the end of the header) ? */
1689 /*********************************************************************
1691 * Function : get_header_value
1693 * Description : Get the value of a given header from a chained list
1694 * of header lines or return NULL if no such header is
1695 * present in the list.
1698 * 1 : header_list = pointer to list
1699 * 2 : header_name = string with name of header to look for.
1700 * Trailing colon required, capitalization
1703 * Returns : NULL if not found, else value of header
1705 *********************************************************************/
1706 char *get_header_value(const struct list *header_list, const char *header_name)
1708 struct list_entry *cur_entry;
1712 assert(header_list);
1713 assert(header_name);
1714 length = strlen(header_name);
1716 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1720 if (!strncmpic(cur_entry->str, header_name, length))
1723 * Found: return pointer to start of value
1725 ret = (char *) (cur_entry->str + length);
1726 while (*ret && ijb_isspace(*ret)) ret++;
1740 /*********************************************************************
1742 * Function : scan_headers
1744 * Description : Scans headers, applies tags and updates action bits.
1747 * 1 : csp = Current client state (buffers, headers, etc...)
1749 * Returns : JB_ERR_OK
1751 *********************************************************************/
1752 static jb_err scan_headers(struct client_state *csp)
1754 struct list_entry *h; /* Header */
1755 jb_err err = JB_ERR_OK;
1757 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1759 /* Header crunch()ed in previous run? -> ignore */
1760 if (h->str == NULL) continue;
1761 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1762 err = header_tagger(csp, h->str);
1769 /*********************************************************************
1773 * Description : add, delete or modify lines in the HTTP header streams.
1774 * On entry, it receives a linked list of headers space
1775 * that was allocated dynamically (both the list nodes
1776 * and the header contents).
1778 * As a side effect it frees the space used by the original
1782 * 1 : csp = Current client state (buffers, headers, etc...)
1783 * 2 : filter_server_headers = Boolean to switch between
1784 * server and header filtering.
1786 * Returns : JB_ERR_OK in case off success, or
1787 * JB_ERR_MEMORY on out-of-memory error.
1789 *********************************************************************/
1790 jb_err sed(struct client_state *csp, int filter_server_headers)
1792 /* XXX: use more descriptive names. */
1793 struct list_entry *p;
1794 const struct parsers *v;
1795 const add_header_func_ptr *f;
1796 jb_err err = JB_ERR_OK;
1798 if (filter_server_headers)
1800 v = server_patterns;
1801 f = add_server_headers;
1805 v = client_patterns;
1806 f = add_client_headers;
1811 while ((err == JB_ERR_OK) && (v->str != NULL))
1813 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1815 /* Header crunch()ed in previous run? -> ignore */
1816 if (p->str == NULL) continue;
1818 /* Does the current parser handle this header? */
1819 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1820 (v->len == CHECK_EVERY_HEADER_REMAINING))
1822 err = v->parser(csp, &(p->str));
1828 /* place additional headers on the csp->headers list */
1829 while ((err == JB_ERR_OK) && (*f))
1839 /*********************************************************************
1841 * Function : update_server_headers
1843 * Description : Updates server headers after the body has been modified.
1846 * 1 : csp = Current client state (buffers, headers, etc...)
1848 * Returns : JB_ERR_OK in case off success, or
1849 * JB_ERR_MEMORY on out-of-memory error.
1851 *********************************************************************/
1852 jb_err update_server_headers(struct client_state *csp)
1854 jb_err err = JB_ERR_OK;
1856 static const struct parsers server_patterns_light[] = {
1857 { "Content-Length:", 15, server_content_length },
1858 { "Transfer-Encoding:", 18, server_transfer_coding },
1860 { "Content-Encoding:", 17, server_content_encoding },
1861 #endif /* def FEATURE_ZLIB */
1865 if (strncmpic(csp->http->cmd, "HEAD", 4))
1867 const struct parsers *v;
1868 struct list_entry *p;
1870 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1872 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1874 /* Header crunch()ed in previous run? -> ignore */
1875 if (p->str == NULL) continue;
1877 /* Does the current parser handle this header? */
1878 if (strncmpic(p->str, v->str, v->len) == 0)
1880 err = v->parser(csp, (char **)&(p->str));
1890 /*********************************************************************
1892 * Function : header_tagger
1894 * Description : Executes all text substitutions from applying
1895 * tag actions and saves the result as tag.
1897 * XXX: Shares enough code with filter_header() and
1898 * pcrs_filter_response() to warrant some helper functions.
1901 * 1 : csp = Current client state (buffers, headers, etc...)
1902 * 2 : header = Header that is used as tagger input
1904 * Returns : JB_ERR_OK on success and always succeeds
1906 *********************************************************************/
1907 static jb_err header_tagger(struct client_state *csp, char *header)
1909 int wanted_filter_type;
1910 int multi_action_index;
1914 struct file_list *fl;
1915 struct re_filterfile_spec *b;
1916 struct list_entry *tag_name;
1918 int found_filters = 0;
1919 const size_t header_length = strlen(header);
1921 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1923 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1924 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1928 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1929 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1932 /* Check if there are any filters */
1933 for (i = 0; i < MAX_AF_FILES; i++)
1946 if (0 == found_filters)
1948 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1949 "tagging enabled, but no taggers available.");
1953 for (i = 0; i < MAX_AF_FILES; i++)
1956 if ((NULL == fl) || (NULL == fl->f))
1959 * Either there are no filter files
1960 * left, or this filter file just
1961 * contains no valid filters.
1963 * Continue to be sure we don't miss
1964 * valid filter files that are chained
1965 * after empty or invalid ones.
1970 /* For all filters, */
1971 for (b = fl->f; b; b = b->next)
1973 if (b->type != wanted_filter_type)
1975 /* skip the ones we don't care about, */
1978 /* leaving only taggers that could apply, of which we use the ones, */
1979 for (tag_name = csp->action->multi[multi_action_index]->first;
1980 NULL != tag_name; tag_name = tag_name->next)
1982 /* that do apply, and */
1983 if (strcmp(b->name, tag_name->str) == 0)
1985 char *modified_tag = NULL;
1987 size_t size = header_length;
1988 pcrs_job *joblist = b->joblist;
1990 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1992 if (NULL == joblist)
1994 log_error(LOG_LEVEL_RE_FILTER,
1995 "Tagger %s has empty joblist. Nothing to do.", b->name);
1999 /* execute their pcrs_joblist on the header. */
2000 for (job = joblist; NULL != job; job = job->next)
2002 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2006 /* Success, continue with the modified version. */
2015 /* Tagger doesn't match */
2018 /* Regex failure, log it but continue anyway. */
2019 log_error(LOG_LEVEL_ERROR,
2020 "Problems with tagger \'%s\' and header \'%s\': %s",
2021 b->name, *header, pcrs_strerror(hits));
2023 freez(modified_tag);
2027 if (b->dynamic) pcrs_free_joblist(joblist);
2029 /* If this tagger matched */
2035 * There is to technical limitation which makes
2036 * it impossible to use empty tags, but I assume
2037 * no one would do it intentionally.
2040 log_error(LOG_LEVEL_INFO,
2041 "Tagger \'%s\' created an empty tag. Ignored.",
2046 if (!list_contains_item(csp->tags, tag))
2048 if (JB_ERR_OK != enlist(csp->tags, tag))
2050 log_error(LOG_LEVEL_ERROR,
2051 "Insufficient memory to add tag \'%s\', "
2052 "based on tagger \'%s\' and header \'%s\'",
2053 tag, b->name, *header);
2057 char *action_message;
2059 * update the action bits right away, to make
2060 * tagging based on tags set by earlier taggers
2061 * of the same kind possible.
2063 if (update_action_bits_for_tag(csp, tag))
2065 action_message = "Action bits updated accordingly.";
2069 action_message = "No action bits update necessary.";
2072 log_error(LOG_LEVEL_HEADER,
2073 "Tagger \'%s\' added tag \'%s\'. %s",
2074 b->name, tag, action_message);
2079 /* XXX: Is this log-worthy? */
2080 log_error(LOG_LEVEL_HEADER,
2081 "Tagger \'%s\' didn't add tag \'%s\'. "
2082 "Tag already present", b->name, tag);
2085 } /* if the tagger matched */
2086 } /* if the tagger applies */
2087 } /* for every tagger that could apply */
2088 } /* for all filters */
2089 } /* for all filter files */
2094 /* here begins the family of parser functions that reformat header lines */
2096 /*********************************************************************
2098 * Function : filter_header
2100 * Description : Executes all text substitutions from all applying
2101 * +(server|client)-header-filter actions on the header.
2102 * Most of the code was copied from pcrs_filter_response,
2103 * including the rather short variable names
2106 * 1 : csp = Current client state (buffers, headers, etc...)
2107 * 2 : header = On input, pointer to header to modify.
2108 * On output, pointer to the modified header, or NULL
2109 * to remove the header. This function frees the
2110 * original string if necessary.
2112 * Returns : JB_ERR_OK on success and always succeeds
2114 *********************************************************************/
2115 static jb_err filter_header(struct client_state *csp, char **header)
2119 size_t size = strlen(*header);
2121 char *newheader = NULL;
2124 struct file_list *fl;
2125 struct re_filterfile_spec *b;
2126 struct list_entry *filtername;
2128 int i, found_filters = 0;
2129 int wanted_filter_type;
2130 int multi_action_index;
2132 if (csp->flags & CSP_FLAG_NO_FILTERING)
2137 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2139 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2140 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2144 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2145 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2149 * Need to check the set of re_filterfiles...
2151 for (i = 0; i < MAX_AF_FILES; i++)
2164 if (0 == found_filters)
2166 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2167 "header filtering enabled, but no matching filters available.");
2171 for (i = 0; i < MAX_AF_FILES; i++)
2174 if ((NULL == fl) || (NULL == fl->f))
2177 * Either there are no filter files
2178 * left, or this filter file just
2179 * contains no valid filters.
2181 * Continue to be sure we don't miss
2182 * valid filter files that are chained
2183 * after empty or invalid ones.
2188 * For all applying +filter actions, look if a filter by that
2189 * name exists and if yes, execute its pcrs_joblist on the
2192 for (b = fl->f; b; b = b->next)
2194 if (b->type != wanted_filter_type)
2196 /* Skip other filter types */
2200 for (filtername = csp->action->multi[multi_action_index]->first;
2201 filtername ; filtername = filtername->next)
2203 if (strcmp(b->name, filtername->str) == 0)
2205 int current_hits = 0;
2206 pcrs_job *joblist = b->joblist;
2208 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2210 if (NULL == joblist)
2212 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2216 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2217 *header, size, b->name);
2219 /* Apply all jobs from the joblist */
2220 for (job = joblist; NULL != job; job = job->next)
2222 matches = pcrs_execute(job, *header, size, &newheader, &size);
2225 current_hits += matches;
2226 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2228 *header = newheader;
2230 else if ( 0 == matches )
2232 /* Filter doesn't change header */
2238 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2239 *header, b->name, pcrs_strerror(matches));
2240 if (newheader != NULL)
2242 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2248 if (b->dynamic) pcrs_free_joblist(joblist);
2250 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2251 hits += current_hits;
2258 * Additionally checking for hits is important because if
2259 * the continue hack is triggered, server headers can
2260 * arrive empty to separate multiple heads from each other.
2262 if ((0 == size) && hits)
2264 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2272 /*********************************************************************
2274 * Function : connection
2276 * Description : Makes sure that the value of the Connection: header
2277 * is "close" and signals connection_close_adder
2281 * 1 : csp = Current client state (buffers, headers, etc...)
2282 * 2 : header = On input, pointer to header to modify.
2283 * On output, pointer to the modified header, or NULL
2284 * to remove the header. This function frees the
2285 * original string if necessary.
2287 * Returns : JB_ERR_OK on success, or
2288 * JB_ERR_MEMORY on out-of-memory error.
2290 *********************************************************************/
2291 static jb_err connection(struct client_state *csp, char **header)
2293 char *old_header = *header;
2295 /* Do we have a 'Connection: close' header? */
2296 if (strcmpic(*header, "Connection: close"))
2298 /* No, create one */
2299 *header = strdup("Connection: close");
2302 return JB_ERR_MEMORY;
2304 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2308 /* Signal connection_close_adder() to return early. */
2309 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2311 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2315 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2322 /*********************************************************************
2324 * Function : crumble
2326 * Description : This is called if a header matches a pattern to "crunch"
2329 * 1 : csp = Current client state (buffers, headers, etc...)
2330 * 2 : header = On input, pointer to header to modify.
2331 * On output, pointer to the modified header, or NULL
2332 * to remove the header. This function frees the
2333 * original string if necessary.
2335 * Returns : JB_ERR_OK on success, or
2336 * JB_ERR_MEMORY on out-of-memory error.
2338 *********************************************************************/
2339 static jb_err crumble(struct client_state *csp, char **header)
2341 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2347 /*********************************************************************
2349 * Function : crunch_server_header
2351 * Description : Crunch server header if it matches a string supplied by the
2352 * user. Called from `sed'.
2355 * 1 : csp = Current client state (buffers, headers, etc...)
2356 * 2 : header = On input, pointer to header to modify.
2357 * On output, pointer to the modified header, or NULL
2358 * to remove the header. This function frees the
2359 * original string if necessary.
2361 * Returns : JB_ERR_OK on success and always succeeds
2363 *********************************************************************/
2364 static jb_err crunch_server_header(struct client_state *csp, char **header)
2366 const char *crunch_pattern;
2368 /* Do we feel like crunching? */
2369 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2371 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2373 /* Is the current header the lucky one? */
2374 if (strstr(*header, crunch_pattern))
2376 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2385 /*********************************************************************
2387 * Function : server_content_type
2389 * Description : Set the content-type for filterable types (text/.*,
2390 * .*xml.*, javascript and image/gif) unless filtering has been
2391 * forbidden (CT_TABOO) while parsing earlier headers.
2392 * NOTE: Since text/plain is commonly used by web servers
2393 * for files whose correct type is unknown, we don't
2394 * set CT_TEXT for it.
2397 * 1 : csp = Current client state (buffers, headers, etc...)
2398 * 2 : header = On input, pointer to header to modify.
2399 * On output, pointer to the modified header, or NULL
2400 * to remove the header. This function frees the
2401 * original string if necessary.
2403 * Returns : JB_ERR_OK on success, or
2404 * JB_ERR_MEMORY on out-of-memory error.
2406 *********************************************************************/
2407 static jb_err server_content_type(struct client_state *csp, char **header)
2409 /* Remove header if it isn't the first Content-Type header */
2410 if ((csp->content_type & CT_DECLARED))
2413 * Another, slightly slower, way to see if
2414 * we already parsed another Content-Type header.
2416 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2418 log_error(LOG_LEVEL_ERROR,
2419 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2427 * Signal that the Content-Type has been set.
2429 csp->content_type |= CT_DECLARED;
2431 if (!(csp->content_type & CT_TABOO))
2434 * XXX: The assumption that text/plain is a sign of
2435 * binary data seems to be somewhat unreasonable nowadays
2436 * and should be dropped after 3.0.8 is out.
2438 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2439 || strstr(*header, "xml")
2440 || strstr(*header, "application/x-javascript"))
2442 csp->content_type |= CT_TEXT;
2444 else if (strstr(*header, "image/gif"))
2446 csp->content_type |= CT_GIF;
2451 * Are we messing with the content type?
2453 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2456 * Make sure the user doesn't accidently
2457 * change the content type of binary documents.
2459 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2462 *header = strdup("Content-Type: ");
2463 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2467 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2468 return JB_ERR_MEMORY;
2470 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2474 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2475 "It doesn't look like a content type that should be filtered. "
2476 "Enable force-text-mode if you know what you're doing.", *header);
2484 /*********************************************************************
2486 * Function : server_transfer_coding
2488 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2489 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2490 * - Remove header if body was chunked but has been
2491 * de-chunked for filtering.
2494 * 1 : csp = Current client state (buffers, headers, etc...)
2495 * 2 : header = On input, pointer to header to modify.
2496 * On output, pointer to the modified header, or NULL
2497 * to remove the header. This function frees the
2498 * original string if necessary.
2500 * Returns : JB_ERR_OK on success, or
2501 * JB_ERR_MEMORY on out-of-memory error.
2503 *********************************************************************/
2504 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2507 * Turn off pcrs and gif filtering if body compressed
2509 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2513 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2515 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2516 csp->http->cmd, *header);
2517 #endif /* def FEATURE_ZLIB */
2518 csp->content_type = CT_TABOO;
2522 * Raise flag if body chunked
2524 if (strstr(*header, "chunked"))
2526 csp->flags |= CSP_FLAG_CHUNKED;
2529 * If the body was modified, it has been de-chunked first
2530 * and the header must be removed.
2532 * FIXME: If there is more than one transfer encoding,
2533 * only the "chunked" part should be removed here.
2535 if (csp->flags & CSP_FLAG_MODIFIED)
2537 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2546 /*********************************************************************
2548 * Function : server_content_encoding
2550 * Description : This function is run twice for each request,
2551 * unless FEATURE_ZLIB and filtering are disabled.
2553 * The first run is used to check if the content
2554 * is compressed, if FEATURE_ZLIB is disabled
2555 * filtering is then disabled as well, if FEATURE_ZLIB
2556 * is enabled the content is marked for decompression.
2558 * The second run is used to remove the Content-Encoding
2559 * header if the decompression was successful.
2562 * 1 : csp = Current client state (buffers, headers, etc...)
2563 * 2 : header = On input, pointer to header to modify.
2564 * On output, pointer to the modified header, or NULL
2565 * to remove the header. This function frees the
2566 * original string if necessary.
2568 * Returns : JB_ERR_OK on success, or
2569 * JB_ERR_MEMORY on out-of-memory error.
2571 *********************************************************************/
2572 static jb_err server_content_encoding(struct client_state *csp, char **header)
2575 if ((csp->flags & CSP_FLAG_MODIFIED)
2576 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2579 * We successfully decompressed the content,
2580 * and have to clean the header now, so the
2581 * client no longer expects compressed data..
2583 * XXX: There is a difference between cleaning
2584 * and removing it completely.
2586 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2589 else if (strstr(*header, "gzip"))
2591 /* Mark for gzip decompression */
2592 csp->content_type |= CT_GZIP;
2594 else if (strstr(*header, "deflate"))
2596 /* Mark for zlib decompression */
2597 csp->content_type |= CT_DEFLATE;
2599 else if (strstr(*header, "compress"))
2602 * We can't decompress this; therefore we can't filter
2605 csp->content_type |= CT_TABOO;
2607 #else /* !defined(FEATURE_ZLIB) */
2608 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2611 * Body is compressed, turn off pcrs and gif filtering.
2613 csp->content_type |= CT_TABOO;
2616 * Log a warning if the user expects the content to be filtered.
2618 if ((csp->rlist != NULL) &&
2619 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2621 log_error(LOG_LEVEL_INFO,
2622 "Compressed content detected, content filtering disabled. "
2623 "Consider recompiling Privoxy with zlib support or "
2624 "enable the prevent-compression action.");
2627 #endif /* defined(FEATURE_ZLIB) */
2634 /*********************************************************************
2636 * Function : server_content_length
2638 * Description : Adjust Content-Length header if we modified
2642 * 1 : csp = Current client state (buffers, headers, etc...)
2643 * 2 : header = On input, pointer to header to modify.
2644 * On output, pointer to the modified header, or NULL
2645 * to remove the header. This function frees the
2646 * original string if necessary.
2648 * Returns : JB_ERR_OK on success, or
2649 * JB_ERR_MEMORY on out-of-memory error.
2651 *********************************************************************/
2652 static jb_err server_content_length(struct client_state *csp, char **header)
2654 const size_t max_header_length = 80;
2656 /* Regenerate header if the content was modified. */
2657 if (csp->flags & CSP_FLAG_MODIFIED)
2660 *header = (char *) zalloc(max_header_length);
2661 if (*header == NULL)
2663 return JB_ERR_MEMORY;
2666 snprintf(*header, max_header_length, "Content-Length: %d",
2667 (int)csp->content_length);
2668 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2669 (int)csp->content_length);
2676 /*********************************************************************
2678 * Function : server_content_md5
2680 * Description : Crumble any Content-MD5 headers if the document was
2681 * modified. FIXME: Should we re-compute instead?
2684 * 1 : csp = Current client state (buffers, headers, etc...)
2685 * 2 : header = On input, pointer to header to modify.
2686 * On output, pointer to the modified header, or NULL
2687 * to remove the header. This function frees the
2688 * original string if necessary.
2690 * Returns : JB_ERR_OK on success, or
2691 * JB_ERR_MEMORY on out-of-memory error.
2693 *********************************************************************/
2694 static jb_err server_content_md5(struct client_state *csp, char **header)
2696 if (csp->flags & CSP_FLAG_MODIFIED)
2698 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2706 /*********************************************************************
2708 * Function : server_content_disposition
2710 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2711 * Called from `sed'.
2714 * 1 : csp = Current client state (buffers, headers, etc...)
2715 * 2 : header = On input, pointer to header to modify.
2716 * On output, pointer to the modified header, or NULL
2717 * to remove the header. This function frees the
2718 * original string if necessary.
2720 * Returns : JB_ERR_OK on success, or
2721 * JB_ERR_MEMORY on out-of-memory error.
2723 *********************************************************************/
2724 static jb_err server_content_disposition(struct client_state *csp, char **header)
2729 * Are we messing with the Content-Disposition header?
2731 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2737 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2739 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2742 * Blocking content-disposition header
2744 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2751 * Replacing Content-Disposition header
2754 *header = strdup("Content-Disposition: ");
2755 string_append(header, newval);
2757 if (*header != NULL)
2759 log_error(LOG_LEVEL_HEADER,
2760 "Content-Disposition header crunched and replaced with: %s", *header);
2763 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2767 /*********************************************************************
2769 * Function : server_last_modified
2771 * Description : Changes Last-Modified header to the actual date
2772 * to help hide-if-modified-since.
2773 * Called from `sed'.
2776 * 1 : csp = Current client state (buffers, headers, etc...)
2777 * 2 : header = On input, pointer to header to modify.
2778 * On output, pointer to the modified header, or NULL
2779 * to remove the header. This function frees the
2780 * original string if necessary.
2782 * Returns : JB_ERR_OK on success, or
2783 * JB_ERR_MEMORY on out-of-memory error.
2785 *********************************************************************/
2786 static jb_err server_last_modified(struct client_state *csp, char **header)
2789 char buf[BUFFER_SIZE];
2792 #ifdef HAVE_GMTIME_R
2795 struct tm *timeptr = NULL;
2796 time_t now, last_modified;
2798 long int days, hours, minutes, seconds;
2801 * Are we messing with the Last-Modified header?
2803 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2809 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2811 if (0 == strcmpic(newval, "block") )
2814 * Blocking Last-Modified header. Useless but why not.
2816 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2820 else if (0 == strcmpic(newval, "reset-to-request-time"))
2823 * Setting Last-Modified Header to now.
2825 get_http_time(0, buf, sizeof(buf));
2827 *header = strdup("Last-Modified: ");
2828 string_append(header, buf);
2830 if (*header == NULL)
2832 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2836 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2839 else if (0 == strcmpic(newval, "randomize"))
2841 const char *header_time = *header + sizeof("Last-Modified:");
2843 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2845 #ifdef HAVE_GMTIME_R
2846 timeptr = gmtime_r(&now, &gmt);
2847 #elif FEATURE_PTHREAD
2848 pthread_mutex_lock(&gmtime_mutex);
2849 timeptr = gmtime(&now);
2850 pthread_mutex_unlock(&gmtime_mutex);
2852 timeptr = gmtime(&now);
2854 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2856 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2861 rtime = (long int)difftime(now, last_modified);
2870 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2872 rtime = pick_from_range(rtime);
2873 if (negative) rtime *= -1;
2874 last_modified += rtime;
2875 #ifdef HAVE_GMTIME_R
2876 timeptr = gmtime_r(&last_modified, &gmt);
2877 #elif FEATURE_PTHREAD
2878 pthread_mutex_lock(&gmtime_mutex);
2879 timeptr = gmtime(&last_modified);
2880 pthread_mutex_unlock(&gmtime_mutex);
2882 timeptr = gmtime(&last_modified);
2884 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2886 *header = strdup("Last-Modified: ");
2887 string_append(header, newheader);
2889 if (*header == NULL)
2891 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2892 return JB_ERR_MEMORY;
2895 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2897 days = rtime / (3600 * 24);
2898 hours = rtime / 3600 % 24;
2899 minutes = rtime / 60 % 60;
2900 seconds = rtime % 60;
2902 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2903 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2904 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2909 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2918 /*********************************************************************
2920 * Function : client_accept_encoding
2922 * Description : Rewrite the client's Accept-Encoding header so that
2923 * if doesn't allow compression, if the action applies.
2924 * Note: For HTTP/1.0 the absence of the header is enough.
2927 * 1 : csp = Current client state (buffers, headers, etc...)
2928 * 2 : header = On input, pointer to header to modify.
2929 * On output, pointer to the modified header, or NULL
2930 * to remove the header. This function frees the
2931 * original string if necessary.
2933 * Returns : JB_ERR_OK on success, or
2934 * JB_ERR_MEMORY on out-of-memory error.
2936 *********************************************************************/
2937 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2939 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2941 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2945 /* Temporarily disable the correct behaviour to
2946 * work around a PHP bug.
2948 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2950 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2951 * if (*header == NULL)
2953 * return JB_ERR_MEMORY;
2964 /*********************************************************************
2966 * Function : client_te
2968 * Description : Rewrite the client's TE header so that
2969 * if doesn't allow compression, if the action applies.
2972 * 1 : csp = Current client state (buffers, headers, etc...)
2973 * 2 : header = On input, pointer to header to modify.
2974 * On output, pointer to the modified header, or NULL
2975 * to remove the header. This function frees the
2976 * original string if necessary.
2978 * Returns : JB_ERR_OK on success, or
2979 * JB_ERR_MEMORY on out-of-memory error.
2981 *********************************************************************/
2982 static jb_err client_te(struct client_state *csp, char **header)
2984 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2987 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2994 /*********************************************************************
2996 * Function : client_referrer
2998 * Description : Handle the "referer" config setting properly.
2999 * Called from `sed'.
3002 * 1 : csp = Current client state (buffers, headers, etc...)
3003 * 2 : header = On input, pointer to header to modify.
3004 * On output, pointer to the modified header, or NULL
3005 * to remove the header. This function frees the
3006 * original string if necessary.
3008 * Returns : JB_ERR_OK on success, or
3009 * JB_ERR_MEMORY on out-of-memory error.
3011 *********************************************************************/
3012 static jb_err client_referrer(struct client_state *csp, char **header)
3014 const char *parameter;
3015 /* booleans for parameters we have to check multiple times */
3016 int parameter_conditional_block;
3017 int parameter_conditional_forge;
3019 #ifdef FEATURE_FORCE_LOAD
3021 * Since the referrer can include the prefix even
3022 * if the request itself is non-forced, we must
3023 * clean it unconditionally.
3025 * XXX: strclean is too broad
3027 strclean(*header, FORCE_PREFIX);
3028 #endif /* def FEATURE_FORCE_LOAD */
3030 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3032 /* Nothing left to do */
3036 parameter = csp->action->string[ACTION_STRING_REFERER];
3037 assert(parameter != NULL);
3038 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3039 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3041 if (!parameter_conditional_block && !parameter_conditional_forge)
3044 * As conditional-block and conditional-forge are the only
3045 * parameters that rely on the original referrer, we can
3046 * remove it now for all the others.
3051 if (0 == strcmpic(parameter, "block"))
3053 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3056 else if (parameter_conditional_block || parameter_conditional_forge)
3058 return handle_conditional_hide_referrer_parameter(header,
3059 csp->http->hostport, parameter_conditional_block);
3061 else if (0 == strcmpic(parameter, "forge"))
3063 return create_forged_referrer(header, csp->http->hostport);
3067 /* interpret parameter as user-supplied referer to fake */
3068 return create_fake_referrer(header, parameter);
3073 /*********************************************************************
3075 * Function : client_accept_language
3077 * Description : Handle the "Accept-Language" config setting properly.
3078 * Called from `sed'.
3081 * 1 : csp = Current client state (buffers, headers, etc...)
3082 * 2 : header = On input, pointer to header to modify.
3083 * On output, pointer to the modified header, or NULL
3084 * to remove the header. This function frees the
3085 * original string if necessary.
3087 * Returns : JB_ERR_OK on success, or
3088 * JB_ERR_MEMORY on out-of-memory error.
3090 *********************************************************************/
3091 static jb_err client_accept_language(struct client_state *csp, char **header)
3096 * Are we messing with the Accept-Language?
3098 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3100 /*I don't think so*/
3104 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3106 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3109 * Blocking Accept-Language header
3111 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3118 * Replacing Accept-Language header
3121 *header = strdup("Accept-Language: ");
3122 string_append(header, newval);
3124 if (*header == NULL)
3126 log_error(LOG_LEVEL_ERROR,
3127 "Insufficent memory. Accept-Language header crunched without replacement.");
3131 log_error(LOG_LEVEL_HEADER,
3132 "Accept-Language header crunched and replaced with: %s", *header);
3135 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3139 /*********************************************************************
3141 * Function : crunch_client_header
3143 * Description : Crunch client header if it matches a string supplied by the
3144 * user. Called from `sed'.
3147 * 1 : csp = Current client state (buffers, headers, etc...)
3148 * 2 : header = On input, pointer to header to modify.
3149 * On output, pointer to the modified header, or NULL
3150 * to remove the header. This function frees the
3151 * original string if necessary.
3153 * Returns : JB_ERR_OK on success and always succeeds
3155 *********************************************************************/
3156 static jb_err crunch_client_header(struct client_state *csp, char **header)
3158 const char *crunch_pattern;
3160 /* Do we feel like crunching? */
3161 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3163 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3165 /* Is the current header the lucky one? */
3166 if (strstr(*header, crunch_pattern))
3168 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3176 /*********************************************************************
3178 * Function : client_uagent
3180 * Description : Handle the "user-agent" config setting properly
3181 * and remember its original value to enable browser
3182 * bug workarounds. Called from `sed'.
3185 * 1 : csp = Current client state (buffers, headers, etc...)
3186 * 2 : header = On input, pointer to header to modify.
3187 * On output, pointer to the modified header, or NULL
3188 * to remove the header. This function frees the
3189 * original string if necessary.
3191 * Returns : JB_ERR_OK on success, or
3192 * JB_ERR_MEMORY on out-of-memory error.
3194 *********************************************************************/
3195 static jb_err client_uagent(struct client_state *csp, char **header)
3199 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3204 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3211 *header = strdup("User-Agent: ");
3212 string_append(header, newval);
3214 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3216 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3220 /*********************************************************************
3222 * Function : client_ua
3224 * Description : Handle "ua-" headers properly. Called from `sed'.
3227 * 1 : csp = Current client state (buffers, headers, etc...)
3228 * 2 : header = On input, pointer to header to modify.
3229 * On output, pointer to the modified header, or NULL
3230 * to remove the header. This function frees the
3231 * original string if necessary.
3233 * Returns : JB_ERR_OK on success, or
3234 * JB_ERR_MEMORY on out-of-memory error.
3236 *********************************************************************/
3237 static jb_err client_ua(struct client_state *csp, char **header)
3239 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3241 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3249 /*********************************************************************
3251 * Function : client_from
3253 * Description : Handle the "from" config setting properly.
3254 * Called from `sed'.
3257 * 1 : csp = Current client state (buffers, headers, etc...)
3258 * 2 : header = On input, pointer to header to modify.
3259 * On output, pointer to the modified header, or NULL
3260 * to remove the header. This function frees the
3261 * original string if necessary.
3263 * Returns : JB_ERR_OK on success, or
3264 * JB_ERR_MEMORY on out-of-memory error.
3266 *********************************************************************/
3267 static jb_err client_from(struct client_state *csp, char **header)
3271 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3278 newval = csp->action->string[ACTION_STRING_FROM];
3281 * Are we blocking the e-mail address?
3283 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3285 log_error(LOG_LEVEL_HEADER, "crunched From!");
3289 log_error(LOG_LEVEL_HEADER, " modified");
3291 *header = strdup("From: ");
3292 string_append(header, newval);
3294 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3298 /*********************************************************************
3300 * Function : client_send_cookie
3302 * Description : Crunches the "cookie" header if necessary.
3303 * Called from `sed'.
3305 * XXX: Stupid name, doesn't send squat.
3308 * 1 : csp = Current client state (buffers, headers, etc...)
3309 * 2 : header = On input, pointer to header to modify.
3310 * On output, pointer to the modified header, or NULL
3311 * to remove the header. This function frees the
3312 * original string if necessary.
3314 * Returns : JB_ERR_OK on success, or
3315 * JB_ERR_MEMORY on out-of-memory error.
3317 *********************************************************************/
3318 static jb_err client_send_cookie(struct client_state *csp, char **header)
3320 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3322 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3330 /*********************************************************************
3332 * Function : client_x_forwarded
3334 * Description : Handle the "x-forwarded-for" config setting properly,
3335 * also used in the add_client_headers list. Called from `sed'.
3338 * 1 : csp = Current client state (buffers, headers, etc...)
3339 * 2 : header = On input, pointer to header to modify.
3340 * On output, pointer to the modified header, or NULL
3341 * to remove the header. This function frees the
3342 * original string if necessary.
3344 * Returns : JB_ERR_OK on success, or
3345 * JB_ERR_MEMORY on out-of-memory error.
3347 *********************************************************************/
3348 jb_err client_x_forwarded(struct client_state *csp, char **header)
3350 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3353 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3360 /*********************************************************************
3362 * Function : client_max_forwards
3364 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3365 * from the value of the Max-Forwards header field.
3368 * 1 : csp = Current client state (buffers, headers, etc...)
3369 * 2 : header = On input, pointer to header to modify.
3370 * On output, pointer to the modified header, or NULL
3371 * to remove the header. This function frees the
3372 * original string if necessary.
3374 * Returns : JB_ERR_OK on success, or
3375 * JB_ERR_MEMORY on out-of-memory error.
3377 *********************************************************************/
3378 static jb_err client_max_forwards(struct client_state *csp, char **header)
3382 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3383 (0 == strcmpic(csp->http->gpc, "options")))
3385 assert(*(*header+12) == ':');
3386 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3388 if (max_forwards > 0)
3390 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3391 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3392 csp->http->gpc, max_forwards);
3394 else if (max_forwards < 0)
3396 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3402 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3411 /*********************************************************************
3413 * Function : client_host
3415 * Description : If the request URI did not contain host and
3416 * port information, parse and evaluate the Host
3419 * Also, kill ill-formed HOST: headers as sent by
3420 * Apple's iTunes software when used with a proxy.
3423 * 1 : csp = Current client state (buffers, headers, etc...)
3424 * 2 : header = On input, pointer to header to modify.
3425 * On output, pointer to the modified header, or NULL
3426 * to remove the header. This function frees the
3427 * original string if necessary.
3429 * Returns : JB_ERR_OK on success, or
3430 * JB_ERR_MEMORY on out-of-memory error.
3432 *********************************************************************/
3433 static jb_err client_host(struct client_state *csp, char **header)
3438 * If the header field name is all upper-case, chances are that it's
3439 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3440 * not a problem -- they are regenerated later.
3442 if ((*header)[1] == 'O')
3444 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3449 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3450 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3453 if (NULL == (p = strdup((*header)+6)))
3455 return JB_ERR_MEMORY;
3458 if (NULL == (q = strdup(p)))
3461 return JB_ERR_MEMORY;
3464 freez(csp->http->hostport);
3465 csp->http->hostport = p;
3466 freez(csp->http->host);
3467 csp->http->host = q;
3468 q = strchr(csp->http->host, ':');
3471 /* Terminate hostname and evaluate port string */
3473 csp->http->port = atoi(q);
3477 csp->http->port = csp->http->ssl ? 443 : 80;
3480 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3481 csp->http->hostport, csp->http->host, csp->http->port);
3484 /* Signal client_host_adder() to return right away */
3485 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3491 /*********************************************************************
3493 * Function : client_if_modified_since
3495 * Description : Remove or modify the If-Modified-Since header.
3498 * 1 : csp = Current client state (buffers, headers, etc...)
3499 * 2 : header = On input, pointer to header to modify.
3500 * On output, pointer to the modified header, or NULL
3501 * to remove the header. This function frees the
3502 * original string if necessary.
3504 * Returns : JB_ERR_OK on success, or
3505 * JB_ERR_MEMORY on out-of-memory error.
3507 *********************************************************************/
3508 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3511 #ifdef HAVE_GMTIME_R
3514 struct tm *timeptr = NULL;
3518 long int hours, minutes, seconds;
3522 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3525 * The client got an error message because of a temporary problem,
3526 * the problem is gone and the client now tries to revalidate our
3527 * error message on the real server. The revalidation would always
3528 * end with the transmission of the whole document and there is
3529 * no need to expose the bogus If-Modified-Since header.
3531 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3534 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3536 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3538 if ((0 == strcmpic(newval, "block")))
3540 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3543 else /* add random value */
3545 const char *header_time = *header + sizeof("If-Modified-Since:");
3547 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3549 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3554 rtime = strtol(newval, &endptr, 0);
3557 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3558 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3565 rtime = pick_from_range(rtime);
3569 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3572 tm += rtime * (negative ? -1 : 1);
3573 #ifdef HAVE_GMTIME_R
3574 timeptr = gmtime_r(&tm, &gmt);
3575 #elif FEATURE_PTHREAD
3576 pthread_mutex_lock(&gmtime_mutex);
3577 timeptr = gmtime(&tm);
3578 pthread_mutex_unlock(&gmtime_mutex);
3580 timeptr = gmtime(&tm);
3582 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3585 *header = strdup("If-Modified-Since: ");
3586 string_append(header, newheader);
3588 if (*header == NULL)
3590 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3591 return JB_ERR_MEMORY;
3594 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3596 hours = rtime / 3600;
3597 minutes = rtime / 60 % 60;
3598 seconds = rtime % 60;
3600 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3601 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3602 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3612 /*********************************************************************
3614 * Function : client_if_none_match
3616 * Description : Remove the If-None-Match header.
3619 * 1 : csp = Current client state (buffers, headers, etc...)
3620 * 2 : header = On input, pointer to header to modify.
3621 * On output, pointer to the modified header, or NULL
3622 * to remove the header. This function frees the
3623 * original string if necessary.
3625 * Returns : JB_ERR_OK on success, or
3626 * JB_ERR_MEMORY on out-of-memory error.
3628 *********************************************************************/
3629 static jb_err client_if_none_match(struct client_state *csp, char **header)
3631 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3633 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3641 /*********************************************************************
3643 * Function : client_x_filter
3645 * Description : Disables filtering if the client set "X-Filter: No".
3646 * Called from `sed'.
3649 * 1 : csp = Current client state (buffers, headers, etc...)
3650 * 2 : header = On input, pointer to header to modify.
3651 * On output, pointer to the modified header, or NULL
3652 * to remove the header. This function frees the
3653 * original string if necessary.
3655 * Returns : JB_ERR_OK on success
3657 *********************************************************************/
3658 jb_err client_x_filter(struct client_state *csp, char **header)
3660 if ( 0 == strcmpic(*header, "X-Filter: No"))
3662 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3664 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3668 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3670 log_error(LOG_LEVEL_HEADER,
3671 "force-text-mode overruled the client's request to fetch without filtering!");
3675 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3676 csp->flags |= CSP_FLAG_NO_FILTERING;
3677 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3679 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3687 /*********************************************************************
3689 * Function : client_range
3691 * Description : Removes Range, Request-Range and If-Range headers if
3692 * content filtering is enabled. If the client's version
3693 * of the document has been altered by Privoxy, the server
3694 * could interpret the range differently than the client
3695 * intended in which case the user could end up with
3696 * corrupted content.
3699 * 1 : csp = Current client state (buffers, headers, etc...)
3700 * 2 : header = On input, pointer to header to modify.
3701 * On output, pointer to the modified header, or NULL
3702 * to remove the header. This function frees the
3703 * original string if necessary.
3705 * Returns : JB_ERR_OK
3707 *********************************************************************/
3708 static jb_err client_range(struct client_state *csp, char **header)
3710 if (content_filters_enabled(csp->action))
3712 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3713 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3720 /* the following functions add headers directly to the header list */
3722 /*********************************************************************
3724 * Function : client_host_adder
3726 * Description : Adds the Host: header field if it is missing.
3727 * Called from `sed'.
3730 * 1 : csp = Current client state (buffers, headers, etc...)
3732 * Returns : JB_ERR_OK on success, or
3733 * JB_ERR_MEMORY on out-of-memory error.
3735 *********************************************************************/
3736 static jb_err client_host_adder(struct client_state *csp)
3741 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3743 /* Header already set by the client, nothing to do. */
3747 if ( !csp->http->hostport || !*(csp->http->hostport))
3749 /* XXX: When does this happen and why is it OK? */
3750 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3755 * remove 'user:pass@' from 'proto://user:pass@host'
3757 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3763 p = csp->http->hostport;
3766 /* XXX: Just add it, we already made sure that it will be unique */
3767 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3768 err = enlist_unique_header(csp->headers, "Host", p);
3775 /*********************************************************************
3777 * Function : client_accept_encoding_adder
3779 * Description : Add an Accept-Encoding header to the client's request
3780 * that disables compression if the action applies, and
3781 * the header is not already there. Called from `sed'.
3782 * Note: For HTTP/1.0, the absence of the header is enough.
3785 * 1 : csp = Current client state (buffers, headers, etc...)
3787 * Returns : JB_ERR_OK on success, or
3788 * JB_ERR_MEMORY on out-of-memory error.
3790 *********************************************************************/
3791 static jb_err client_accept_encoding_adder(struct client_state *csp)
3793 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3794 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3796 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3804 /*********************************************************************
3806 * Function : client_xtra_adder
3808 * Description : Used in the add_client_headers list. Called from `sed'.
3811 * 1 : csp = Current client state (buffers, headers, etc...)
3813 * Returns : JB_ERR_OK on success, or
3814 * JB_ERR_MEMORY on out-of-memory error.
3816 *********************************************************************/
3817 static jb_err client_xtra_adder(struct client_state *csp)
3819 struct list_entry *lst;
3822 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3823 lst ; lst = lst->next)
3825 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3826 err = enlist(csp->headers, lst->str);
3838 /*********************************************************************
3840 * Function : connection_close_adder
3842 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3843 * support. Adds a "Connection: close" header to csp->headers
3844 * unless the header was already present. Called from `sed'.
3846 * FIXME: This whole function shouldn't be neccessary!
3849 * 1 : csp = Current client state (buffers, headers, etc...)
3851 * Returns : JB_ERR_OK on success, or
3852 * JB_ERR_MEMORY on out-of-memory error.
3854 *********************************************************************/
3855 static jb_err connection_close_adder(struct client_state *csp)
3857 const unsigned int flags = csp->flags;
3860 * Return right away if
3862 * - we're parsing server headers and the server header
3863 * "Connection: close" is already set, or if
3865 * - we're parsing client headers and the client header
3866 * "Connection: close" is already set.
3868 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3869 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3870 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3871 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3876 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3878 return enlist(csp->headers, "Connection: close");
3882 /*********************************************************************
3884 * Function : server_http
3886 * Description : - Save the HTTP Status into csp->http->status
3887 * - Set CT_TABOO to prevent filtering if the answer
3888 * is a partial range (HTTP status 206)
3889 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3893 * 1 : csp = Current client state (buffers, headers, etc...)
3894 * 2 : header = On input, pointer to header to modify.
3895 * On output, pointer to the modified header, or NULL
3896 * to remove the header. This function frees the
3897 * original string if necessary.
3899 * Returns : JB_ERR_OK on success, or
3900 * JB_ERR_MEMORY on out-of-memory error.
3902 *********************************************************************/
3903 static jb_err server_http(struct client_state *csp, char **header)
3905 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3906 if (csp->http->status == 206)
3908 csp->content_type = CT_TABOO;
3911 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3913 /* XXX: Should we do a real validity check here? */
3914 if (strlen(*header) > 8)
3917 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3922 * XXX: Should we block the request or
3923 * enlist a valid status code line here?
3925 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3926 "Downgrading to HTTP/1.0 impossible.");
3934 /*********************************************************************
3936 * Function : server_set_cookie
3938 * Description : Handle the server "cookie" header properly.
3939 * Log cookie to the jar file. Then "crunch",
3940 * accept or rewrite it to a session cookie.
3941 * Called from `sed'.
3943 * TODO: Allow the user to specify a new expiration
3944 * time to cause the cookie to expire even before the
3945 * browser is closed.
3948 * 1 : csp = Current client state (buffers, headers, etc...)
3949 * 2 : header = On input, pointer to header to modify.
3950 * On output, pointer to the modified header, or NULL
3951 * to remove the header. This function frees the
3952 * original string if necessary.
3954 * Returns : JB_ERR_OK on success, or
3955 * JB_ERR_MEMORY on out-of-memory error.
3957 *********************************************************************/
3958 static jb_err server_set_cookie(struct client_state *csp, char **header)
3965 #ifdef FEATURE_COOKIE_JAR
3966 if (csp->config->jar)
3969 * Write timestamp into outbuf.
3971 * Complex because not all OSs have tm_gmtoff or
3972 * the %z field in strftime()
3974 char tempbuf[ BUFFER_SIZE ];
3976 #ifdef HAVE_LOCALTIME_R
3977 tm_now = *localtime_r(&now, &tm_now);
3978 #elif FEATURE_PTHREAD
3979 pthread_mutex_lock(&localtime_mutex);
3980 tm_now = *localtime (&now);
3981 pthread_mutex_unlock(&localtime_mutex);
3983 tm_now = *localtime (&now);
3985 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3987 /* strlen("set-cookie: ") = 12 */
3988 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3990 #endif /* def FEATURE_COOKIE_JAR */
3992 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3994 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3997 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3999 /* Flag whether or not to log a message */
4002 /* A variable to store the tag we're working on */
4005 /* Skip "Set-Cookie:" (11 characters) in header */
4006 cur_tag = *header + 11;
4008 /* skip whitespace between "Set-Cookie:" and value */
4009 while (*cur_tag && ijb_isspace(*cur_tag))
4014 /* Loop through each tag in the cookie */
4018 char *next_tag = strchr(cur_tag, ';');
4019 if (next_tag != NULL)
4021 /* Skip the ';' character itself */
4024 /* skip whitespace ";" and start of tag */
4025 while (*next_tag && ijb_isspace(*next_tag))
4032 /* "Next tag" is the end of the string */
4033 next_tag = cur_tag + strlen(cur_tag);
4037 * Check the expiration date to see
4038 * if the cookie is still valid, if yes,
4039 * rewrite it to a session cookie.
4041 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4043 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4045 /* Did we detect the date properly? */
4046 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4049 * Nope, treat it as if it was still valid.
4051 * XXX: Should we remove the whole cookie instead?
4053 log_error(LOG_LEVEL_ERROR,
4054 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4055 string_move(cur_tag, next_tag);
4061 * Yes. Check if the cookie is still valid.
4063 * If the cookie is already expired it's probably
4064 * a delete cookie and even if it isn't, the browser
4065 * will discard it anyway.
4069 * XXX: timegm() isn't available on some AmigaOS
4070 * versions and our replacement doesn't work.
4072 * Our options are to either:
4074 * - disable session-cookies-only completely if timegm
4077 * - to simply remove all expired tags, like it has
4078 * been done until Privoxy 3.0.6 and to live with
4079 * the consequence that it can cause login/logout
4080 * problems on servers that don't validate their
4081 * input properly, or
4083 * - to replace it with mktime in which
4084 * case there is a slight chance of valid cookies
4085 * passing as already expired.
4087 * This is the way it's currently done and it's not
4088 * as bad as it sounds. If the missing GMT offset is
4089 * enough to change the result of the expiration check
4090 * the cookie will be only valid for a few hours
4091 * anyway, which in many cases will be shorter
4092 * than a browser session.
4094 if (cookie_time - now < 0)
4096 log_error(LOG_LEVEL_HEADER,
4097 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4098 /* Just in case some clown sets more then one expiration date */
4104 * Still valid, delete expiration date by copying
4105 * the rest of the string over it.
4107 string_move(cur_tag, next_tag);
4109 /* That changed the header, need to issue a log message */
4113 * Note that the next tag has now been moved to *cur_tag,
4114 * so we do not need to update the cur_tag pointer.
4122 /* Move on to next cookie tag */
4129 assert(NULL != *header);
4130 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4139 #ifdef FEATURE_FORCE_LOAD
4140 /*********************************************************************
4142 * Function : strclean
4144 * Description : In-Situ-Eliminate all occurances of substring in
4148 * 1 : string = string to clean
4149 * 2 : substring = substring to eliminate
4151 * Returns : Number of eliminations
4153 *********************************************************************/
4154 int strclean(const char *string, const char *substring)
4160 len = strlen(substring);
4162 while((pos = strstr(string, substring)) != NULL)
4169 while (*p++ != '\0');
4176 #endif /* def FEATURE_FORCE_LOAD */
4179 /*********************************************************************
4181 * Function : parse_header_time
4183 * Description : Parses time formats used in HTTP header strings
4184 * to get the numerical respresentation.
4187 * 1 : header_time = HTTP header time as string.
4188 * 2 : result = storage for header_time in seconds
4190 * Returns : JB_ERR_OK if the time format was recognized, or
4191 * JB_ERR_PARSE otherwise.
4193 *********************************************************************/
4194 static jb_err parse_header_time(const char *header_time, time_t *result)
4199 * Zero out gmt to prevent time zone offsets.
4201 * While this is only necessary on some platforms
4202 * (mingw32 for example), I don't know how to
4203 * detect these automatically and doing it everywhere
4206 memset(&gmt, 0, sizeof(gmt));
4208 /* Tue, 02 Jun 2037 20:00:00 */
4209 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4210 /* Tue, 02-Jun-2037 20:00:00 */
4211 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4212 /* Tue, 02-Jun-37 20:00:00 */
4213 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4214 /* Tuesday, 02-Jun-2037 20:00:00 */
4215 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4216 /* Tuesday Jun 02 20:00:00 2037 */
4217 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4219 return JB_ERR_PARSE;
4222 *result = timegm(&gmt);
4229 /*********************************************************************
4231 * Function : get_destination_from_headers
4233 * Description : Parse the "Host:" header to get the request's destination.
4234 * Only needed if the client's request was forcefully
4235 * redirected into Privoxy.
4237 * Code mainly copied from client_host() which is currently
4238 * run too late for this purpose.
4241 * 1 : headers = List of headers (one of them hopefully being
4242 * the "Host:" header)
4243 * 2 : http = storage for the result (host, port and hostport).
4245 * Returns : JB_ERR_MEMORY in case of memory problems,
4246 * JB_ERR_PARSE if the host header couldn't be found,
4247 * JB_ERR_OK otherwise.
4249 *********************************************************************/
4250 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4256 host = get_header_value(headers, "Host:");
4260 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4261 return JB_ERR_PARSE;
4264 if (NULL == (p = strdup((host))))
4266 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4267 return JB_ERR_MEMORY;
4270 if (NULL == (q = strdup(p)))
4273 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4274 return JB_ERR_MEMORY;
4277 freez(http->hostport);
4281 q = strchr(http->host, ':');
4284 /* Terminate hostname and evaluate port string */
4286 http->port = atoi(q);
4290 http->port = http->ssl ? 443 : 80;
4293 /* Rebuild request URL */
4295 http->url = strdup(http->ssl ? "https://" : "http://");
4296 string_append(&http->url, http->hostport);
4297 string_append(&http->url, http->path);
4298 if (http->url == NULL)
4300 return JB_ERR_MEMORY;
4303 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4311 /*********************************************************************
4313 * Function : create_forged_referrer
4315 * Description : Helper for client_referrer to forge a referer as
4316 * 'http://[hostname:port/' to fool stupid
4317 * checks for in-site links
4320 * 1 : header = Pointer to header pointer
4321 * 2 : hostport = Host and optionally port as string
4323 * Returns : JB_ERR_OK in case of success, or
4324 * JB_ERR_MEMORY in case of memory problems.
4326 *********************************************************************/
4327 static jb_err create_forged_referrer(char **header, const char *hostport)
4329 assert(NULL == *header);
4331 *header = strdup("Referer: http://");
4332 string_append(header, hostport);
4333 string_append(header, "/");
4335 if (NULL == *header)
4337 return JB_ERR_MEMORY;
4340 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4347 /*********************************************************************
4349 * Function : create_fake_referrer
4351 * Description : Helper for client_referrer to create a fake referrer
4352 * based on a string supplied by the user.
4355 * 1 : header = Pointer to header pointer
4356 * 2 : hosthost = Referrer to fake
4358 * Returns : JB_ERR_OK in case of success, or
4359 * JB_ERR_MEMORY in case of memory problems.
4361 *********************************************************************/
4362 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4364 assert(NULL == *header);
4366 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4368 log_error(LOG_LEVEL_HEADER,
4369 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4371 *header = strdup("Referer: ");
4372 string_append(header, fake_referrer);
4374 if (NULL == *header)
4376 return JB_ERR_MEMORY;
4379 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4386 /*********************************************************************
4388 * Function : handle_conditional_hide_referrer_parameter
4390 * Description : Helper for client_referrer to crunch or forge
4391 * the referrer header if the host has changed.
4394 * 1 : header = Pointer to header pointer
4395 * 2 : host = The target host (may include the port)
4396 * 3 : parameter_conditional_block = Boolean to signal
4397 * if we're in conditional-block mode. If not set,
4398 * we're in conditional-forge mode.
4400 * Returns : JB_ERR_OK in case of success, or
4401 * JB_ERR_MEMORY in case of memory problems.
4403 *********************************************************************/
4404 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4405 const char *host, const int parameter_conditional_block)
4407 char *referer = strdup(*header);
4408 const size_t hostlenght = strlen(host);
4410 if (NULL == referer)
4413 return JB_ERR_MEMORY;
4416 /* referer begins with 'Referer: http[s]://' */
4417 if (hostlenght < (strlen(referer)-17))
4420 * Shorten referer to make sure the referer is blocked
4421 * if www.example.org/www.example.com-shall-see-the-referer/
4422 * links to www.example.com/
4424 referer[hostlenght+17] = '\0';
4426 if (NULL == strstr(referer, host))
4428 /* Host has changed */
4429 if (parameter_conditional_block)
4431 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4438 return create_forged_referrer(header, host);