1 const char parsers_rcs[] = "$Id: parsers.c,v 1.110 2007/09/29 10:42:37 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-2007 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.110 2007/09/29 10:42:37 fabiankeil
48 * - Remove "scanning headers for" log message again.
49 * - Some more whitespace fixes.
51 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
52 * Refactor client_referrer() and add conditional-forge parameter.
54 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
55 * A bunch of whitespace fixes, pointy hat to me.
57 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
58 * Fix possible memory corruption in server_http, make sure it's not
59 * executed for ordinary server headers and mark some problems for later.
61 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
62 * Let content-type-overwrite{} honour force-text-mode again.
64 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
65 * - Add prototpyes for the header parsers and make them static.
66 * - Comment out client_accept_encoding_adder() which isn't used right now.
68 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
69 * Move the ACTION_FORCE_TEXT_MODE check out of
70 * server_content_type(). Signal other functions
71 * whether or not a content type has been declared.
72 * Part of the fix for BR#1750917.
74 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
75 * Change sed() to return a jb_err in preparation for forward-override{}.
77 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
78 * Adjust "X-Filter: No" to disable dedicated header filters.
80 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
81 * Streamline client_cookie_adder().
83 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
84 * Make sure filters with dynamic jobs actually use them.
86 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
87 * - Introduce dynamic pcrs jobs that can resolve variables.
88 * - Remove unnecessary update_action_bits_for_all_tags() call.
90 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
91 * - Make tagging based on tags set by earlier taggers
92 * of the same kind possible.
93 * - Log whether or not new tags cause action bits updates
94 * (in which case a matching tag-pattern section exists).
95 * - Log if the user tries to set a tag that is already set.
97 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
98 * Introduce tags as alternative way to specify which
99 * actions apply to a request. At the moment tags can be
100 * created based on client and server headers.
102 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
103 * Log a warning if the content is compressed, filtering is
104 * enabled and Privoxy was compiled without zlib support.
107 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
108 * - Fix warnings when compiled with glibc.
109 * - Don't use crumble() for cookie crunching.
110 * - Move cookie time parsing into parse_header_time().
111 * - Let parse_header_time() return a jb_err code
112 * instead of a pointer that can only be used to
113 * check for NULL anyway.
115 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
116 * - Add better protection against malicious gzip headers.
117 * - Stop logging the first hundred bytes of decompressed content.
118 * It looks like it's working and there is always debug 16.
119 * - Log the content size after decompression in decompress_iob()
120 * instead of pcrs_filter_response().
122 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
123 * - Use dedicated header filter actions instead of abusing "filter".
124 * Replace "filter-client-headers" and "filter-client-headers"
125 * with "server-header-filter" and "client-header-filter".
126 * - Remove filter_client_header() and filter_client_header(),
127 * filter_header() now checks the shiny new
128 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
130 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
131 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
132 * - Handle "Cookie:" and "Connection:" headers a bit smarter
133 * (don't crunch them just to recreate them later on).
134 * - Add another non-standard time format for the cookie
135 * expiration date detection.
136 * - Fix a valgrind warning.
138 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
139 * Improve cookie expiration date detection.
141 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
142 * Don't run server_content_length() the first time
143 * sed() parses server headers; only adjust the
144 * Content-Length header if the page was modified.
146 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
147 * Fix log messages regarding the cookie time format
148 * (cookie and request URL were mixed up).
150 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
151 * - Let decompress_iob()
152 * - not corrupt the content if decompression fails
153 * early. (the first byte(s) were lost).
154 * - use pointer arithmetics with defined outcome for
156 * - Use a different kludge to remember a failed decompression.
158 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
159 * Search for Max-Forwards headers case-insensitive,
160 * don't generate the "501 unsupported" message for invalid
161 * Max-Forwards values and don't increase negative ones.
163 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
164 * - Let server_set_cookie() check the expiration date
165 * of cookies and don't touch the ones that are already
166 * expired. Fixes problems with low quality web applications
167 * as described in BR 932612.
169 * - Adjust comment in client_max_forwards to reality;
170 * remove invalid Max-Forwards headers.
172 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
173 * Stop filter_header() from unintentionally removing
174 * empty header lines that were enlisted by the continue
177 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
178 * - Repeat the request URL before logging any headers.
179 * Makes reading the log easier in case of simultaneous requests.
180 * - If there are more than one Content-Type headers in one request,
181 * use the first one and remove the others.
182 * - Remove "newval" variable in server_content_type().
183 * It's only used once.
185 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
186 * Correct a cast, check inflateEnd() exit code
187 * to see if we have to, replace sprintf calls
190 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
191 * Integrate a modified version of Wil Mahan's
192 * zlib patch (PR #895531).
194 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
195 * Skip empty filter files in filter_header()
196 * but don't ignore the ones that come afterwards.
197 * Fixes BR 1619208, this time for real.
199 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
200 * Reverted parts of my last commit
201 * to keep error handling working.
203 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
204 * Fixed gcc43 conversion warnings.
206 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
207 * Bringing back the "useless" localtime() call
208 * I removed in revision 1.67. On some platforms
209 * it's necessary to prevent time zone offsets.
211 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
212 * Rebuild request URL in get_destination_from_headers()
213 * to make sure redirect{pcrs command} works as expected
214 * for intercepted requests.
216 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
217 * Added get_destination_from_headers().
219 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
220 * Make pthread mutex locking more generic. Instead of
221 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
222 * and use mutex locking unless there is an _r function
223 * available. Better safe than sorry.
225 * Fixes "./configure --disable-pthread" and should result
226 * in less threading-related problems on pthread-using platforms,
227 * but it still doesn't fix BR#1122404.
229 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
230 * The special header "X-Filter: No" now disables
231 * header filtering as well.
233 * Revision 1.73 2006/09/23 13:26:38 roro
234 * Replace TABs by spaces in source code.
236 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
237 * Don't print a log message every time filter_headers is
238 * entered or left. It only creates noise without any real
241 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
242 * Fix +hide-if-modified-since{-n}.
244 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
245 * Have hide-if-modified-since interpret the random
246 * range value as minutes instead of hours. Allows
247 * more fine-grained configuration.
249 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
250 * Always have parse_header_time return a pointer
251 * that actual makes sense, even though we currently
252 * only need it to detect problems.
254 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
255 * Added config option enable-remote-http-toggle
256 * to specify if Privoxy should recognize special
257 * headers (currently only X-Filter) to change its
258 * behaviour. Disabled by default.
260 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
261 * After filtering de-chunked instances, remove
262 * "Transfer-Encoding" header entirely instead of changing
263 * it to "Transfer-Encoding: identity", which is invalid.
264 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
266 * Don't use localtime in parse_header_time. An empty time struct
267 * is good enough, it gets overwritten by strptime anyway.
269 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
270 * Use gmtime_r if available, fallback to gmtime with mutex
271 * protection for MacOSX and use vanilla gmtime for the rest.
273 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
274 * Changed client_referrer to use the right type (size_t) for
275 * hostlenght and to shorten the temporary referrer string with
276 * '\0' instead of adding a useless line break.
278 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
279 * - Back to timegm() using GnuPG's replacement if necessary.
280 * Using mktime() and localtime() could add a on hour offset if
281 * the randomize factor was big enough to lead to a summer/wintertime
284 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
286 * - Moved randomization code into pick_from_range().
288 * - Changed parse_header_time definition.
289 * time_t isn't guaranteed to be signed and
290 * if it isn't, -1 isn't available as error code.
291 * Changed some variable types in client_if_modified_since()
292 * because of the same reason.
294 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
295 * OS/2 compilation compatibility fixups
297 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
298 * Changed include from strptime.c to strptime.h
300 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
301 * Split filter-headers{} into filter-client-headers{}
302 * and filter-server-headers{}.
303 * Added parse_header_time() to share some code.
304 * Replaced timegm() with mktime().
306 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
307 * Windows service integration
309 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
310 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
312 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
313 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
314 * with what was really the latest development (the v_3_0_branch branch)
316 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
317 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
319 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
320 * Add the ability to check jpeg images for invalid
321 * lengths of comment blocks. Defensive strategy
322 * against the exploit:
323 * Microsoft Security Bulletin MS04-028
324 * Buffer Overrun in JPEG Processing (GDI+) Could
325 * Allow Code Execution (833987)
326 * Enabled with +inspect-jpegs in actions files.
328 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
329 * Excluded text/plain objects from filtering. This fixes a
330 * couple of client-crashing, download corruption and
331 * Privoxy performance issues, whose root cause lies in
332 * web servers labelling content of unknown type as text/plain.
334 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
335 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
337 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
338 * Completing the previous change
340 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
341 * Added temporary workaround for bug in PHP < 4.2.3
343 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
344 * 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.
346 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
347 * Fix typo: supressed -> suppressed
349 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
350 * Improved cookie logging
352 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
353 * Added basic support for OPTIONS and TRACE HTTP methods:
354 * - New parser function client_max_forwards which decrements
355 * the Max-Forwards HTTP header field of OPTIONS and TRACE
356 * requests by one before forwarding
357 * - New parser function client_host which extracts the host
358 * and port information from the HTTP header field if the
359 * request URI was not absolute
360 * - Don't crumble and re-add the Host: header, but only generate
361 * and append if missing
363 * Revision 1.56 2002/05/12 15:34:22 jongfoster
364 * Fixing typo in a comment
366 * Revision 1.55 2002/05/08 16:01:07 oes
367 * Optimized add_to_iob:
368 * - Use realloc instead of malloc(), memcpy(), free()
369 * - Expand to powers of two if possible, to get
370 * O(log n) reallocs instead of O(n).
371 * - Moved check for buffer limit here from chat
372 * - Report failure via returncode
374 * Revision 1.54 2002/04/02 15:03:16 oes
375 * Tiny code cosmetics
377 * Revision 1.53 2002/03/26 22:29:55 swa
378 * we have a new homepage!
380 * Revision 1.52 2002/03/24 13:25:43 swa
381 * name change related issues
383 * Revision 1.51 2002/03/13 00:27:05 jongfoster
386 * Revision 1.50 2002/03/12 01:45:35 oes
387 * More verbose logging
389 * Revision 1.49 2002/03/09 20:03:52 jongfoster
390 * - Making various functions return int rather than size_t.
391 * (Undoing a recent change). Since size_t is unsigned on
392 * Windows, functions like read_socket that return -1 on
393 * error cannot return a size_t.
395 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
396 * crashes, and also frequently caused JB to jump to 100%
397 * CPU and stay there. (Because it thought it had just
398 * read ((unsigned)-1) == 4Gb of data...)
400 * - The signature of write_socket has changed, it now simply
401 * returns success=0/failure=nonzero.
403 * - Trying to get rid of a few warnings --with-debug on
404 * Windows, I've introduced a new type "jb_socket". This is
405 * used for the socket file descriptors. On Windows, this
406 * is SOCKET (a typedef for unsigned). Everywhere else, it's
407 * an int. The error value can't be -1 any more, so it's
408 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
409 * Windows it maps to the #define INVALID_SOCKET.)
411 * - The signature of bind_port has changed.
413 * Revision 1.48 2002/03/07 03:46:53 oes
414 * Fixed compiler warnings etc
416 * Revision 1.47 2002/02/20 23:15:13 jongfoster
417 * Parsing functions now handle out-of-memory gracefully by returning
420 * Revision 1.46 2002/01/17 21:03:47 jongfoster
421 * Moving all our URL and URL pattern parsing code to urlmatch.c.
423 * Revision 1.45 2002/01/09 14:33:03 oes
424 * Added support for localtime_r.
426 * Revision 1.44 2001/12/14 01:22:54 steudten
427 * Remove 'user:pass@' from 'proto://user:pass@host' for the
428 * new added header 'Host: ..'. (See Req ID 491818)
430 * Revision 1.43 2001/11/23 00:26:38 jongfoster
431 * Fixing two really stupid errors in my previous commit
433 * Revision 1.42 2001/11/22 21:59:30 jongfoster
434 * Adding code to handle +no-cookies-keep
436 * Revision 1.41 2001/11/05 23:43:05 steudten
437 * Add time+date to log files.
439 * Revision 1.40 2001/10/26 20:13:09 jongfoster
440 * ctype.h is needed in Windows, too.
442 * Revision 1.39 2001/10/26 17:40:04 oes
443 * Introduced get_header_value()
444 * Removed http->user_agent, csp->referrer and csp->accept_types
445 * Removed client_accept()
447 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
448 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
449 * threads to call select() simultaneously. So, it's time to do a real, live,
450 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
451 * (native). Both versions will work, but using __OS2__ offers multi-threading.
453 * Revision 1.37 2001/10/23 21:36:02 jongfoster
454 * Documenting sed()'s error behaviou (doc change only)
456 * Revision 1.36 2001/10/13 12:51:51 joergs
457 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
458 * force-load), instead crumble Host: and add it (again) in client_host_adder
459 * (in case we get a HTTP/1.0 request without Host: header and forward it to
460 * a HTTP/1.1 server/proxy).
462 * Revision 1.35 2001/10/09 22:39:21 jongfoster
463 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
466 * Revision 1.34 2001/10/07 18:50:55 oes
467 * Added server_content_encoding, renamed server_transfer_encoding
469 * Revision 1.33 2001/10/07 18:04:49 oes
470 * Changed server_http11 to server_http and its pattern to "HTTP".
471 * Additional functionality: it now saves the HTTP status into
472 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
474 * Revision 1.32 2001/10/07 15:43:28 oes
475 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
476 * client_te and client_accept_encoding_adder, triggered by the new
477 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
478 * changed to allow only identity and chunked, and the TE header is
479 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
481 * parse_http_request no longer does anything than parsing. The rewriting
482 * of http->cmd and version mangling are gone. It now also recognizes
483 * the put and delete methods and saves the url in http->url. Removed
486 * renamed content_type and content_length to have the server_ prefix
488 * server_content_type now only works if csp->content_type != CT_TABOO
490 * added server_transfer_encoding, which
491 * - Sets CT_TABOO to prohibit filtering if encoding compresses
492 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
493 * - Change from "chunked" to "identity" if body was chunked
494 * but has been de-chunked for filtering.
496 * added server_content_md5 which crunches any Content-MD5 headers
497 * if the body was modified.
499 * made server_http11 conditional on +downgrade action
501 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
503 * Revision 1.31 2001/10/05 14:25:02 oes
504 * Crumble Keep-Alive from Server
506 * Revision 1.30 2001/09/29 12:56:03 joergs
507 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
509 * Revision 1.29 2001/09/24 21:09:24 jongfoster
510 * Fixing 2 memory leaks that Guy spotted, where the paramater to
511 * enlist() was not being free()d.
513 * Revision 1.28 2001/09/22 16:32:28 jongfoster
514 * Removing unused #includes.
516 * Revision 1.27 2001/09/20 15:45:25 steudten
518 * add casting from size_t to int for printf()
519 * remove local variable shadow s2
521 * Revision 1.26 2001/09/16 17:05:14 jongfoster
522 * Removing unused #include showarg.h
524 * Revision 1.25 2001/09/16 13:21:27 jongfoster
525 * Changes to use new list functions.
527 * Revision 1.24 2001/09/13 23:05:50 jongfoster
528 * Changing the string paramater to the header parsers a "const".
530 * Revision 1.23 2001/09/12 18:08:19 steudten
532 * In parse_http_request() header rewriting miss the host value, so
533 * from http://www.mydomain.com the result was just " / " not
534 * http://www.mydomain.com/ in case we forward.
536 * Revision 1.22 2001/09/10 10:58:53 oes
537 * Silenced compiler warnings
539 * Revision 1.21 2001/07/31 14:46:00 oes
540 * - Persistant connections now suppressed
541 * - sed() no longer appends empty header to csp->headers
543 * Revision 1.20 2001/07/30 22:08:36 jongfoster
544 * Tidying up #defines:
545 * - All feature #defines are now of the form FEATURE_xxx
546 * - Permanently turned off WIN_GUI_EDIT
547 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
549 * Revision 1.19 2001/07/25 17:21:54 oes
550 * client_uagent now saves copy of User-Agent: header value
552 * Revision 1.18 2001/07/13 14:02:46 oes
553 * - Included fix to repair broken HTTP requests that
554 * don't contain a path, not even '/'.
555 * - Removed all #ifdef PCRS
556 * - content_type now always inspected and classified as
557 * text, gif or other.
558 * - formatting / comments
560 * Revision 1.17 2001/06/29 21:45:41 oes
561 * Indentation, CRLF->LF, Tab-> Space
563 * Revision 1.16 2001/06/29 13:32:42 oes
565 * - Adapted free_http_request
566 * - Removed logentry from cancelled commit
568 * Revision 1.15 2001/06/03 19:12:38 oes
569 * deleted const struct interceptors
571 * Revision 1.14 2001/06/01 18:49:17 jongfoster
572 * Replaced "list_share" with "list" - the tiny memory gain was not
573 * worth the extra complexity.
575 * Revision 1.13 2001/05/31 21:30:33 jongfoster
576 * Removed list code - it's now in list.[ch]
577 * Renamed "permission" to "action", and changed many features
578 * to use the actions file rather than the global config.
580 * Revision 1.12 2001/05/31 17:33:13 oes
584 * Revision 1.11 2001/05/29 20:11:19 joergs
585 * '/ * inside comment' warning removed.
587 * Revision 1.10 2001/05/29 09:50:24 jongfoster
588 * Unified blocklist/imagelist/permissionslist.
589 * File format is still under discussion, but the internal changes
592 * Also modified interceptor behaviour:
593 * - We now intercept all URLs beginning with one of the following
594 * prefixes (and *only* these prefixes):
596 * * http://ijbswa.sf.net/config/
597 * * http://ijbswa.sourceforge.net/config/
598 * - New interceptors "home page" - go to http://i.j.b/ to see it.
599 * - Internal changes so that intercepted and fast redirect pages
600 * are not replaced with an image.
601 * - Interceptors now have the option to send a binary page direct
602 * to the client. (i.e. ijb-send-banner uses this)
603 * - Implemented show-url-info interceptor. (Which is why I needed
604 * the above interceptors changes - a typical URL is
605 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
606 * The previous mechanism would not have intercepted that, and
607 * if it had been intercepted then it then it would have replaced
610 * Revision 1.9 2001/05/28 17:26:33 jongfoster
611 * Fixing segfault if last header was crunched.
612 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
613 * can use the cross-platform sprintf() instead.)
615 * Revision 1.8 2001/05/27 22:17:04 oes
617 * - re_process_buffer no longer writes the modified buffer
618 * to the client, which was very ugly. It now returns the
619 * buffer, which it is then written by chat.
621 * - content_length now adjusts the Content-Length: header
622 * for modified documents rather than crunch()ing it.
623 * (Length info in csp->content_length, which is 0 for
624 * unmodified documents)
626 * - For this to work, sed() is called twice when filtering.
628 * Revision 1.7 2001/05/27 13:19:06 oes
629 * Patched Joergs solution for the content-length in.
631 * Revision 1.6 2001/05/26 13:39:32 jongfoster
632 * Only crunches Content-Length header if applying RE filtering.
633 * Without this fix, Microsoft Windows Update wouldn't work.
635 * Revision 1.5 2001/05/26 00:28:36 jongfoster
636 * Automatic reloading of config file.
637 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
638 * Most of the global variables have been moved to a new
639 * struct configuration_spec, accessed through csp->config->globalname
640 * Most of the globals remaining are used by the Win32 GUI.
642 * Revision 1.4 2001/05/22 18:46:04 oes
644 * - Enabled filtering banners by size rather than URL
645 * by adding patterns that replace all standard banner
646 * sizes with the "Junkbuster" gif to the re_filterfile
648 * - Enabled filtering WebBugs by providing a pattern
649 * which kills all 1x1 images
651 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
652 * which is selected by the (nonstandard and therefore
653 * capital) letter 'U' in the option string.
654 * It causes the quantifiers to be ungreedy by default.
655 * Appending a ? turns back to greedy (!).
657 * - Added a new interceptor ijb-send-banner, which
658 * sends back the "Junkbuster" gif. Without imagelist or
659 * MSIE detection support, or if tinygif = 1, or the
660 * URL isn't recognized as an imageurl, a lame HTML
661 * explanation is sent instead.
663 * - Added new feature, which permits blocking remote
664 * script redirects and firing back a local redirect
666 * The feature is conditionally compiled, i.e. it
667 * can be disabled with --disable-fast-redirects,
668 * plus it must be activated by a "fast-redirects"
669 * line in the config file, has its own log level
670 * and of course wants to be displayed by show-proxy-args
671 * Note: Boy, all the #ifdefs in 1001 locations and
672 * all the fumbling with configure.in and acconfig.h
673 * were *way* more work than the feature itself :-(
675 * - Because a generic redirect template was needed for
676 * this, tinygif = 3 now uses the same.
678 * - Moved GIFs, and other static HTTP response templates
683 * - Removed some >400 CRs again (Jon, you really worked
686 * Revision 1.3 2001/05/20 01:21:20 jongfoster
687 * Version 2.9.4 checkin.
688 * - Merged popupfile and cookiefile, and added control over PCRS
689 * filtering, in new "permissionsfile".
690 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
691 * file error you now get a message box (in the Win32 GUI) rather
692 * than the program exiting with no explanation.
693 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
695 * - Removed tabs from "config"
696 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
697 * - Bumped up version number.
699 * Revision 1.2 2001/05/17 23:02:36 oes
700 * - Made referrer option accept 'L' as a substitute for '§'
702 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
703 * Initial import of version 2.9.3 source tree
706 *********************************************************************/
713 #include <sys/types.h>
723 * Convince GNU's libc to provide a strptime prototype.
726 #endif /*__GLIBC__ */
733 #if !defined(_WIN32) && !defined(__OS2__)
739 #ifdef FEATURE_PTHREAD
741 /* jcc.h is for mutex semapores only */
742 #endif /* def FEATURE_PTHREAD */
748 #include "jbsockets.h"
749 #include "miscutil.h"
754 #ifndef HAVE_STRPTIME
755 #include "strptime.h"
758 const char parsers_h_rcs[] = PARSERS_H_VERSION;
760 /* Fix a problem with Solaris. There should be no effect on other
762 * Solaris's isspace() is a macro which uses its argument directly
763 * as an array index. Therefore we need to make sure that high-bit
764 * characters generate +ve values, and ideally we also want to make
765 * the argument match the declared parameter type of "int".
767 * Why did they write a character function that can't take a simple
768 * "char" argument? Doh!
770 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
771 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
773 static jb_err scan_headers(struct client_state *csp);
774 static jb_err header_tagger(struct client_state *csp, char *header);
775 static jb_err parse_header_time(const char *header_time, time_t *result);
777 static jb_err crumble (struct client_state *csp, char **header);
778 static jb_err connection (struct client_state *csp, char **header);
779 static jb_err filter_header (struct client_state *csp, char **header);
780 static jb_err client_referrer (struct client_state *csp, char **header);
781 static jb_err client_uagent (struct client_state *csp, char **header);
782 static jb_err client_ua (struct client_state *csp, char **header);
783 static jb_err client_from (struct client_state *csp, char **header);
784 static jb_err client_send_cookie (struct client_state *csp, char **header);
785 static jb_err client_x_forwarded (struct client_state *csp, char **header);
786 static jb_err client_accept_encoding (struct client_state *csp, char **header);
787 static jb_err client_te (struct client_state *csp, char **header);
788 static jb_err client_max_forwards (struct client_state *csp, char **header);
789 static jb_err client_host (struct client_state *csp, char **header);
790 static jb_err client_if_modified_since (struct client_state *csp, char **header);
791 static jb_err client_accept_language (struct client_state *csp, char **header);
792 static jb_err client_if_none_match (struct client_state *csp, char **header);
793 static jb_err crunch_client_header (struct client_state *csp, char **header);
794 static jb_err client_x_filter (struct client_state *csp, char **header);
795 static jb_err server_set_cookie (struct client_state *csp, char **header);
796 static jb_err server_content_type (struct client_state *csp, char **header);
797 static jb_err server_content_length (struct client_state *csp, char **header);
798 static jb_err server_content_md5 (struct client_state *csp, char **header);
799 static jb_err server_content_encoding (struct client_state *csp, char **header);
800 static jb_err server_transfer_coding (struct client_state *csp, char **header);
801 static jb_err server_http (struct client_state *csp, char **header);
802 static jb_err crunch_server_header (struct client_state *csp, char **header);
803 static jb_err server_last_modified (struct client_state *csp, char **header);
804 static jb_err server_content_disposition(struct client_state *csp, char **header);
806 static jb_err client_host_adder (struct client_state *csp);
807 static jb_err client_cookie_adder (struct client_state *csp);
808 static jb_err client_xtra_adder (struct client_state *csp);
809 static jb_err client_x_forwarded_adder(struct client_state *csp);
810 static jb_err connection_close_adder (struct client_state *csp);
812 static jb_err create_forged_referrer(char **header, const char *hostport);
813 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
814 static jb_err handle_conditional_hide_referrer_parameter(char **header,
815 const char *host, const int parameter_conditional_block);
817 const struct parsers client_patterns[] = {
818 { "referer:", 8, client_referrer },
819 { "user-agent:", 11, client_uagent },
820 { "ua-", 3, client_ua },
821 { "from:", 5, client_from },
822 { "cookie:", 7, client_send_cookie },
823 { "x-forwarded-for:", 16, client_x_forwarded },
824 { "Accept-Encoding:", 16, client_accept_encoding },
825 { "TE:", 3, client_te },
826 { "Host:", 5, client_host },
827 { "if-modified-since:", 18, client_if_modified_since },
828 { "Keep-Alive:", 11, crumble },
829 { "connection:", 11, connection },
830 { "proxy-connection:", 17, crumble },
831 { "max-forwards:", 13, client_max_forwards },
832 { "Accept-Language:", 16, client_accept_language },
833 { "if-none-match:", 14, client_if_none_match },
834 { "X-Filter:", 9, client_x_filter },
835 { "*", 0, crunch_client_header },
836 { "*", 0, filter_header },
840 const struct parsers server_patterns[] = {
841 { "HTTP/", 5, server_http },
842 { "set-cookie:", 11, server_set_cookie },
843 { "connection:", 11, connection },
844 { "Content-Type:", 13, server_content_type },
845 { "Content-MD5:", 12, server_content_md5 },
846 { "Content-Encoding:", 17, server_content_encoding },
847 { "Transfer-Encoding:", 18, server_transfer_coding },
848 { "Keep-Alive:", 11, crumble },
849 { "content-disposition:", 20, server_content_disposition },
850 { "Last-Modified:", 14, server_last_modified },
851 { "*", 0, crunch_server_header },
852 { "*", 0, filter_header },
856 const struct parsers server_patterns_light[] = {
857 { "Content-Length:", 15, server_content_length },
858 { "Transfer-Encoding:", 18, server_transfer_coding },
860 { "Content-Encoding:", 17, server_content_encoding },
861 #endif /* def FEATURE_ZLIB */
865 const add_header_func_ptr add_client_headers[] = {
868 client_x_forwarded_adder,
870 /* Temporarily disabled: client_accept_encoding_adder, */
871 connection_close_adder,
875 const add_header_func_ptr add_server_headers[] = {
876 connection_close_adder,
880 /* The vanilla wafer. */
881 static const char VANILLA_WAFER[] =
882 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
883 "Do_not_send_me_any_copyrighted_information_other_than_the_"
884 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
885 "In_particular_do_not_send_me_any_cookies_that_"
886 "are_subject_to_a_claim_of_copyright_by_anybody._"
887 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
888 "(copyright_or_otherwise)_applying_to_any_cookie._";
890 /*********************************************************************
892 * Function : flush_socket
894 * Description : Write any pending "buffered" content.
897 * 1 : fd = file descriptor of the socket to read
898 * 2 : csp = Current client state (buffers, headers, etc...)
900 * Returns : On success, the number of bytes written are returned (zero
901 * indicates nothing was written). On error, -1 is returned,
902 * and errno is set appropriately. If count is zero and the
903 * file descriptor refers to a regular file, 0 will be
904 * returned without causing any other effect. For a special
905 * file, the results are not portable.
907 *********************************************************************/
908 int flush_socket(jb_socket fd, struct client_state *csp)
910 struct iob *iob = csp->iob;
911 int len = iob->eod - iob->cur;
918 if (write_socket(fd, iob->cur, (size_t)len))
922 iob->eod = iob->cur = iob->buf;
928 /*********************************************************************
930 * Function : add_to_iob
932 * Description : Add content to the buffered page, expanding the
933 * buffer if necessary.
936 * 1 : csp = Current client state (buffers, headers, etc...)
937 * 2 : buf = holds the content to be added to the page
938 * 3 : n = number of bytes to be added
940 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
941 * or buffer limit reached.
943 *********************************************************************/
944 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
946 struct iob *iob = csp->iob;
947 size_t used, offset, need, want;
950 if (n <= 0) return JB_ERR_OK;
952 used = (size_t)(iob->eod - iob->buf);
953 offset = (size_t)(iob->cur - iob->buf);
954 need = used + (size_t)n + 1;
957 * If the buffer can't hold the new data, extend it first.
958 * Use the next power of two if possible, else use the actual need.
960 if (need > csp->config->buffer_limit)
962 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
963 return JB_ERR_MEMORY;
966 if (need > iob->size)
968 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
970 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
974 else if (NULL != (p = (char *)realloc(iob->buf, need)))
980 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
981 return JB_ERR_MEMORY;
984 /* Update the iob pointers */
985 iob->cur = p + offset;
990 /* copy the new data into the iob buffer */
991 memcpy(iob->eod, buf, (size_t)n);
993 /* point to the end of the data */
996 /* null terminate == cheap insurance */
1005 /*********************************************************************
1007 * Function : decompress_iob
1009 * Description : Decompress buffered page, expanding the
1010 * buffer as necessary. csp->iob->cur
1011 * should point to the the beginning of the
1012 * compressed data block.
1015 * 1 : csp = Current client state (buffers, headers, etc...)
1017 * Returns : JB_ERR_OK on success,
1018 * JB_ERR_MEMORY if out-of-memory limit reached, and
1019 * JB_ERR_COMPRESS if error decompressing buffer.
1021 *********************************************************************/
1022 jb_err decompress_iob(struct client_state *csp)
1024 char *buf; /* new, uncompressed buffer */
1025 char *cur; /* Current iob position (to keep the original
1026 * iob->cur unmodified if we return early) */
1027 size_t bufsize; /* allocated size of the new buffer */
1028 size_t old_size; /* Content size before decompression */
1029 size_t skip_size; /* Number of bytes at the beginning of the iob
1030 that we should NOT decompress. */
1031 int status; /* return status of the inflate() call */
1032 z_stream zstr; /* used by calls to zlib */
1034 assert(csp->iob->cur - csp->iob->buf > 0);
1035 assert(csp->iob->eod - csp->iob->cur > 0);
1037 bufsize = csp->iob->size;
1038 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1039 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1041 cur = csp->iob->cur;
1046 * This is to protect the parsing of gzipped data,
1047 * but it should(?) be valid for deflated data also.
1049 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1050 return JB_ERR_COMPRESS;
1053 if (csp->content_type & CT_GZIP)
1056 * Our task is slightly complicated by the facts that data
1057 * compressed by gzip does not include a zlib header, and
1058 * that there is no easily accessible interface in zlib to
1059 * handle a gzip header. We strip off the gzip header by
1060 * hand, and later inform zlib not to expect a header.
1064 * Strip off the gzip header. Please see RFC 1952 for more
1065 * explanation of the appropriate fields.
1067 if ((*cur++ != (char)0x1f)
1068 || (*cur++ != (char)0x8b)
1069 || (*cur++ != Z_DEFLATED))
1071 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1072 return JB_ERR_COMPRESS;
1078 * XXX: These magic numbers should be replaced
1079 * with macros to give a better idea what they do.
1083 /* The gzip header has reserved bits set; bail out. */
1084 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1085 return JB_ERR_COMPRESS;
1089 /* Skip extra fields if necessary. */
1093 * Skip a given number of bytes, specified
1094 * as a 16-bit little-endian value.
1097 * XXX: This code used to be:
1099 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1101 * which I had to change into:
1103 * cur += *cur++ + (*cur++ << 8);
1105 * at which point gcc43 finally noticed that the value
1106 * of cur is undefined (it depends on which of the
1107 * summands is evaluated first).
1109 * I haven't come across a site where this
1110 * code is actually executed yet, but I hope
1114 skip_bytes = *cur++;
1115 skip_bytes = *cur++ << 8;
1117 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1120 * The number of bytes to skip should be positive
1121 * and we'd like to stay in the buffer.
1123 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1125 log_error(LOG_LEVEL_ERROR,
1126 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1128 return JB_ERR_COMPRESS;
1130 log_error(LOG_LEVEL_INFO,
1131 "Skipping %d bytes for gzip compression. Does this sound right?",
1136 /* Skip the filename if necessary. */
1139 /* A null-terminated string is supposed to follow. */
1140 while (*cur++ && (cur < csp->iob->eod));
1144 /* Skip the comment if necessary. */
1147 /* A null-terminated string is supposed to follow. */
1148 while (*cur++ && (cur < csp->iob->eod));
1151 /* Skip the CRC if necessary. */
1157 if (cur >= csp->iob->eod)
1160 * If the current position pointer reached or passed
1161 * the buffer end, we were obviously tricked to skip
1164 log_error(LOG_LEVEL_ERROR,
1165 "Malformed gzip header detected. Aborting decompression.");
1166 return JB_ERR_COMPRESS;
1170 else if (csp->content_type & CT_DEFLATE)
1173 * XXX: The debug level should be lowered
1174 * before the next stable release.
1176 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1178 * In theory (that is, according to RFC 1950), deflate-compressed
1179 * data should begin with a two-byte zlib header and have an
1180 * adler32 checksum at the end. It seems that in practice only
1181 * the raw compressed data is sent. Note that this means that
1182 * we are not RFC 1950-compliant here, but the advantage is that
1183 * this actually works. :)
1185 * We add a dummy null byte to tell zlib where the data ends,
1186 * and later inform it not to expect a header.
1188 * Fortunately, add_to_iob() has thoughtfully null-terminated
1189 * the buffer; we can just increment the end pointer to include
1196 log_error(LOG_LEVEL_ERROR,
1197 "Unable to determine compression format for decompression");
1198 return JB_ERR_COMPRESS;
1201 /* Set up the fields required by zlib. */
1202 zstr.next_in = (Bytef *)cur;
1203 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1204 zstr.zalloc = Z_NULL;
1205 zstr.zfree = Z_NULL;
1206 zstr.opaque = Z_NULL;
1209 * Passing -MAX_WBITS to inflateInit2 tells the library
1210 * that there is no zlib header.
1212 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1214 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1215 return JB_ERR_COMPRESS;
1219 * Next, we allocate new storage for the inflated data.
1220 * We don't modify the existing iob yet, so in case there
1221 * is error in decompression we can recover gracefully.
1223 buf = zalloc(bufsize);
1226 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1227 return JB_ERR_MEMORY;
1230 assert(bufsize >= skip_size);
1231 memcpy(buf, csp->iob->buf, skip_size);
1232 zstr.avail_out = bufsize - skip_size;
1233 zstr.next_out = (Bytef *)buf + skip_size;
1235 /* Try to decompress the whole stream in one shot. */
1236 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1238 /* We need to allocate more memory for the output buffer. */
1240 char *tmpbuf; /* used for realloc'ing the buffer */
1241 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1244 * If zlib wants more data then there's a problem, because
1245 * the complete compressed file should have been buffered.
1247 if (0 == zstr.avail_in)
1249 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1250 return JB_ERR_COMPRESS;
1254 * If we tried the limit and still didn't have enough
1255 * memory, just give up.
1257 if (bufsize == csp->config->buffer_limit)
1259 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1260 return JB_ERR_MEMORY;
1263 /* Try doubling the buffer size each time. */
1266 /* Don't exceed the buffer limit. */
1267 if (bufsize > csp->config->buffer_limit)
1269 bufsize = csp->config->buffer_limit;
1272 /* Try to allocate the new buffer. */
1273 tmpbuf = realloc(buf, bufsize);
1276 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1278 return JB_ERR_MEMORY;
1282 char *oldnext_out = (char *)zstr.next_out;
1285 * Update the fields for inflate() to use the new
1286 * buffer, which may be in a location different from
1289 zstr.avail_out += bufsize - oldbufsize;
1290 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1293 * Compare with an uglier method of calculating these values
1294 * that doesn't require the extra oldbufsize variable.
1296 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1297 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1298 assert(zstr.avail_out > 0);
1304 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1306 log_error(LOG_LEVEL_ERROR,
1307 "Inconsistent stream state after decompression: %s", zstr.msg);
1309 * XXX: Intentionally no return.
1311 * According to zlib.h, Z_STREAM_ERROR is returned
1312 * "if the stream state was inconsistent".
1314 * I assume in this case inflate()'s status
1315 * would also be something different than Z_STREAM_END
1316 * so this check should be redundant, but lets see.
1320 if (status != Z_STREAM_END)
1322 /* We failed to decompress the stream. */
1323 log_error(LOG_LEVEL_ERROR,
1324 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1325 return JB_ERR_COMPRESS;
1329 * Finally, we can actually update the iob, since the
1330 * decompression was successful. First, free the old
1333 freez(csp->iob->buf);
1335 /* Now, update the iob to use the new buffer. */
1336 csp->iob->buf = buf;
1337 csp->iob->cur = csp->iob->buf + skip_size;
1338 csp->iob->eod = (char *)zstr.next_out;
1339 csp->iob->size = bufsize;
1342 * Make sure the new uncompressed iob obeys some minimal
1343 * consistency conditions.
1345 if ((csp->iob->buf < csp->iob->cur)
1346 && (csp->iob->cur <= csp->iob->eod)
1347 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1349 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1352 log_error(LOG_LEVEL_RE_FILTER,
1353 "Decompression successful. Old size: %d, new size: %d.",
1354 old_size, new_size);
1358 /* zlib thinks this is OK, so lets do the same. */
1359 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1364 /* It seems that zlib did something weird. */
1365 log_error(LOG_LEVEL_ERROR,
1366 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1367 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1368 csp->iob->eod, csp->iob->buf + csp->iob->size);
1369 return JB_ERR_COMPRESS;
1375 #endif /* defined(FEATURE_ZLIB) */
1378 /*********************************************************************
1380 * Function : get_header
1382 * Description : This (odd) routine will parse the csp->iob
1385 * 1 : csp = Current client state (buffers, headers, etc...)
1387 * Returns : Any one of the following:
1389 * 1) a pointer to a dynamically allocated string that contains a header line
1390 * 2) NULL indicating that the end of the header was reached
1391 * 3) "" indicating that the end of the iob was reached before finding
1392 * a complete header line.
1394 *********************************************************************/
1395 char *get_header(struct client_state *csp)
1401 if ((iob->cur == NULL)
1402 || ((p = strchr(iob->cur, '\n')) == NULL))
1404 return(""); /* couldn't find a complete header */
1409 ret = strdup(iob->cur);
1412 /* FIXME No way to handle error properly */
1413 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1418 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1420 /* is this a blank line (i.e. the end of the header) ? */
1432 /*********************************************************************
1434 * Function : get_header_value
1436 * Description : Get the value of a given header from a chained list
1437 * of header lines or return NULL if no such header is
1438 * present in the list.
1441 * 1 : header_list = pointer to list
1442 * 2 : header_name = string with name of header to look for.
1443 * Trailing colon required, capitalization
1446 * Returns : NULL if not found, else value of header
1448 *********************************************************************/
1449 char *get_header_value(const struct list *header_list, const char *header_name)
1451 struct list_entry *cur_entry;
1455 assert(header_list);
1456 assert(header_name);
1457 length = strlen(header_name);
1459 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1463 if (!strncmpic(cur_entry->str, header_name, length))
1466 * Found: return pointer to start of value
1468 ret = (char *) (cur_entry->str + length);
1469 while (*ret && ijb_isspace(*ret)) ret++;
1483 /*********************************************************************
1485 * Function : scan_headers
1487 * Description : Scans headers, applies tags and updates action bits.
1490 * 1 : csp = Current client state (buffers, headers, etc...)
1492 * Returns : JB_ERR_OK
1494 *********************************************************************/
1495 static jb_err scan_headers(struct client_state *csp)
1497 struct list_entry *h; /* Header */
1498 jb_err err = JB_ERR_OK;
1500 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1502 /* Header crunch()ed in previous run? -> ignore */
1503 if (h->str == NULL) continue;
1504 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1505 err = header_tagger(csp, h->str);
1512 /*********************************************************************
1516 * Description : add, delete or modify lines in the HTTP header streams.
1517 * On entry, it receives a linked list of headers space
1518 * that was allocated dynamically (both the list nodes
1519 * and the header contents).
1521 * As a side effect it frees the space used by the original
1524 * XXX: should be split to remove the first_run hack.
1527 * 1 : pats = list of patterns to match against headers
1528 * 2 : more_headers = list of functions to add more
1529 * headers (client or server)
1530 * 3 : csp = Current client state (buffers, headers, etc...)
1532 * Returns : JB_ERR_OK in case off success, or
1533 * JB_ERR_MEMORY on out-of-memory error.
1535 *********************************************************************/
1536 jb_err sed(const struct parsers pats[],
1537 const add_header_func_ptr more_headers[],
1538 struct client_state *csp)
1540 struct list_entry *p;
1541 const struct parsers *v;
1542 const add_header_func_ptr *f;
1543 jb_err err = JB_ERR_OK;
1547 * If filtering is enabled, sed is run twice,
1548 * but most of the work needs to be done only once.
1550 first_run = (more_headers != NULL ) ? 1 : 0;
1552 if (first_run) /* Parse and print */
1556 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1558 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1560 /* Header crunch()ed in previous run? -> ignore */
1561 if (p->str == NULL) continue;
1563 /* Does the current parser handle this header? */
1564 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1566 err = v->parser(csp, (char **)&(p->str));
1570 /* place any additional headers on the csp->headers list */
1571 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1576 else /* Parse only */
1579 * The second run is only needed if the body was modified
1580 * and the content-lenght has changed.
1582 if (strncmpic(csp->http->cmd, "HEAD", 4))
1584 /*XXX: Code duplication */
1585 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1587 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1589 /* Header crunch()ed in previous run? -> ignore */
1590 if (p->str == NULL) continue;
1592 /* Does the current parser handle this header? */
1593 if (strncmpic(p->str, v->str, v->len) == 0)
1595 err = v->parser(csp, (char **)&(p->str));
1607 /*********************************************************************
1609 * Function : header_tagger
1611 * Description : Executes all text substitutions from applying
1612 * tag actions and saves the result as tag.
1614 * XXX: Shares enough code with filter_header() and
1615 * pcrs_filter_response() to warrant some helper functions.
1618 * 1 : csp = Current client state (buffers, headers, etc...)
1619 * 2 : header = Header that is used as tagger input
1621 * Returns : JB_ERR_OK on success and always succeeds
1623 *********************************************************************/
1624 static jb_err header_tagger(struct client_state *csp, char *header)
1626 int wanted_filter_type;
1627 int multi_action_index;
1631 struct file_list *fl;
1632 struct re_filterfile_spec *b;
1633 struct list_entry *tag_name;
1635 int found_filters = 0;
1636 const size_t header_length = strlen(header);
1638 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1640 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1641 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1645 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1646 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1649 /* Check if there are any filters */
1650 for (i = 0; i < MAX_AF_FILES; i++)
1663 if (0 == found_filters)
1665 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1669 for (i = 0; i < MAX_AF_FILES; i++)
1672 if ((NULL == fl) || (NULL == fl->f))
1675 * Either there are no filter files
1676 * left, or this filter file just
1677 * contains no valid filters.
1679 * Continue to be sure we don't miss
1680 * valid filter files that are chained
1681 * after empty or invalid ones.
1686 /* For all filters, */
1687 for (b = fl->f; b; b = b->next)
1689 if (b->type != wanted_filter_type)
1691 /* skip the ones we don't care about, */
1694 /* leaving only taggers that could apply, of which we use the ones, */
1695 for (tag_name = csp->action->multi[multi_action_index]->first;
1696 NULL != tag_name; tag_name = tag_name->next)
1698 /* that do apply, and */
1699 if (strcmp(b->name, tag_name->str) == 0)
1701 char *modified_tag = NULL;
1703 size_t size = header_length;
1704 pcrs_job *joblist = b->joblist;
1706 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1708 if (NULL == joblist)
1710 log_error(LOG_LEVEL_RE_FILTER,
1711 "Tagger %s has empty joblist. Nothing to do.", b->name);
1715 /* execute their pcrs_joblist on the header. */
1716 for (job = joblist; NULL != job; job = job->next)
1718 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1722 /* Success, continue with the modified version. */
1731 /* Tagger doesn't match */
1734 /* Regex failure, log it but continue anyway. */
1735 log_error(LOG_LEVEL_ERROR,
1736 "Problems with tagger \'%s\' and header \'%s\': %s",
1737 b->name, *header, pcrs_strerror(hits));
1739 freez(modified_tag);
1743 if (b->dynamic) pcrs_free_joblist(joblist);
1745 /* If this tagger matched */
1751 * There is to technical limitation which makes
1752 * it impossible to use empty tags, but I assume
1753 * no one would do it intentionally.
1756 log_error(LOG_LEVEL_INFO,
1757 "Tagger \'%s\' created an empty tag. Ignored.",
1762 if (!list_contains_item(csp->tags, tag))
1764 if (JB_ERR_OK != enlist(csp->tags, tag))
1766 log_error(LOG_LEVEL_ERROR,
1767 "Insufficient memory to add tag \'%s\', "
1768 "based on tagger \'%s\' and header \'%s\'",
1769 tag, b->name, *header);
1773 char *action_message;
1775 * update the action bits right away, to make
1776 * tagging based on tags set by earlier taggers
1777 * of the same kind possible.
1779 if (update_action_bits_for_tag(csp, tag))
1781 action_message = "Action bits updated accordingly.";
1785 action_message = "No action bits update necessary.";
1788 log_error(LOG_LEVEL_HEADER,
1789 "Tagger \'%s\' added tag \'%s\'. %s",
1790 b->name, tag, action_message);
1795 /* XXX: Is this log-worthy? */
1796 log_error(LOG_LEVEL_HEADER,
1797 "Tagger \'%s\' didn't add tag \'%s\'. "
1798 "Tag already present", b->name, tag);
1801 } /* if the tagger matched */
1802 } /* if the tagger applies */
1803 } /* for every tagger that could apply */
1804 } /* for all filters */
1805 } /* for all filter files */
1810 /* here begins the family of parser functions that reformat header lines */
1812 /*********************************************************************
1814 * Function : filter_header
1816 * Description : Executes all text substitutions from all applying
1817 * +(server|client)-header-filter actions on the header.
1818 * Most of the code was copied from pcrs_filter_response,
1819 * including the rather short variable names
1822 * 1 : csp = Current client state (buffers, headers, etc...)
1823 * 2 : header = On input, pointer to header to modify.
1824 * On output, pointer to the modified header, or NULL
1825 * to remove the header. This function frees the
1826 * original string if necessary.
1828 * Returns : JB_ERR_OK on success and always succeeds
1830 *********************************************************************/
1831 static jb_err filter_header(struct client_state *csp, char **header)
1835 size_t size = strlen(*header);
1837 char *newheader = NULL;
1840 struct file_list *fl;
1841 struct re_filterfile_spec *b;
1842 struct list_entry *filtername;
1844 int i, found_filters = 0;
1845 int wanted_filter_type;
1846 int multi_action_index;
1848 if (csp->flags & CSP_FLAG_NO_FILTERING)
1853 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1855 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1856 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1860 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1861 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1865 * Need to check the set of re_filterfiles...
1867 for (i = 0; i < MAX_AF_FILES; i++)
1880 if (0 == found_filters)
1882 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1886 for (i = 0; i < MAX_AF_FILES; i++)
1889 if ((NULL == fl) || (NULL == fl->f))
1892 * Either there are no filter files
1893 * left, or this filter file just
1894 * contains no valid filters.
1896 * Continue to be sure we don't miss
1897 * valid filter files that are chained
1898 * after empty or invalid ones.
1903 * For all applying +filter actions, look if a filter by that
1904 * name exists and if yes, execute its pcrs_joblist on the
1907 for (b = fl->f; b; b = b->next)
1909 if (b->type != wanted_filter_type)
1911 /* Skip other filter types */
1915 for (filtername = csp->action->multi[multi_action_index]->first;
1916 filtername ; filtername = filtername->next)
1918 if (strcmp(b->name, filtername->str) == 0)
1920 int current_hits = 0;
1921 pcrs_job *joblist = b->joblist;
1923 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1925 if (NULL == joblist)
1927 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1931 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1932 *header, size, b->name);
1934 /* Apply all jobs from the joblist */
1935 for (job = joblist; NULL != job; job = job->next)
1937 matches = pcrs_execute(job, *header, size, &newheader, &size);
1940 current_hits += matches;
1941 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1943 *header = newheader;
1945 else if ( 0 == matches )
1947 /* Filter doesn't change header */
1953 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1954 *header, b->name, pcrs_strerror(matches));
1955 if (newheader != NULL)
1957 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1963 if (b->dynamic) pcrs_free_joblist(joblist);
1965 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1966 hits += current_hits;
1973 * Additionally checking for hits is important because if
1974 * the continue hack is triggered, server headers can
1975 * arrive empty to separate multiple heads from each other.
1977 if ((0 == size) && hits)
1979 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1987 /*********************************************************************
1989 * Function : connection
1991 * Description : Makes sure that the value of the Connection: header
1992 * is "close" and signals connection_close_adder
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * 2 : header = On input, pointer to header to modify.
1998 * On output, pointer to the modified header, or NULL
1999 * to remove the header. This function frees the
2000 * original string if necessary.
2002 * Returns : JB_ERR_OK on success, or
2003 * JB_ERR_MEMORY on out-of-memory error.
2005 *********************************************************************/
2006 static jb_err connection(struct client_state *csp, char **header)
2008 char *old_header = *header;
2010 /* Do we have a 'Connection: close' header? */
2011 if (strcmpic(*header, "Connection: close"))
2013 /* No, create one */
2014 *header = strdup("Connection: close");
2017 return JB_ERR_MEMORY;
2019 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2023 /* Signal connection_close_adder() to return early. */
2024 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2026 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2030 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2037 /*********************************************************************
2039 * Function : crumble
2041 * Description : This is called if a header matches a pattern to "crunch"
2044 * 1 : csp = Current client state (buffers, headers, etc...)
2045 * 2 : header = On input, pointer to header to modify.
2046 * On output, pointer to the modified header, or NULL
2047 * to remove the header. This function frees the
2048 * original string if necessary.
2050 * Returns : JB_ERR_OK on success, or
2051 * JB_ERR_MEMORY on out-of-memory error.
2053 *********************************************************************/
2054 static jb_err crumble(struct client_state *csp, char **header)
2056 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2062 /*********************************************************************
2064 * Function : crunch_server_header
2066 * Description : Crunch server header if it matches a string supplied by the
2067 * user. Called from `sed'.
2070 * 1 : csp = Current client state (buffers, headers, etc...)
2071 * 2 : header = On input, pointer to header to modify.
2072 * On output, pointer to the modified header, or NULL
2073 * to remove the header. This function frees the
2074 * original string if necessary.
2076 * Returns : JB_ERR_OK on success and always succeeds
2078 *********************************************************************/
2079 static jb_err crunch_server_header(struct client_state *csp, char **header)
2081 const char *crunch_pattern;
2083 /* Do we feel like crunching? */
2084 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2086 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2088 /* Is the current header the lucky one? */
2089 if (strstr(*header, crunch_pattern))
2091 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2100 /*********************************************************************
2102 * Function : server_content_type
2104 * Description : Set the content-type for filterable types (text/.*,
2105 * .*xml.*, javascript and image/gif) unless filtering has been
2106 * forbidden (CT_TABOO) while parsing earlier headers.
2107 * NOTE: Since text/plain is commonly used by web servers
2108 * for files whose correct type is unknown, we don't
2109 * set CT_TEXT for it.
2112 * 1 : csp = Current client state (buffers, headers, etc...)
2113 * 2 : header = On input, pointer to header to modify.
2114 * On output, pointer to the modified header, or NULL
2115 * to remove the header. This function frees the
2116 * original string if necessary.
2118 * Returns : JB_ERR_OK on success, or
2119 * JB_ERR_MEMORY on out-of-memory error.
2121 *********************************************************************/
2122 static jb_err server_content_type(struct client_state *csp, char **header)
2124 /* Remove header if it isn't the first Content-Type header */
2125 if ((csp->content_type & CT_DECLARED))
2128 * Another, slightly slower, way to see if
2129 * we already parsed another Content-Type header.
2131 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2133 log_error(LOG_LEVEL_ERROR,
2134 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2142 * Signal that the Content-Type has been set.
2144 csp->content_type |= CT_DECLARED;
2146 if (!(csp->content_type & CT_TABOO))
2148 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2149 || strstr(*header, "xml")
2150 || strstr(*header, "application/x-javascript"))
2152 csp->content_type |= CT_TEXT;
2154 else if (strstr(*header, " image/gif"))
2156 csp->content_type |= CT_GIF;
2158 else if (strstr(*header, " image/jpeg"))
2160 csp->content_type |= CT_JPEG;
2165 * Are we messing with the content type?
2167 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2170 * Make sure the user doesn't accidently
2171 * change the content type of binary documents.
2173 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2176 *header = strdup("Content-Type: ");
2177 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2181 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2182 return JB_ERR_MEMORY;
2184 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2188 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2189 "Enable force-text-mode if you know what you're doing.", *header);
2197 /*********************************************************************
2199 * Function : server_transfer_coding
2201 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2202 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2203 * - Remove header if body was chunked but has been
2204 * de-chunked for filtering.
2207 * 1 : csp = Current client state (buffers, headers, etc...)
2208 * 2 : header = On input, pointer to header to modify.
2209 * On output, pointer to the modified header, or NULL
2210 * to remove the header. This function frees the
2211 * original string if necessary.
2213 * Returns : JB_ERR_OK on success, or
2214 * JB_ERR_MEMORY on out-of-memory error.
2216 *********************************************************************/
2217 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2220 * Turn off pcrs and gif filtering if body compressed
2222 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2226 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2228 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2229 csp->http->cmd, *header);
2230 #endif /* def FEATURE_ZLIB */
2231 csp->content_type = CT_TABOO;
2235 * Raise flag if body chunked
2237 if (strstr(*header, "chunked"))
2239 csp->flags |= CSP_FLAG_CHUNKED;
2242 * If the body was modified, it has been de-chunked first
2243 * and the header must be removed.
2245 * FIXME: If there is more than one transfer encoding,
2246 * only the "chunked" part should be removed here.
2248 if (csp->flags & CSP_FLAG_MODIFIED)
2250 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2259 /*********************************************************************
2261 * Function : server_content_encoding
2263 * Description : This function is run twice for each request,
2264 * unless FEATURE_ZLIB and filtering are disabled.
2266 * The first run is used to check if the content
2267 * is compressed, if FEATURE_ZLIB is disabled
2268 * filtering is then disabled as well, if FEATURE_ZLIB
2269 * is enabled the content is marked for decompression.
2271 * The second run is used to remove the Content-Encoding
2272 * header if the decompression was successful.
2275 * 1 : csp = Current client state (buffers, headers, etc...)
2276 * 2 : header = On input, pointer to header to modify.
2277 * On output, pointer to the modified header, or NULL
2278 * to remove the header. This function frees the
2279 * original string if necessary.
2281 * Returns : JB_ERR_OK on success, or
2282 * JB_ERR_MEMORY on out-of-memory error.
2284 *********************************************************************/
2285 static jb_err server_content_encoding(struct client_state *csp, char **header)
2288 if ((csp->flags & CSP_FLAG_MODIFIED)
2289 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2292 * We successfully decompressed the content,
2293 * and have to clean the header now, so the
2294 * client no longer expects compressed data..
2296 * XXX: There is a difference between cleaning
2297 * and removing it completely.
2299 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2302 else if (strstr(*header, "gzip"))
2304 /* Mark for gzip decompression */
2305 csp->content_type |= CT_GZIP;
2307 else if (strstr(*header, "deflate"))
2309 /* Mark for zlib decompression */
2310 csp->content_type |= CT_DEFLATE;
2312 else if (strstr(*header, "compress"))
2315 * We can't decompress this; therefore we can't filter
2318 csp->content_type |= CT_TABOO;
2320 #else /* !defined(FEATURE_ZLIB) */
2321 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2324 * Body is compressed, turn off pcrs and gif filtering.
2326 csp->content_type |= CT_TABOO;
2329 * Log a warning if the user expects the content to be filtered.
2331 if ((csp->rlist != NULL) &&
2332 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2334 log_error(LOG_LEVEL_INFO,
2335 "Compressed content detected, content filtering disabled. "
2336 "Consider recompiling Privoxy with zlib support or "
2337 "enable the prevent-compression action.");
2340 #endif /* defined(FEATURE_ZLIB) */
2347 /*********************************************************************
2349 * Function : server_content_length
2351 * Description : Adjust Content-Length header if we modified
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, or
2362 * JB_ERR_MEMORY on out-of-memory error.
2364 *********************************************************************/
2365 static jb_err server_content_length(struct client_state *csp, char **header)
2367 const size_t max_header_length = 80;
2369 /* Regenerate header if the content was modified. */
2370 if (csp->flags & CSP_FLAG_MODIFIED)
2373 *header = (char *) zalloc(max_header_length);
2374 if (*header == NULL)
2376 return JB_ERR_MEMORY;
2379 snprintf(*header, max_header_length, "Content-Length: %d",
2380 (int)csp->content_length);
2381 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2382 (int)csp->content_length);
2389 /*********************************************************************
2391 * Function : server_content_md5
2393 * Description : Crumble any Content-MD5 headers if the document was
2394 * modified. FIXME: Should we re-compute instead?
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_md5(struct client_state *csp, char **header)
2409 if (csp->flags & CSP_FLAG_MODIFIED)
2411 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2419 /*********************************************************************
2421 * Function : server_content_disposition
2423 * Description : If enabled, blocks or modifies the "content-disposition" header.
2424 * Called from `sed'.
2427 * 1 : csp = Current client state (buffers, headers, etc...)
2428 * 2 : header = On input, pointer to header to modify.
2429 * On output, pointer to the modified header, or NULL
2430 * to remove the header. This function frees the
2431 * original string if necessary.
2433 * Returns : JB_ERR_OK on success, or
2434 * JB_ERR_MEMORY on out-of-memory error.
2436 *********************************************************************/
2437 static jb_err server_content_disposition(struct client_state *csp, char **header)
2442 * Are we messing with the content-disposition header?
2444 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2450 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2452 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2455 * Blocking content-disposition header
2457 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2464 * Replacing content-disposition header
2467 *header = strdup("content-disposition: ");
2468 string_append(header, newval);
2470 if (*header == NULL)
2472 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2476 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2479 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2483 /*********************************************************************
2485 * Function : server_last_modified
2487 * Description : Changes Last-Modified header to the actual date
2488 * to help hide-if-modified-since.
2489 * Called from `sed'.
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2493 * 2 : header = On input, pointer to header to modify.
2494 * On output, pointer to the modified header, or NULL
2495 * to remove the header. This function frees the
2496 * original string if necessary.
2498 * Returns : JB_ERR_OK on success, or
2499 * JB_ERR_MEMORY on out-of-memory error.
2501 *********************************************************************/
2502 static jb_err server_last_modified(struct client_state *csp, char **header)
2505 char buf[BUFFER_SIZE];
2508 #ifdef HAVE_GMTIME_R
2511 struct tm *timeptr = NULL;
2512 time_t now, last_modified;
2514 long int days, hours, minutes, seconds;
2517 * Are we messing with the Last-Modified header?
2519 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2525 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2527 if (0 == strcmpic(newval, "block") )
2530 * Blocking Last-Modified header. Useless but why not.
2532 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2536 else if (0 == strcmpic(newval, "reset-to-request-time"))
2539 * Setting Last-Modified Header to now.
2541 get_http_time(0, buf);
2543 *header = strdup("Last-Modified: ");
2544 string_append(header, buf);
2546 if (*header == NULL)
2548 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2552 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2555 else if (0 == strcmpic(newval, "randomize"))
2557 const char *header_time = *header + sizeof("Last-Modified:");
2559 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2561 #ifdef HAVE_GMTIME_R
2562 timeptr = gmtime_r(&now, &gmt);
2563 #elif FEATURE_PTHREAD
2564 pthread_mutex_lock(&gmtime_mutex);
2565 timeptr = gmtime(&now);
2566 pthread_mutex_unlock(&gmtime_mutex);
2568 timeptr = gmtime(&now);
2570 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2572 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2577 rtime = (long int)difftime(now, last_modified);
2580 rtime = pick_from_range(rtime);
2581 last_modified += rtime;
2582 #ifdef HAVE_GMTIME_R
2583 timeptr = gmtime_r(&last_modified, &gmt);
2584 #elif FEATURE_PTHREAD
2585 pthread_mutex_lock(&gmtime_mutex);
2586 timeptr = gmtime(&last_modified);
2587 pthread_mutex_unlock(&gmtime_mutex);
2589 timeptr = gmtime(&last_modified);
2591 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2593 *header = strdup("Last-Modified: ");
2594 string_append(header, newheader);
2596 if (*header == NULL)
2598 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2599 return JB_ERR_MEMORY;
2602 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2604 days = rtime / (3600 * 24);
2605 hours = rtime / 3600 % 24;
2606 minutes = rtime / 60 % 60;
2607 seconds = rtime % 60;
2609 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2610 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2611 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2616 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2625 /*********************************************************************
2627 * Function : client_accept_encoding
2629 * Description : Rewrite the client's Accept-Encoding header so that
2630 * if doesn't allow compression, if the action applies.
2631 * Note: For HTTP/1.0 the absence of the header is enough.
2634 * 1 : csp = Current client state (buffers, headers, etc...)
2635 * 2 : header = On input, pointer to header to modify.
2636 * On output, pointer to the modified header, or NULL
2637 * to remove the header. This function frees the
2638 * original string if necessary.
2640 * Returns : JB_ERR_OK on success, or
2641 * JB_ERR_MEMORY on out-of-memory error.
2643 *********************************************************************/
2644 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2646 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2648 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2652 /* Temporarily disable the correct behaviour to
2653 * work around a PHP bug.
2655 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2657 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2658 * if (*header == NULL)
2660 * return JB_ERR_MEMORY;
2671 /*********************************************************************
2673 * Function : client_te
2675 * Description : Rewrite the client's TE header so that
2676 * if doesn't allow compression, if the action applies.
2679 * 1 : csp = Current client state (buffers, headers, etc...)
2680 * 2 : header = On input, pointer to header to modify.
2681 * On output, pointer to the modified header, or NULL
2682 * to remove the header. This function frees the
2683 * original string if necessary.
2685 * Returns : JB_ERR_OK on success, or
2686 * JB_ERR_MEMORY on out-of-memory error.
2688 *********************************************************************/
2689 static jb_err client_te(struct client_state *csp, char **header)
2691 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2694 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2701 /*********************************************************************
2703 * Function : client_referrer
2705 * Description : Handle the "referer" config setting properly.
2706 * Called from `sed'.
2709 * 1 : csp = Current client state (buffers, headers, etc...)
2710 * 2 : header = On input, pointer to header to modify.
2711 * On output, pointer to the modified header, or NULL
2712 * to remove the header. This function frees the
2713 * original string if necessary.
2715 * Returns : JB_ERR_OK on success, or
2716 * JB_ERR_MEMORY on out-of-memory error.
2718 *********************************************************************/
2719 static jb_err client_referrer(struct client_state *csp, char **header)
2721 const char *parameter;
2722 /* booleans for parameters we have to check multiple times */
2723 int parameter_conditional_block;
2724 int parameter_conditional_forge;
2726 #ifdef FEATURE_FORCE_LOAD
2728 * Since the referrer can include the prefix even
2729 * if the request itself is non-forced, we must
2730 * clean it unconditionally.
2732 * XXX: strclean is too broad
2734 strclean(*header, FORCE_PREFIX);
2735 #endif /* def FEATURE_FORCE_LOAD */
2737 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2739 /* Nothing left to do */
2743 parameter = csp->action->string[ACTION_STRING_REFERER];
2744 assert(parameter != NULL);
2745 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2746 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2748 if (!parameter_conditional_block && !parameter_conditional_forge)
2751 * As conditional-block and conditional-forge are the only
2752 * parameters that rely on the original referrer, we can
2753 * remove it now for all the others.
2758 if (0 == strcmpic(parameter, "block"))
2760 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2763 else if (parameter_conditional_block || parameter_conditional_forge)
2765 return handle_conditional_hide_referrer_parameter(header,
2766 csp->http->hostport, parameter_conditional_block);
2768 else if (0 == strcmpic(parameter, "forge"))
2770 return create_forged_referrer(header, csp->http->hostport);
2774 /* interpret parameter as user-supplied referer to fake */
2775 return create_fake_referrer(header, parameter);
2780 /*********************************************************************
2782 * Function : client_accept_language
2784 * Description : Handle the "Accept-Language" config setting properly.
2785 * Called from `sed'.
2788 * 1 : csp = Current client state (buffers, headers, etc...)
2789 * 2 : header = On input, pointer to header to modify.
2790 * On output, pointer to the modified header, or NULL
2791 * to remove the header. This function frees the
2792 * original string if necessary.
2794 * Returns : JB_ERR_OK on success, or
2795 * JB_ERR_MEMORY on out-of-memory error.
2797 *********************************************************************/
2798 static jb_err client_accept_language(struct client_state *csp, char **header)
2803 * Are we messing with the Accept-Language?
2805 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2807 /*I don't think so*/
2811 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2813 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2816 * Blocking Accept-Language header
2818 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2825 * Replacing Accept-Language header
2828 *header = strdup("Accept-Language: ");
2829 string_append(header, newval);
2831 if (*header == NULL)
2833 log_error(LOG_LEVEL_ERROR,
2834 "Insufficent memory. Accept-Language header crunched without replacement.");
2838 log_error(LOG_LEVEL_HEADER,
2839 "Accept-Language header crunched and replaced with: %s", *header);
2842 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2846 /*********************************************************************
2848 * Function : crunch_client_header
2850 * Description : Crunch client header if it matches a string supplied by the
2851 * user. Called from `sed'.
2854 * 1 : csp = Current client state (buffers, headers, etc...)
2855 * 2 : header = On input, pointer to header to modify.
2856 * On output, pointer to the modified header, or NULL
2857 * to remove the header. This function frees the
2858 * original string if necessary.
2860 * Returns : JB_ERR_OK on success and always succeeds
2862 *********************************************************************/
2863 static jb_err crunch_client_header(struct client_state *csp, char **header)
2865 const char *crunch_pattern;
2867 /* Do we feel like crunching? */
2868 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2870 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2872 /* Is the current header the lucky one? */
2873 if (strstr(*header, crunch_pattern))
2875 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2883 /*********************************************************************
2885 * Function : client_uagent
2887 * Description : Handle the "user-agent" config setting properly
2888 * and remember its original value to enable browser
2889 * bug workarounds. Called from `sed'.
2892 * 1 : csp = Current client state (buffers, headers, etc...)
2893 * 2 : header = On input, pointer to header to modify.
2894 * On output, pointer to the modified header, or NULL
2895 * to remove the header. This function frees the
2896 * original string if necessary.
2898 * Returns : JB_ERR_OK on success, or
2899 * JB_ERR_MEMORY on out-of-memory error.
2901 *********************************************************************/
2902 static jb_err client_uagent(struct client_state *csp, char **header)
2906 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2911 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2918 *header = strdup("User-Agent: ");
2919 string_append(header, newval);
2921 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2923 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2927 /*********************************************************************
2929 * Function : client_ua
2931 * Description : Handle "ua-" headers properly. Called from `sed'.
2934 * 1 : csp = Current client state (buffers, headers, etc...)
2935 * 2 : header = On input, pointer to header to modify.
2936 * On output, pointer to the modified header, or NULL
2937 * to remove the header. This function frees the
2938 * original string if necessary.
2940 * Returns : JB_ERR_OK on success, or
2941 * JB_ERR_MEMORY on out-of-memory error.
2943 *********************************************************************/
2944 static jb_err client_ua(struct client_state *csp, char **header)
2946 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2948 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2956 /*********************************************************************
2958 * Function : client_from
2960 * Description : Handle the "from" config setting properly.
2961 * Called from `sed'.
2964 * 1 : csp = Current client state (buffers, headers, etc...)
2965 * 2 : header = On input, pointer to header to modify.
2966 * On output, pointer to the modified header, or NULL
2967 * to remove the header. This function frees the
2968 * original string if necessary.
2970 * Returns : JB_ERR_OK on success, or
2971 * JB_ERR_MEMORY on out-of-memory error.
2973 *********************************************************************/
2974 static jb_err client_from(struct client_state *csp, char **header)
2978 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2985 newval = csp->action->string[ACTION_STRING_FROM];
2988 * Are we blocking the e-mail address?
2990 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2992 log_error(LOG_LEVEL_HEADER, "crunched From!");
2996 log_error(LOG_LEVEL_HEADER, " modified");
2998 *header = strdup("From: ");
2999 string_append(header, newval);
3001 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3005 /*********************************************************************
3007 * Function : client_send_cookie
3009 * Description : Crunches the "cookie" header if necessary.
3010 * Called from `sed'.
3012 * XXX: Stupid name, doesn't send squat.
3015 * 1 : csp = Current client state (buffers, headers, etc...)
3016 * 2 : header = On input, pointer to header to modify.
3017 * On output, pointer to the modified header, or NULL
3018 * to remove the header. This function frees the
3019 * original string if necessary.
3021 * Returns : JB_ERR_OK on success, or
3022 * JB_ERR_MEMORY on out-of-memory error.
3024 *********************************************************************/
3025 static jb_err client_send_cookie(struct client_state *csp, char **header)
3027 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3029 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3037 /*********************************************************************
3039 * Function : client_x_forwarded
3041 * Description : Handle the "x-forwarded-for" config setting properly,
3042 * also used in the add_client_headers list. Called from `sed'.
3045 * 1 : csp = Current client state (buffers, headers, etc...)
3046 * 2 : header = On input, pointer to header to modify.
3047 * On output, pointer to the modified header, or NULL
3048 * to remove the header. This function frees the
3049 * original string if necessary.
3051 * Returns : JB_ERR_OK on success, or
3052 * JB_ERR_MEMORY on out-of-memory error.
3054 *********************************************************************/
3055 jb_err client_x_forwarded(struct client_state *csp, char **header)
3057 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3059 /* Save it so we can re-add it later */
3060 freez(csp->x_forwarded);
3061 csp->x_forwarded = *header;
3064 * Always set *header = NULL, since this information
3065 * will be sent at the end of the header.
3072 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3079 /*********************************************************************
3081 * Function : client_max_forwards
3083 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3084 * from the value of the Max-Forwards header field.
3087 * 1 : csp = Current client state (buffers, headers, etc...)
3088 * 2 : header = On input, pointer to header to modify.
3089 * On output, pointer to the modified header, or NULL
3090 * to remove the header. This function frees the
3091 * original string if necessary.
3093 * Returns : JB_ERR_OK on success, or
3094 * JB_ERR_MEMORY on out-of-memory error.
3096 *********************************************************************/
3097 static jb_err client_max_forwards(struct client_state *csp, char **header)
3101 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3102 (0 == strcmpic(csp->http->gpc, "options")))
3104 assert(*(*header+12) == ':');
3105 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3107 if (max_forwards > 0)
3109 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3110 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3111 csp->http->gpc, max_forwards);
3113 else if (max_forwards < 0)
3115 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3121 * Not supposed to be reached. direct_response() which
3122 * was already called earlier in chat() should have
3123 * intercepted the request.
3125 log_error(LOG_LEVEL_ERROR,
3126 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3127 assert(max_forwards != 0);
3132 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3141 /*********************************************************************
3143 * Function : client_host
3145 * Description : If the request URI did not contain host and
3146 * port information, parse and evaluate the Host
3149 * Also, kill ill-formed HOST: headers as sent by
3150 * Apple's iTunes software when used with a proxy.
3153 * 1 : csp = Current client state (buffers, headers, etc...)
3154 * 2 : header = On input, pointer to header to modify.
3155 * On output, pointer to the modified header, or NULL
3156 * to remove the header. This function frees the
3157 * original string if necessary.
3159 * Returns : JB_ERR_OK on success, or
3160 * JB_ERR_MEMORY on out-of-memory error.
3162 *********************************************************************/
3163 static jb_err client_host(struct client_state *csp, char **header)
3168 * If the header field name is all upper-case, chances are that it's
3169 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3170 * not a problem -- they are regenerated later.
3172 if ((*header)[1] == 'O')
3174 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3179 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3180 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3183 if (NULL == (p = strdup((*header)+6)))
3185 return JB_ERR_MEMORY;
3188 if (NULL == (q = strdup(p)))
3191 return JB_ERR_MEMORY;
3194 freez(csp->http->hostport);
3195 csp->http->hostport = p;
3196 freez(csp->http->host);
3197 csp->http->host = q;
3198 q = strchr(csp->http->host, ':');
3201 /* Terminate hostname and evaluate port string */
3203 csp->http->port = atoi(q);
3207 csp->http->port = csp->http->ssl ? 443 : 80;
3210 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3211 csp->http->hostport, csp->http->host, csp->http->port);
3214 /* Signal client_host_adder() to return right away */
3215 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3221 /*********************************************************************
3223 * Function : client_if_modified_since
3225 * Description : Remove or modify the If-Modified-Since header.
3228 * 1 : csp = Current client state (buffers, headers, etc...)
3229 * 2 : header = On input, pointer to header to modify.
3230 * On output, pointer to the modified header, or NULL
3231 * to remove the header. This function frees the
3232 * original string if necessary.
3234 * Returns : JB_ERR_OK on success, or
3235 * JB_ERR_MEMORY on out-of-memory error.
3237 *********************************************************************/
3238 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3241 #ifdef HAVE_GMTIME_R
3244 struct tm *timeptr = NULL;
3248 long int hours, minutes, seconds;
3252 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3255 * The client got an error message because of a temporary problem,
3256 * the problem is gone and the client now tries to revalidate our
3257 * error message on the real server. The revalidation would always
3258 * end with the transmission of the whole document and there is
3259 * no need to expose the bogus If-Modified-Since header.
3261 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3264 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3266 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3268 if ((0 == strcmpic(newval, "block")))
3270 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3273 else /* add random value */
3275 const char *header_time = *header + sizeof("If-Modified-Since:");
3277 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3279 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3284 rtime = strtol(newval, &endptr, 0);
3287 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3288 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3295 rtime = pick_from_range(rtime);
3299 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3302 tm += rtime * (negative ? -1 : 1);
3303 #ifdef HAVE_GMTIME_R
3304 timeptr = gmtime_r(&tm, &gmt);
3305 #elif FEATURE_PTHREAD
3306 pthread_mutex_lock(&gmtime_mutex);
3307 timeptr = gmtime(&tm);
3308 pthread_mutex_unlock(&gmtime_mutex);
3310 timeptr = gmtime(&tm);
3312 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3315 *header = strdup("If-Modified-Since: ");
3316 string_append(header, newheader);
3318 if (*header == NULL)
3320 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3321 return JB_ERR_MEMORY;
3324 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3326 hours = rtime / 3600;
3327 minutes = rtime / 60 % 60;
3328 seconds = rtime % 60;
3330 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3331 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3332 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3342 /*********************************************************************
3344 * Function : client_if_none_match
3346 * Description : Remove the If-None-Match header.
3349 * 1 : csp = Current client state (buffers, headers, etc...)
3350 * 2 : header = On input, pointer to header to modify.
3351 * On output, pointer to the modified header, or NULL
3352 * to remove the header. This function frees the
3353 * original string if necessary.
3355 * Returns : JB_ERR_OK on success, or
3356 * JB_ERR_MEMORY on out-of-memory error.
3358 *********************************************************************/
3359 static jb_err client_if_none_match(struct client_state *csp, char **header)
3361 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3363 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3371 /*********************************************************************
3373 * Function : client_x_filter
3375 * Description : Disables filtering if the client set "X-Filter: No".
3376 * Called from `sed'.
3379 * 1 : csp = Current client state (buffers, headers, etc...)
3380 * 2 : header = On input, pointer to header to modify.
3381 * On output, pointer to the modified header, or NULL
3382 * to remove the header. This function frees the
3383 * original string if necessary.
3385 * Returns : JB_ERR_OK on success
3387 *********************************************************************/
3388 jb_err client_x_filter(struct client_state *csp, char **header)
3390 if ( 0 == strcmpic(*header, "X-Filter: No"))
3392 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3394 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3398 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3400 log_error(LOG_LEVEL_HEADER,
3401 "force-text-mode overruled the client's request to fetch without filtering!");
3405 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3406 csp->flags |= CSP_FLAG_NO_FILTERING;
3407 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3409 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3416 /* the following functions add headers directly to the header list */
3418 /*********************************************************************
3420 * Function : client_host_adder
3422 * Description : Adds the Host: header field if it is missing.
3423 * Called from `sed'.
3426 * 1 : csp = Current client state (buffers, headers, etc...)
3428 * Returns : JB_ERR_OK on success, or
3429 * JB_ERR_MEMORY on out-of-memory error.
3431 *********************************************************************/
3432 static jb_err client_host_adder(struct client_state *csp)
3437 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3439 /* Header already set by the client, nothing to do. */
3443 if ( !csp->http->hostport || !*(csp->http->hostport))
3445 /* XXX: When does this happen and why is it OK? */
3446 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3451 * remove 'user:pass@' from 'proto://user:pass@host'
3453 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3459 p = csp->http->hostport;
3462 /* XXX: Just add it, we already made sure that it will be unique */
3463 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3464 err = enlist_unique_header(csp->headers, "Host", p);
3470 /*********************************************************************
3472 * Function : client_cookie_adder
3474 * Description : Used in the add_client_headers list to add "wafers".
3475 * Called from `sed'.
3478 * 1 : csp = Current client state (buffers, headers, etc...)
3480 * Returns : JB_ERR_OK on success, or
3481 * JB_ERR_MEMORY on out-of-memory error.
3483 *********************************************************************/
3484 jb_err client_cookie_adder(struct client_state *csp)
3487 struct list_entry *wafer;
3488 struct list_entry *wafer_list;
3492 * If the user has not supplied any wafers, and the user has not
3493 * told us to suppress the vanilla wafer, then send the vanilla wafer.
3495 if ((0 != (csp->action->flags & ACTION_VANILLA_WAFER))
3496 && list_is_empty(csp->action->multi[ACTION_MULTI_WAFER]))
3498 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
3501 wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3503 if (NULL == wafer_list)
3509 tmp = strdup("Cookie: ");
3511 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3513 if (wafer != wafer_list)
3515 /* As this isn't the first wafer, we need a delimiter. */
3516 string_append(&tmp, "; ");
3518 string_join(&tmp, cookie_encode(wafer->str));
3523 return JB_ERR_MEMORY;
3526 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3527 err = enlist(csp->headers, tmp);
3534 /*********************************************************************
3536 * Function : client_accept_encoding_adder
3538 * Description : Add an Accept-Encoding header to the client's request
3539 * that disables compression if the action applies, and
3540 * the header is not already there. Called from `sed'.
3541 * Note: For HTTP/1.0, the absence of the header is enough.
3544 * 1 : csp = Current client state (buffers, headers, etc...)
3546 * Returns : JB_ERR_OK on success, or
3547 * JB_ERR_MEMORY on out-of-memory error.
3549 *********************************************************************/
3550 static jb_err client_accept_encoding_adder(struct client_state *csp)
3552 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3553 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3555 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3563 /*********************************************************************
3565 * Function : client_xtra_adder
3567 * Description : Used in the add_client_headers list. Called from `sed'.
3570 * 1 : csp = Current client state (buffers, headers, etc...)
3572 * Returns : JB_ERR_OK on success, or
3573 * JB_ERR_MEMORY on out-of-memory error.
3575 *********************************************************************/
3576 static jb_err client_xtra_adder(struct client_state *csp)
3578 struct list_entry *lst;
3581 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3582 lst ; lst = lst->next)
3584 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3585 err = enlist(csp->headers, lst->str);
3597 /*********************************************************************
3599 * Function : client_x_forwarded_adder
3601 * Description : Used in the add_client_headers list. Called from `sed'.
3604 * 1 : csp = Current client state (buffers, headers, etc...)
3606 * Returns : JB_ERR_OK on success, or
3607 * JB_ERR_MEMORY on out-of-memory error.
3609 *********************************************************************/
3610 static jb_err client_x_forwarded_adder(struct client_state *csp)
3615 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3620 if (csp->x_forwarded)
3622 p = strdup(csp->x_forwarded);
3623 string_append(&p, ", ");
3627 p = strdup("X-Forwarded-For: ");
3629 string_append(&p, csp->ip_addr_str);
3633 return JB_ERR_MEMORY;
3636 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3637 err = enlist(csp->headers, p);
3644 /*********************************************************************
3646 * Function : connection_close_adder
3648 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3649 * support. Adds a "Connection: close" header to csp->headers
3650 * unless the header was already present. Called from `sed'.
3652 * FIXME: This whole function shouldn't be neccessary!
3655 * 1 : csp = Current client state (buffers, headers, etc...)
3657 * Returns : JB_ERR_OK on success, or
3658 * JB_ERR_MEMORY on out-of-memory error.
3660 *********************************************************************/
3661 static jb_err connection_close_adder(struct client_state *csp)
3663 const unsigned int flags = csp->flags;
3666 * Return right away if
3668 * - we're parsing server headers and the server header
3669 * "Connection: close" is already set, or if
3671 * - we're parsing client headers and the client header
3672 * "Connection: close" is already set.
3674 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3675 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3676 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3677 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3682 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3684 return enlist(csp->headers, "Connection: close");
3688 /*********************************************************************
3690 * Function : server_http
3692 * Description : - Save the HTTP Status into csp->http->status
3693 * - Set CT_TABOO to prevent filtering if the answer
3694 * is a partial range (HTTP status 206)
3695 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
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 on success, or
3706 * JB_ERR_MEMORY on out-of-memory error.
3708 *********************************************************************/
3709 static jb_err server_http(struct client_state *csp, char **header)
3711 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3712 if (csp->http->status == 206)
3714 csp->content_type = CT_TABOO;
3717 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3719 /* XXX: Should we do a real validity check here? */
3720 if (strlen(*header) > 8)
3723 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3728 * XXX: Should we block the request or
3729 * enlist a valid status code line here?
3731 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3732 "Downgrading to HTTP/1.0 impossible.");
3740 /*********************************************************************
3742 * Function : server_set_cookie
3744 * Description : Handle the server "cookie" header properly.
3745 * Log cookie to the jar file. Then "crunch",
3746 * accept or rewrite it to a session cookie.
3747 * Called from `sed'.
3749 * TODO: Allow the user to specify a new expiration
3750 * time to cause the cookie to expire even before the
3751 * browser is closed.
3754 * 1 : csp = Current client state (buffers, headers, etc...)
3755 * 2 : header = On input, pointer to header to modify.
3756 * On output, pointer to the modified header, or NULL
3757 * to remove the header. This function frees the
3758 * original string if necessary.
3760 * Returns : JB_ERR_OK on success, or
3761 * JB_ERR_MEMORY on out-of-memory error.
3763 *********************************************************************/
3764 static jb_err server_set_cookie(struct client_state *csp, char **header)
3771 #ifdef FEATURE_COOKIE_JAR
3772 if (csp->config->jar)
3775 * Write timestamp into outbuf.
3777 * Complex because not all OSs have tm_gmtoff or
3778 * the %z field in strftime()
3780 char tempbuf[ BUFFER_SIZE ];
3782 #ifdef HAVE_LOCALTIME_R
3783 tm_now = *localtime_r(&now, &tm_now);
3784 #elif FEATURE_PTHREAD
3785 pthread_mutex_lock(&localtime_mutex);
3786 tm_now = *localtime (&now);
3787 pthread_mutex_unlock(&localtime_mutex);
3789 tm_now = *localtime (&now);
3791 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3793 /* strlen("set-cookie: ") = 12 */
3794 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3796 #endif /* def FEATURE_COOKIE_JAR */
3798 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3800 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3803 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3805 /* Flag whether or not to log a message */
3808 /* A variable to store the tag we're working on */
3811 /* Skip "Set-Cookie:" (11 characters) in header */
3812 cur_tag = *header + 11;
3814 /* skip whitespace between "Set-Cookie:" and value */
3815 while (*cur_tag && ijb_isspace(*cur_tag))
3820 /* Loop through each tag in the cookie */
3824 char *next_tag = strchr(cur_tag, ';');
3825 if (next_tag != NULL)
3827 /* Skip the ';' character itself */
3830 /* skip whitespace ";" and start of tag */
3831 while (*next_tag && ijb_isspace(*next_tag))
3838 /* "Next tag" is the end of the string */
3839 next_tag = cur_tag + strlen(cur_tag);
3843 * Check the expiration date to see
3844 * if the cookie is still valid, if yes,
3845 * rewrite it to a session cookie.
3847 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3849 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3851 /* Did we detect the date properly? */
3852 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3855 * Nope, treat it as if it was still valid.
3857 * XXX: Should we remove the whole cookie instead?
3859 log_error(LOG_LEVEL_ERROR,
3860 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3861 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3867 * Yes. Check if the cookie is still valid.
3869 * If the cookie is already expired it's probably
3870 * a delete cookie and even if it isn't, the browser
3871 * will discard it anyway.
3875 * XXX: timegm() isn't available on some AmigaOS
3876 * versions and our replacement doesn't work.
3878 * Our options are to either:
3880 * - disable session-cookies-only completely if timegm
3883 * - to simply remove all expired tags, like it has
3884 * been done until Privoxy 3.0.6 and to live with
3885 * the consequence that it can cause login/logout
3886 * problems on servers that don't validate their
3887 * input properly, or
3889 * - to replace it with mktime in which
3890 * case there is a slight chance of valid cookies
3891 * passing as already expired.
3893 * This is the way it's currently done and it's not
3894 * as bad as it sounds. If the missing GMT offset is
3895 * enough to change the result of the expiration check
3896 * the cookie will be only valid for a few hours
3897 * anyway, which in many cases will be shorter
3898 * than a browser session.
3900 if (cookie_time - now < 0)
3902 log_error(LOG_LEVEL_HEADER,
3903 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3904 /* Just in case some clown sets more then one expiration date */
3910 * Still valid, delete expiration date by copying
3911 * the rest of the string over it.
3913 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3914 * since the behaviour of strcpy is undefined for overlapping
3917 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3919 /* That changed the header, need to issue a log message */
3923 * Note that the next tag has now been moved to *cur_tag,
3924 * so we do not need to update the cur_tag pointer.
3932 /* Move on to next cookie tag */
3939 assert(NULL != *header);
3940 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3949 #ifdef FEATURE_FORCE_LOAD
3950 /*********************************************************************
3952 * Function : strclean
3954 * Description : In-Situ-Eliminate all occurances of substring in
3958 * 1 : string = string to clean
3959 * 2 : substring = substring to eliminate
3961 * Returns : Number of eliminations
3963 *********************************************************************/
3964 int strclean(const char *string, const char *substring)
3970 len = strlen(substring);
3972 while((pos = strstr(string, substring)) != NULL)
3979 while (*p++ != '\0');
3986 #endif /* def FEATURE_FORCE_LOAD */
3989 /*********************************************************************
3991 * Function : parse_header_time
3993 * Description : Parses time formats used in HTTP header strings
3994 * to get the numerical respresentation.
3997 * 1 : header_time = HTTP header time as string.
3998 * 2 : result = storage for header_time in seconds
4000 * Returns : JB_ERR_OK if the time format was recognized, or
4001 * JB_ERR_PARSE otherwise.
4003 *********************************************************************/
4004 static jb_err parse_header_time(const char *header_time, time_t *result)
4009 * Zero out gmt to prevent time zone offsets.
4011 * While this is only necessary on some platforms
4012 * (mingw32 for example), I don't know how to
4013 * detect these automatically and doing it everywhere
4016 memset(&gmt, 0, sizeof(gmt));
4018 /* Tue, 02 Jun 2037 20:00:00 */
4019 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4020 /* Tue, 02-Jun-2037 20:00:00 */
4021 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4022 /* Tue, 02-Jun-37 20:00:00 */
4023 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4024 /* Tuesday, 02-Jun-2037 20:00:00 */
4025 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4026 /* Tuesday Jun 02 20:00:00 2037 */
4027 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4029 return JB_ERR_PARSE;
4032 *result = timegm(&gmt);
4039 /*********************************************************************
4041 * Function : get_destination_from_headers
4043 * Description : Parse the "Host:" header to get the request's destination.
4044 * Only needed if the client's request was forcefully
4045 * redirected into Privoxy.
4047 * Code mainly copied from client_host() which is currently
4048 * run too late for this purpose.
4051 * 1 : headers = List of headers (one of them hopefully being
4052 * the "Host:" header)
4053 * 2 : http = storage for the result (host, port and hostport).
4055 * Returns : JB_ERR_MEMORY in case of memory problems,
4056 * JB_ERR_PARSE if the host header couldn't be found,
4057 * JB_ERR_OK otherwise.
4059 *********************************************************************/
4060 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4066 host = get_header_value(headers, "Host:");
4070 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4071 return JB_ERR_PARSE;
4074 if (NULL == (p = strdup((host))))
4076 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4077 return JB_ERR_MEMORY;
4080 if (NULL == (q = strdup(p)))
4083 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4084 return JB_ERR_MEMORY;
4087 freez(http->hostport);
4091 q = strchr(http->host, ':');
4094 /* Terminate hostname and evaluate port string */
4096 http->port = atoi(q);
4100 http->port = http->ssl ? 443 : 80;
4103 /* Rebuild request URL */
4105 http->url = strdup(http->ssl ? "https://" : "http://");
4106 string_append(&http->url, http->hostport);
4107 string_append(&http->url, http->path);
4108 if (http->url == NULL)
4110 return JB_ERR_MEMORY;
4113 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4121 /*********************************************************************
4123 * Function : create_forged_referrer
4125 * Description : Helper for client_referrer to forge a referer as
4126 * 'http://[hostname:port/' to fool stupid
4127 * checks for in-site links
4130 * 1 : header = Pointer to header pointer
4131 * 2 : hostport = Host and optionally port as string
4133 * Returns : JB_ERR_OK in case of success, or
4134 * JB_ERR_MEMORY in case of memory problems.
4136 *********************************************************************/
4137 static jb_err create_forged_referrer(char **header, const char *hostport)
4139 assert(NULL == *header);
4141 *header = strdup("Referer: http://");
4142 string_append(header, hostport);
4143 string_append(header, "/");
4145 if (NULL == *header)
4147 return JB_ERR_MEMORY;
4150 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4157 /*********************************************************************
4159 * Function : create_fake_referrer
4161 * Description : Helper for client_referrer to create a fake referrer
4162 * based on a string supplied by the user.
4165 * 1 : header = Pointer to header pointer
4166 * 2 : hosthost = Referrer to fake
4168 * Returns : JB_ERR_OK in case of success, or
4169 * JB_ERR_MEMORY in case of memory problems.
4171 *********************************************************************/
4172 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4174 assert(NULL == *header);
4176 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4178 log_error(LOG_LEVEL_HEADER,
4179 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4181 *header = strdup("Referer: ");
4182 string_append(header, fake_referrer);
4184 if (NULL == *header)
4186 return JB_ERR_MEMORY;
4189 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4196 /*********************************************************************
4198 * Function : handle_conditional_hide_referrer_parameter
4200 * Description : Helper for client_referrer to crunch or forge
4201 * the referrer header if the host has changed.
4204 * 1 : header = Pointer to header pointer
4205 * 2 : host = The target host (may include the port)
4206 * 3 : parameter_conditional_block = Boolean to signal
4207 * if we're in conditional-block mode. If not set,
4208 * we're in conditional-forge mode.
4210 * Returns : JB_ERR_OK in case of success, or
4211 * JB_ERR_MEMORY in case of memory problems.
4213 *********************************************************************/
4214 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4215 const char *host, const int parameter_conditional_block)
4217 char *referer = strdup(*header);
4218 const size_t hostlenght = strlen(host);
4220 if (NULL == referer)
4223 return JB_ERR_MEMORY;
4226 /* referer begins with 'Referer: http[s]://' */
4227 if (hostlenght < (strlen(referer)-17))
4230 * Shorten referer to make sure the referer is blocked
4231 * if www.example.org/www.example.com-shall-see-the-referer/
4232 * links to www.example.com/
4234 referer[hostlenght+17] = '\0';
4236 if (NULL == strstr(referer, host))
4238 /* Host has changed */
4239 if (parameter_conditional_block)
4241 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4248 return create_forged_referrer(header, host);