1 const char parsers_rcs[] = "$Id: parsers.c,v 1.109 2007/09/08 14:25:48 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.109 2007/09/08 14:25:48 fabiankeil
48 * Refactor client_referrer() and add conditional-forge parameter.
50 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
51 * A bunch of whitespace fixes, pointy hat to me.
53 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
54 * Fix possible memory corruption in server_http, make sure it's not
55 * executed for ordinary server headers and mark some problems for later.
57 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
58 * Let content-type-overwrite{} honour force-text-mode again.
60 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
61 * - Add prototpyes for the header parsers and make them static.
62 * - Comment out client_accept_encoding_adder() which isn't used right now.
64 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
65 * Move the ACTION_FORCE_TEXT_MODE check out of
66 * server_content_type(). Signal other functions
67 * whether or not a content type has been declared.
68 * Part of the fix for BR#1750917.
70 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
71 * Change sed() to return a jb_err in preparation for forward-override{}.
73 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
74 * Adjust "X-Filter: No" to disable dedicated header filters.
76 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
77 * Streamline client_cookie_adder().
79 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
80 * Make sure filters with dynamic jobs actually use them.
82 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
83 * - Introduce dynamic pcrs jobs that can resolve variables.
84 * - Remove unnecessary update_action_bits_for_all_tags() call.
86 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
87 * - Make tagging based on tags set by earlier taggers
88 * of the same kind possible.
89 * - Log whether or not new tags cause action bits updates
90 * (in which case a matching tag-pattern section exists).
91 * - Log if the user tries to set a tag that is already set.
93 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
94 * Introduce tags as alternative way to specify which
95 * actions apply to a request. At the moment tags can be
96 * created based on client and server headers.
98 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
99 * Log a warning if the content is compressed, filtering is
100 * enabled and Privoxy was compiled without zlib support.
103 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
104 * - Fix warnings when compiled with glibc.
105 * - Don't use crumble() for cookie crunching.
106 * - Move cookie time parsing into parse_header_time().
107 * - Let parse_header_time() return a jb_err code
108 * instead of a pointer that can only be used to
109 * check for NULL anyway.
111 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
112 * - Add better protection against malicious gzip headers.
113 * - Stop logging the first hundred bytes of decompressed content.
114 * It looks like it's working and there is always debug 16.
115 * - Log the content size after decompression in decompress_iob()
116 * instead of pcrs_filter_response().
118 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
119 * - Use dedicated header filter actions instead of abusing "filter".
120 * Replace "filter-client-headers" and "filter-client-headers"
121 * with "server-header-filter" and "client-header-filter".
122 * - Remove filter_client_header() and filter_client_header(),
123 * filter_header() now checks the shiny new
124 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
126 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
127 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
128 * - Handle "Cookie:" and "Connection:" headers a bit smarter
129 * (don't crunch them just to recreate them later on).
130 * - Add another non-standard time format for the cookie
131 * expiration date detection.
132 * - Fix a valgrind warning.
134 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
135 * Improve cookie expiration date detection.
137 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
138 * Don't run server_content_length() the first time
139 * sed() parses server headers; only adjust the
140 * Content-Length header if the page was modified.
142 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
143 * Fix log messages regarding the cookie time format
144 * (cookie and request URL were mixed up).
146 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
147 * - Let decompress_iob()
148 * - not corrupt the content if decompression fails
149 * early. (the first byte(s) were lost).
150 * - use pointer arithmetics with defined outcome for
152 * - Use a different kludge to remember a failed decompression.
154 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
155 * Search for Max-Forwards headers case-insensitive,
156 * don't generate the "501 unsupported" message for invalid
157 * Max-Forwards values and don't increase negative ones.
159 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
160 * - Let server_set_cookie() check the expiration date
161 * of cookies and don't touch the ones that are already
162 * expired. Fixes problems with low quality web applications
163 * as described in BR 932612.
165 * - Adjust comment in client_max_forwards to reality;
166 * remove invalid Max-Forwards headers.
168 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
169 * Stop filter_header() from unintentionally removing
170 * empty header lines that were enlisted by the continue
173 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
174 * - Repeat the request URL before logging any headers.
175 * Makes reading the log easier in case of simultaneous requests.
176 * - If there are more than one Content-Type headers in one request,
177 * use the first one and remove the others.
178 * - Remove "newval" variable in server_content_type().
179 * It's only used once.
181 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
182 * Correct a cast, check inflateEnd() exit code
183 * to see if we have to, replace sprintf calls
186 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
187 * Integrate a modified version of Wil Mahan's
188 * zlib patch (PR #895531).
190 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
191 * Skip empty filter files in filter_header()
192 * but don't ignore the ones that come afterwards.
193 * Fixes BR 1619208, this time for real.
195 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
196 * Reverted parts of my last commit
197 * to keep error handling working.
199 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
200 * Fixed gcc43 conversion warnings.
202 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
203 * Bringing back the "useless" localtime() call
204 * I removed in revision 1.67. On some platforms
205 * it's necessary to prevent time zone offsets.
207 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
208 * Rebuild request URL in get_destination_from_headers()
209 * to make sure redirect{pcrs command} works as expected
210 * for intercepted requests.
212 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
213 * Added get_destination_from_headers().
215 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
216 * Make pthread mutex locking more generic. Instead of
217 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
218 * and use mutex locking unless there is an _r function
219 * available. Better safe than sorry.
221 * Fixes "./configure --disable-pthread" and should result
222 * in less threading-related problems on pthread-using platforms,
223 * but it still doesn't fix BR#1122404.
225 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
226 * The special header "X-Filter: No" now disables
227 * header filtering as well.
229 * Revision 1.73 2006/09/23 13:26:38 roro
230 * Replace TABs by spaces in source code.
232 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
233 * Don't print a log message every time filter_headers is
234 * entered or left. It only creates noise without any real
237 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
238 * Fix +hide-if-modified-since{-n}.
240 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
241 * Have hide-if-modified-since interpret the random
242 * range value as minutes instead of hours. Allows
243 * more fine-grained configuration.
245 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
246 * Always have parse_header_time return a pointer
247 * that actual makes sense, even though we currently
248 * only need it to detect problems.
250 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
251 * Added config option enable-remote-http-toggle
252 * to specify if Privoxy should recognize special
253 * headers (currently only X-Filter) to change its
254 * behaviour. Disabled by default.
256 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
257 * After filtering de-chunked instances, remove
258 * "Transfer-Encoding" header entirely instead of changing
259 * it to "Transfer-Encoding: identity", which is invalid.
260 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
262 * Don't use localtime in parse_header_time. An empty time struct
263 * is good enough, it gets overwritten by strptime anyway.
265 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
266 * Use gmtime_r if available, fallback to gmtime with mutex
267 * protection for MacOSX and use vanilla gmtime for the rest.
269 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
270 * Changed client_referrer to use the right type (size_t) for
271 * hostlenght and to shorten the temporary referrer string with
272 * '\0' instead of adding a useless line break.
274 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
275 * - Back to timegm() using GnuPG's replacement if necessary.
276 * Using mktime() and localtime() could add a on hour offset if
277 * the randomize factor was big enough to lead to a summer/wintertime
280 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
282 * - Moved randomization code into pick_from_range().
284 * - Changed parse_header_time definition.
285 * time_t isn't guaranteed to be signed and
286 * if it isn't, -1 isn't available as error code.
287 * Changed some variable types in client_if_modified_since()
288 * because of the same reason.
290 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
291 * OS/2 compilation compatibility fixups
293 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
294 * Changed include from strptime.c to strptime.h
296 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
297 * Split filter-headers{} into filter-client-headers{}
298 * and filter-server-headers{}.
299 * Added parse_header_time() to share some code.
300 * Replaced timegm() with mktime().
302 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
303 * Windows service integration
305 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
306 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
308 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
309 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
310 * with what was really the latest development (the v_3_0_branch branch)
312 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
313 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
315 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
316 * Add the ability to check jpeg images for invalid
317 * lengths of comment blocks. Defensive strategy
318 * against the exploit:
319 * Microsoft Security Bulletin MS04-028
320 * Buffer Overrun in JPEG Processing (GDI+) Could
321 * Allow Code Execution (833987)
322 * Enabled with +inspect-jpegs in actions files.
324 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
325 * Excluded text/plain objects from filtering. This fixes a
326 * couple of client-crashing, download corruption and
327 * Privoxy performance issues, whose root cause lies in
328 * web servers labelling content of unknown type as text/plain.
330 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
331 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
333 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
334 * Completing the previous change
336 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
337 * Added temporary workaround for bug in PHP < 4.2.3
339 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
340 * 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.
342 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
343 * Fix typo: supressed -> suppressed
345 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
346 * Improved cookie logging
348 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
349 * Added basic support for OPTIONS and TRACE HTTP methods:
350 * - New parser function client_max_forwards which decrements
351 * the Max-Forwards HTTP header field of OPTIONS and TRACE
352 * requests by one before forwarding
353 * - New parser function client_host which extracts the host
354 * and port information from the HTTP header field if the
355 * request URI was not absolute
356 * - Don't crumble and re-add the Host: header, but only generate
357 * and append if missing
359 * Revision 1.56 2002/05/12 15:34:22 jongfoster
360 * Fixing typo in a comment
362 * Revision 1.55 2002/05/08 16:01:07 oes
363 * Optimized add_to_iob:
364 * - Use realloc instead of malloc(), memcpy(), free()
365 * - Expand to powers of two if possible, to get
366 * O(log n) reallocs instead of O(n).
367 * - Moved check for buffer limit here from chat
368 * - Report failure via returncode
370 * Revision 1.54 2002/04/02 15:03:16 oes
371 * Tiny code cosmetics
373 * Revision 1.53 2002/03/26 22:29:55 swa
374 * we have a new homepage!
376 * Revision 1.52 2002/03/24 13:25:43 swa
377 * name change related issues
379 * Revision 1.51 2002/03/13 00:27:05 jongfoster
382 * Revision 1.50 2002/03/12 01:45:35 oes
383 * More verbose logging
385 * Revision 1.49 2002/03/09 20:03:52 jongfoster
386 * - Making various functions return int rather than size_t.
387 * (Undoing a recent change). Since size_t is unsigned on
388 * Windows, functions like read_socket that return -1 on
389 * error cannot return a size_t.
391 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
392 * crashes, and also frequently caused JB to jump to 100%
393 * CPU and stay there. (Because it thought it had just
394 * read ((unsigned)-1) == 4Gb of data...)
396 * - The signature of write_socket has changed, it now simply
397 * returns success=0/failure=nonzero.
399 * - Trying to get rid of a few warnings --with-debug on
400 * Windows, I've introduced a new type "jb_socket". This is
401 * used for the socket file descriptors. On Windows, this
402 * is SOCKET (a typedef for unsigned). Everywhere else, it's
403 * an int. The error value can't be -1 any more, so it's
404 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
405 * Windows it maps to the #define INVALID_SOCKET.)
407 * - The signature of bind_port has changed.
409 * Revision 1.48 2002/03/07 03:46:53 oes
410 * Fixed compiler warnings etc
412 * Revision 1.47 2002/02/20 23:15:13 jongfoster
413 * Parsing functions now handle out-of-memory gracefully by returning
416 * Revision 1.46 2002/01/17 21:03:47 jongfoster
417 * Moving all our URL and URL pattern parsing code to urlmatch.c.
419 * Revision 1.45 2002/01/09 14:33:03 oes
420 * Added support for localtime_r.
422 * Revision 1.44 2001/12/14 01:22:54 steudten
423 * Remove 'user:pass@' from 'proto://user:pass@host' for the
424 * new added header 'Host: ..'. (See Req ID 491818)
426 * Revision 1.43 2001/11/23 00:26:38 jongfoster
427 * Fixing two really stupid errors in my previous commit
429 * Revision 1.42 2001/11/22 21:59:30 jongfoster
430 * Adding code to handle +no-cookies-keep
432 * Revision 1.41 2001/11/05 23:43:05 steudten
433 * Add time+date to log files.
435 * Revision 1.40 2001/10/26 20:13:09 jongfoster
436 * ctype.h is needed in Windows, too.
438 * Revision 1.39 2001/10/26 17:40:04 oes
439 * Introduced get_header_value()
440 * Removed http->user_agent, csp->referrer and csp->accept_types
441 * Removed client_accept()
443 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
444 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
445 * threads to call select() simultaneously. So, it's time to do a real, live,
446 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
447 * (native). Both versions will work, but using __OS2__ offers multi-threading.
449 * Revision 1.37 2001/10/23 21:36:02 jongfoster
450 * Documenting sed()'s error behaviou (doc change only)
452 * Revision 1.36 2001/10/13 12:51:51 joergs
453 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
454 * force-load), instead crumble Host: and add it (again) in client_host_adder
455 * (in case we get a HTTP/1.0 request without Host: header and forward it to
456 * a HTTP/1.1 server/proxy).
458 * Revision 1.35 2001/10/09 22:39:21 jongfoster
459 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
462 * Revision 1.34 2001/10/07 18:50:55 oes
463 * Added server_content_encoding, renamed server_transfer_encoding
465 * Revision 1.33 2001/10/07 18:04:49 oes
466 * Changed server_http11 to server_http and its pattern to "HTTP".
467 * Additional functionality: it now saves the HTTP status into
468 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
470 * Revision 1.32 2001/10/07 15:43:28 oes
471 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
472 * client_te and client_accept_encoding_adder, triggered by the new
473 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
474 * changed to allow only identity and chunked, and the TE header is
475 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
477 * parse_http_request no longer does anything than parsing. The rewriting
478 * of http->cmd and version mangling are gone. It now also recognizes
479 * the put and delete methods and saves the url in http->url. Removed
482 * renamed content_type and content_length to have the server_ prefix
484 * server_content_type now only works if csp->content_type != CT_TABOO
486 * added server_transfer_encoding, which
487 * - Sets CT_TABOO to prohibit filtering if encoding compresses
488 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
489 * - Change from "chunked" to "identity" if body was chunked
490 * but has been de-chunked for filtering.
492 * added server_content_md5 which crunches any Content-MD5 headers
493 * if the body was modified.
495 * made server_http11 conditional on +downgrade action
497 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
499 * Revision 1.31 2001/10/05 14:25:02 oes
500 * Crumble Keep-Alive from Server
502 * Revision 1.30 2001/09/29 12:56:03 joergs
503 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
505 * Revision 1.29 2001/09/24 21:09:24 jongfoster
506 * Fixing 2 memory leaks that Guy spotted, where the paramater to
507 * enlist() was not being free()d.
509 * Revision 1.28 2001/09/22 16:32:28 jongfoster
510 * Removing unused #includes.
512 * Revision 1.27 2001/09/20 15:45:25 steudten
514 * add casting from size_t to int for printf()
515 * remove local variable shadow s2
517 * Revision 1.26 2001/09/16 17:05:14 jongfoster
518 * Removing unused #include showarg.h
520 * Revision 1.25 2001/09/16 13:21:27 jongfoster
521 * Changes to use new list functions.
523 * Revision 1.24 2001/09/13 23:05:50 jongfoster
524 * Changing the string paramater to the header parsers a "const".
526 * Revision 1.23 2001/09/12 18:08:19 steudten
528 * In parse_http_request() header rewriting miss the host value, so
529 * from http://www.mydomain.com the result was just " / " not
530 * http://www.mydomain.com/ in case we forward.
532 * Revision 1.22 2001/09/10 10:58:53 oes
533 * Silenced compiler warnings
535 * Revision 1.21 2001/07/31 14:46:00 oes
536 * - Persistant connections now suppressed
537 * - sed() no longer appends empty header to csp->headers
539 * Revision 1.20 2001/07/30 22:08:36 jongfoster
540 * Tidying up #defines:
541 * - All feature #defines are now of the form FEATURE_xxx
542 * - Permanently turned off WIN_GUI_EDIT
543 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
545 * Revision 1.19 2001/07/25 17:21:54 oes
546 * client_uagent now saves copy of User-Agent: header value
548 * Revision 1.18 2001/07/13 14:02:46 oes
549 * - Included fix to repair broken HTTP requests that
550 * don't contain a path, not even '/'.
551 * - Removed all #ifdef PCRS
552 * - content_type now always inspected and classified as
553 * text, gif or other.
554 * - formatting / comments
556 * Revision 1.17 2001/06/29 21:45:41 oes
557 * Indentation, CRLF->LF, Tab-> Space
559 * Revision 1.16 2001/06/29 13:32:42 oes
561 * - Adapted free_http_request
562 * - Removed logentry from cancelled commit
564 * Revision 1.15 2001/06/03 19:12:38 oes
565 * deleted const struct interceptors
567 * Revision 1.14 2001/06/01 18:49:17 jongfoster
568 * Replaced "list_share" with "list" - the tiny memory gain was not
569 * worth the extra complexity.
571 * Revision 1.13 2001/05/31 21:30:33 jongfoster
572 * Removed list code - it's now in list.[ch]
573 * Renamed "permission" to "action", and changed many features
574 * to use the actions file rather than the global config.
576 * Revision 1.12 2001/05/31 17:33:13 oes
580 * Revision 1.11 2001/05/29 20:11:19 joergs
581 * '/ * inside comment' warning removed.
583 * Revision 1.10 2001/05/29 09:50:24 jongfoster
584 * Unified blocklist/imagelist/permissionslist.
585 * File format is still under discussion, but the internal changes
588 * Also modified interceptor behaviour:
589 * - We now intercept all URLs beginning with one of the following
590 * prefixes (and *only* these prefixes):
592 * * http://ijbswa.sf.net/config/
593 * * http://ijbswa.sourceforge.net/config/
594 * - New interceptors "home page" - go to http://i.j.b/ to see it.
595 * - Internal changes so that intercepted and fast redirect pages
596 * are not replaced with an image.
597 * - Interceptors now have the option to send a binary page direct
598 * to the client. (i.e. ijb-send-banner uses this)
599 * - Implemented show-url-info interceptor. (Which is why I needed
600 * the above interceptors changes - a typical URL is
601 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
602 * The previous mechanism would not have intercepted that, and
603 * if it had been intercepted then it then it would have replaced
606 * Revision 1.9 2001/05/28 17:26:33 jongfoster
607 * Fixing segfault if last header was crunched.
608 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
609 * can use the cross-platform sprintf() instead.)
611 * Revision 1.8 2001/05/27 22:17:04 oes
613 * - re_process_buffer no longer writes the modified buffer
614 * to the client, which was very ugly. It now returns the
615 * buffer, which it is then written by chat.
617 * - content_length now adjusts the Content-Length: header
618 * for modified documents rather than crunch()ing it.
619 * (Length info in csp->content_length, which is 0 for
620 * unmodified documents)
622 * - For this to work, sed() is called twice when filtering.
624 * Revision 1.7 2001/05/27 13:19:06 oes
625 * Patched Joergs solution for the content-length in.
627 * Revision 1.6 2001/05/26 13:39:32 jongfoster
628 * Only crunches Content-Length header if applying RE filtering.
629 * Without this fix, Microsoft Windows Update wouldn't work.
631 * Revision 1.5 2001/05/26 00:28:36 jongfoster
632 * Automatic reloading of config file.
633 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
634 * Most of the global variables have been moved to a new
635 * struct configuration_spec, accessed through csp->config->globalname
636 * Most of the globals remaining are used by the Win32 GUI.
638 * Revision 1.4 2001/05/22 18:46:04 oes
640 * - Enabled filtering banners by size rather than URL
641 * by adding patterns that replace all standard banner
642 * sizes with the "Junkbuster" gif to the re_filterfile
644 * - Enabled filtering WebBugs by providing a pattern
645 * which kills all 1x1 images
647 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
648 * which is selected by the (nonstandard and therefore
649 * capital) letter 'U' in the option string.
650 * It causes the quantifiers to be ungreedy by default.
651 * Appending a ? turns back to greedy (!).
653 * - Added a new interceptor ijb-send-banner, which
654 * sends back the "Junkbuster" gif. Without imagelist or
655 * MSIE detection support, or if tinygif = 1, or the
656 * URL isn't recognized as an imageurl, a lame HTML
657 * explanation is sent instead.
659 * - Added new feature, which permits blocking remote
660 * script redirects and firing back a local redirect
662 * The feature is conditionally compiled, i.e. it
663 * can be disabled with --disable-fast-redirects,
664 * plus it must be activated by a "fast-redirects"
665 * line in the config file, has its own log level
666 * and of course wants to be displayed by show-proxy-args
667 * Note: Boy, all the #ifdefs in 1001 locations and
668 * all the fumbling with configure.in and acconfig.h
669 * were *way* more work than the feature itself :-(
671 * - Because a generic redirect template was needed for
672 * this, tinygif = 3 now uses the same.
674 * - Moved GIFs, and other static HTTP response templates
679 * - Removed some >400 CRs again (Jon, you really worked
682 * Revision 1.3 2001/05/20 01:21:20 jongfoster
683 * Version 2.9.4 checkin.
684 * - Merged popupfile and cookiefile, and added control over PCRS
685 * filtering, in new "permissionsfile".
686 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
687 * file error you now get a message box (in the Win32 GUI) rather
688 * than the program exiting with no explanation.
689 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
691 * - Removed tabs from "config"
692 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
693 * - Bumped up version number.
695 * Revision 1.2 2001/05/17 23:02:36 oes
696 * - Made referrer option accept 'L' as a substitute for '§'
698 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
699 * Initial import of version 2.9.3 source tree
702 *********************************************************************/
709 #include <sys/types.h>
719 * Convince GNU's libc to provide a strptime prototype.
722 #endif /*__GLIBC__ */
729 #if !defined(_WIN32) && !defined(__OS2__)
735 #ifdef FEATURE_PTHREAD
737 /* jcc.h is for mutex semapores only */
738 #endif /* def FEATURE_PTHREAD */
744 #include "jbsockets.h"
745 #include "miscutil.h"
750 #ifndef HAVE_STRPTIME
751 #include "strptime.h"
754 const char parsers_h_rcs[] = PARSERS_H_VERSION;
756 /* Fix a problem with Solaris. There should be no effect on other
758 * Solaris's isspace() is a macro which uses its argument directly
759 * as an array index. Therefore we need to make sure that high-bit
760 * characters generate +ve values, and ideally we also want to make
761 * the argument match the declared parameter type of "int".
763 * Why did they write a character function that can't take a simple
764 * "char" argument? Doh!
766 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
767 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
769 static jb_err scan_headers(struct client_state *csp);
770 static jb_err header_tagger(struct client_state *csp, char *header);
771 static jb_err parse_header_time(const char *header_time, time_t *result);
773 static jb_err crumble (struct client_state *csp, char **header);
774 static jb_err connection (struct client_state *csp, char **header);
775 static jb_err filter_header (struct client_state *csp, char **header);
776 static jb_err client_referrer (struct client_state *csp, char **header);
777 static jb_err client_uagent (struct client_state *csp, char **header);
778 static jb_err client_ua (struct client_state *csp, char **header);
779 static jb_err client_from (struct client_state *csp, char **header);
780 static jb_err client_send_cookie (struct client_state *csp, char **header);
781 static jb_err client_x_forwarded (struct client_state *csp, char **header);
782 static jb_err client_accept_encoding (struct client_state *csp, char **header);
783 static jb_err client_te (struct client_state *csp, char **header);
784 static jb_err client_max_forwards (struct client_state *csp, char **header);
785 static jb_err client_host (struct client_state *csp, char **header);
786 static jb_err client_if_modified_since (struct client_state *csp, char **header);
787 static jb_err client_accept_language (struct client_state *csp, char **header);
788 static jb_err client_if_none_match (struct client_state *csp, char **header);
789 static jb_err crunch_client_header (struct client_state *csp, char **header);
790 static jb_err client_x_filter (struct client_state *csp, char **header);
791 static jb_err server_set_cookie (struct client_state *csp, char **header);
792 static jb_err server_content_type (struct client_state *csp, char **header);
793 static jb_err server_content_length (struct client_state *csp, char **header);
794 static jb_err server_content_md5 (struct client_state *csp, char **header);
795 static jb_err server_content_encoding (struct client_state *csp, char **header);
796 static jb_err server_transfer_coding (struct client_state *csp, char **header);
797 static jb_err server_http (struct client_state *csp, char **header);
798 static jb_err crunch_server_header (struct client_state *csp, char **header);
799 static jb_err server_last_modified (struct client_state *csp, char **header);
800 static jb_err server_content_disposition(struct client_state *csp, char **header);
802 static jb_err client_host_adder (struct client_state *csp);
803 static jb_err client_cookie_adder (struct client_state *csp);
804 static jb_err client_xtra_adder (struct client_state *csp);
805 static jb_err client_x_forwarded_adder(struct client_state *csp);
806 static jb_err connection_close_adder (struct client_state *csp);
808 static jb_err create_forged_referrer(char **header, const char *hostport);
809 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
810 static jb_err handle_conditional_hide_referrer_parameter(char **header,
811 const char *host, const int parameter_conditional_block);
813 const struct parsers client_patterns[] = {
814 { "referer:", 8, client_referrer },
815 { "user-agent:", 11, client_uagent },
816 { "ua-", 3, client_ua },
817 { "from:", 5, client_from },
818 { "cookie:", 7, client_send_cookie },
819 { "x-forwarded-for:", 16, client_x_forwarded },
820 { "Accept-Encoding:", 16, client_accept_encoding },
821 { "TE:", 3, client_te },
822 { "Host:", 5, client_host },
823 { "if-modified-since:", 18, client_if_modified_since },
824 { "Keep-Alive:", 11, crumble },
825 { "connection:", 11, connection },
826 { "proxy-connection:", 17, crumble },
827 { "max-forwards:", 13, client_max_forwards },
828 { "Accept-Language:", 16, client_accept_language },
829 { "if-none-match:", 14, client_if_none_match },
830 { "X-Filter:", 9, client_x_filter },
831 { "*", 0, crunch_client_header },
832 { "*", 0, filter_header },
836 const struct parsers server_patterns[] = {
837 { "HTTP/", 5, server_http },
838 { "set-cookie:", 11, server_set_cookie },
839 { "connection:", 11, connection },
840 { "Content-Type:", 13, server_content_type },
841 { "Content-MD5:", 12, server_content_md5 },
842 { "Content-Encoding:", 17, server_content_encoding },
843 { "Transfer-Encoding:", 18, server_transfer_coding },
844 { "Keep-Alive:", 11, crumble },
845 { "content-disposition:", 20, server_content_disposition },
846 { "Last-Modified:", 14, server_last_modified },
847 { "*", 0, crunch_server_header },
848 { "*", 0, filter_header },
852 const struct parsers server_patterns_light[] = {
853 { "Content-Length:", 15, server_content_length },
854 { "Transfer-Encoding:", 18, server_transfer_coding },
856 { "Content-Encoding:", 17, server_content_encoding },
857 #endif /* def FEATURE_ZLIB */
861 const add_header_func_ptr add_client_headers[] = {
864 client_x_forwarded_adder,
866 /* Temporarily disabled: client_accept_encoding_adder, */
867 connection_close_adder,
871 const add_header_func_ptr add_server_headers[] = {
872 connection_close_adder,
876 /*********************************************************************
878 * Function : flush_socket
880 * Description : Write any pending "buffered" content.
883 * 1 : fd = file descriptor of the socket to read
884 * 2 : csp = Current client state (buffers, headers, etc...)
886 * Returns : On success, the number of bytes written are returned (zero
887 * indicates nothing was written). On error, -1 is returned,
888 * and errno is set appropriately. If count is zero and the
889 * file descriptor refers to a regular file, 0 will be
890 * returned without causing any other effect. For a special
891 * file, the results are not portable.
893 *********************************************************************/
894 int flush_socket(jb_socket fd, struct client_state *csp)
896 struct iob *iob = csp->iob;
897 int len = iob->eod - iob->cur;
904 if (write_socket(fd, iob->cur, (size_t)len))
908 iob->eod = iob->cur = iob->buf;
914 /*********************************************************************
916 * Function : add_to_iob
918 * Description : Add content to the buffered page, expanding the
919 * buffer if necessary.
922 * 1 : csp = Current client state (buffers, headers, etc...)
923 * 2 : buf = holds the content to be added to the page
924 * 3 : n = number of bytes to be added
926 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
927 * or buffer limit reached.
929 *********************************************************************/
930 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
932 struct iob *iob = csp->iob;
933 size_t used, offset, need, want;
936 if (n <= 0) return JB_ERR_OK;
938 used = (size_t)(iob->eod - iob->buf);
939 offset = (size_t)(iob->cur - iob->buf);
940 need = used + (size_t)n + 1;
943 * If the buffer can't hold the new data, extend it first.
944 * Use the next power of two if possible, else use the actual need.
946 if (need > csp->config->buffer_limit)
948 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
949 return JB_ERR_MEMORY;
952 if (need > iob->size)
954 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
956 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
960 else if (NULL != (p = (char *)realloc(iob->buf, need)))
966 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
967 return JB_ERR_MEMORY;
970 /* Update the iob pointers */
971 iob->cur = p + offset;
976 /* copy the new data into the iob buffer */
977 memcpy(iob->eod, buf, (size_t)n);
979 /* point to the end of the data */
982 /* null terminate == cheap insurance */
991 /*********************************************************************
993 * Function : decompress_iob
995 * Description : Decompress buffered page, expanding the
996 * buffer as necessary. csp->iob->cur
997 * should point to the the beginning of the
998 * compressed data block.
1001 * 1 : csp = Current client state (buffers, headers, etc...)
1003 * Returns : JB_ERR_OK on success,
1004 * JB_ERR_MEMORY if out-of-memory limit reached, and
1005 * JB_ERR_COMPRESS if error decompressing buffer.
1007 *********************************************************************/
1008 jb_err decompress_iob(struct client_state *csp)
1010 char *buf; /* new, uncompressed buffer */
1011 char *cur; /* Current iob position (to keep the original
1012 * iob->cur unmodified if we return early) */
1013 size_t bufsize; /* allocated size of the new buffer */
1014 size_t old_size; /* Content size before decompression */
1015 size_t skip_size; /* Number of bytes at the beginning of the iob
1016 that we should NOT decompress. */
1017 int status; /* return status of the inflate() call */
1018 z_stream zstr; /* used by calls to zlib */
1020 assert(csp->iob->cur - csp->iob->buf > 0);
1021 assert(csp->iob->eod - csp->iob->cur > 0);
1023 bufsize = csp->iob->size;
1024 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1025 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1027 cur = csp->iob->cur;
1032 * This is to protect the parsing of gzipped data,
1033 * but it should(?) be valid for deflated data also.
1035 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1036 return JB_ERR_COMPRESS;
1039 if (csp->content_type & CT_GZIP)
1042 * Our task is slightly complicated by the facts that data
1043 * compressed by gzip does not include a zlib header, and
1044 * that there is no easily accessible interface in zlib to
1045 * handle a gzip header. We strip off the gzip header by
1046 * hand, and later inform zlib not to expect a header.
1050 * Strip off the gzip header. Please see RFC 1952 for more
1051 * explanation of the appropriate fields.
1053 if ((*cur++ != (char)0x1f)
1054 || (*cur++ != (char)0x8b)
1055 || (*cur++ != Z_DEFLATED))
1057 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1058 return JB_ERR_COMPRESS;
1064 * XXX: These magic numbers should be replaced
1065 * with macros to give a better idea what they do.
1069 /* The gzip header has reserved bits set; bail out. */
1070 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1071 return JB_ERR_COMPRESS;
1075 /* Skip extra fields if necessary. */
1079 * Skip a given number of bytes, specified
1080 * as a 16-bit little-endian value.
1083 * XXX: This code used to be:
1085 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1087 * which I had to change into:
1089 * cur += *cur++ + (*cur++ << 8);
1091 * at which point gcc43 finally noticed that the value
1092 * of cur is undefined (it depends on which of the
1093 * summands is evaluated first).
1095 * I haven't come across a site where this
1096 * code is actually executed yet, but I hope
1100 skip_bytes = *cur++;
1101 skip_bytes = *cur++ << 8;
1103 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1106 * The number of bytes to skip should be positive
1107 * and we'd like to stay in the buffer.
1109 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1111 log_error(LOG_LEVEL_ERROR,
1112 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1114 return JB_ERR_COMPRESS;
1116 log_error(LOG_LEVEL_INFO,
1117 "Skipping %d bytes for gzip compression. Does this sound right?",
1122 /* Skip the filename if necessary. */
1125 /* A null-terminated string is supposed to follow. */
1126 while (*cur++ && (cur < csp->iob->eod));
1130 /* Skip the comment if necessary. */
1133 /* A null-terminated string is supposed to follow. */
1134 while (*cur++ && (cur < csp->iob->eod));
1137 /* Skip the CRC if necessary. */
1143 if (cur >= csp->iob->eod)
1146 * If the current position pointer reached or passed
1147 * the buffer end, we were obviously tricked to skip
1150 log_error(LOG_LEVEL_ERROR,
1151 "Malformed gzip header detected. Aborting decompression.");
1152 return JB_ERR_COMPRESS;
1156 else if (csp->content_type & CT_DEFLATE)
1159 * XXX: The debug level should be lowered
1160 * before the next stable release.
1162 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1164 * In theory (that is, according to RFC 1950), deflate-compressed
1165 * data should begin with a two-byte zlib header and have an
1166 * adler32 checksum at the end. It seems that in practice only
1167 * the raw compressed data is sent. Note that this means that
1168 * we are not RFC 1950-compliant here, but the advantage is that
1169 * this actually works. :)
1171 * We add a dummy null byte to tell zlib where the data ends,
1172 * and later inform it not to expect a header.
1174 * Fortunately, add_to_iob() has thoughtfully null-terminated
1175 * the buffer; we can just increment the end pointer to include
1182 log_error(LOG_LEVEL_ERROR,
1183 "Unable to determine compression format for decompression");
1184 return JB_ERR_COMPRESS;
1187 /* Set up the fields required by zlib. */
1188 zstr.next_in = (Bytef *)cur;
1189 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1190 zstr.zalloc = Z_NULL;
1191 zstr.zfree = Z_NULL;
1192 zstr.opaque = Z_NULL;
1195 * Passing -MAX_WBITS to inflateInit2 tells the library
1196 * that there is no zlib header.
1198 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1200 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1201 return JB_ERR_COMPRESS;
1205 * Next, we allocate new storage for the inflated data.
1206 * We don't modify the existing iob yet, so in case there
1207 * is error in decompression we can recover gracefully.
1209 buf = zalloc(bufsize);
1212 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1213 return JB_ERR_MEMORY;
1216 assert(bufsize >= skip_size);
1217 memcpy(buf, csp->iob->buf, skip_size);
1218 zstr.avail_out = bufsize - skip_size;
1219 zstr.next_out = (Bytef *)buf + skip_size;
1221 /* Try to decompress the whole stream in one shot. */
1222 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1224 /* We need to allocate more memory for the output buffer. */
1226 char *tmpbuf; /* used for realloc'ing the buffer */
1227 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1230 * If zlib wants more data then there's a problem, because
1231 * the complete compressed file should have been buffered.
1233 if (0 == zstr.avail_in)
1235 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1236 return JB_ERR_COMPRESS;
1240 * If we tried the limit and still didn't have enough
1241 * memory, just give up.
1243 if (bufsize == csp->config->buffer_limit)
1245 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1246 return JB_ERR_MEMORY;
1249 /* Try doubling the buffer size each time. */
1252 /* Don't exceed the buffer limit. */
1253 if (bufsize > csp->config->buffer_limit)
1255 bufsize = csp->config->buffer_limit;
1258 /* Try to allocate the new buffer. */
1259 tmpbuf = realloc(buf, bufsize);
1262 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1264 return JB_ERR_MEMORY;
1268 char *oldnext_out = (char *)zstr.next_out;
1271 * Update the fields for inflate() to use the new
1272 * buffer, which may be in a location different from
1275 zstr.avail_out += bufsize - oldbufsize;
1276 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1279 * Compare with an uglier method of calculating these values
1280 * that doesn't require the extra oldbufsize variable.
1282 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1283 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1284 assert(zstr.avail_out > 0);
1290 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1292 log_error(LOG_LEVEL_ERROR,
1293 "Inconsistent stream state after decompression: %s", zstr.msg);
1295 * XXX: Intentionally no return.
1297 * According to zlib.h, Z_STREAM_ERROR is returned
1298 * "if the stream state was inconsistent".
1300 * I assume in this case inflate()'s status
1301 * would also be something different than Z_STREAM_END
1302 * so this check should be redundant, but lets see.
1306 if (status != Z_STREAM_END)
1308 /* We failed to decompress the stream. */
1309 log_error(LOG_LEVEL_ERROR,
1310 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1311 return JB_ERR_COMPRESS;
1315 * Finally, we can actually update the iob, since the
1316 * decompression was successful. First, free the old
1319 freez(csp->iob->buf);
1321 /* Now, update the iob to use the new buffer. */
1322 csp->iob->buf = buf;
1323 csp->iob->cur = csp->iob->buf + skip_size;
1324 csp->iob->eod = (char *)zstr.next_out;
1325 csp->iob->size = bufsize;
1328 * Make sure the new uncompressed iob obeys some minimal
1329 * consistency conditions.
1331 if ((csp->iob->buf < csp->iob->cur)
1332 && (csp->iob->cur <= csp->iob->eod)
1333 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1335 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1338 log_error(LOG_LEVEL_RE_FILTER,
1339 "Decompression successful. Old size: %d, new size: %d.",
1340 old_size, new_size);
1344 /* zlib thinks this is OK, so lets do the same. */
1345 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1350 /* It seems that zlib did something weird. */
1351 log_error(LOG_LEVEL_ERROR,
1352 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1353 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1354 csp->iob->eod, csp->iob->buf + csp->iob->size);
1355 return JB_ERR_COMPRESS;
1361 #endif /* defined(FEATURE_ZLIB) */
1364 /*********************************************************************
1366 * Function : get_header
1368 * Description : This (odd) routine will parse the csp->iob
1371 * 1 : csp = Current client state (buffers, headers, etc...)
1373 * Returns : Any one of the following:
1375 * 1) a pointer to a dynamically allocated string that contains a header line
1376 * 2) NULL indicating that the end of the header was reached
1377 * 3) "" indicating that the end of the iob was reached before finding
1378 * a complete header line.
1380 *********************************************************************/
1381 char *get_header(struct client_state *csp)
1387 if ((iob->cur == NULL)
1388 || ((p = strchr(iob->cur, '\n')) == NULL))
1390 return(""); /* couldn't find a complete header */
1395 ret = strdup(iob->cur);
1398 /* FIXME No way to handle error properly */
1399 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1404 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1406 /* is this a blank line (i.e. the end of the header) ? */
1418 /*********************************************************************
1420 * Function : get_header_value
1422 * Description : Get the value of a given header from a chained list
1423 * of header lines or return NULL if no such header is
1424 * present in the list.
1427 * 1 : header_list = pointer to list
1428 * 2 : header_name = string with name of header to look for.
1429 * Trailing colon required, capitalization
1432 * Returns : NULL if not found, else value of header
1434 *********************************************************************/
1435 char *get_header_value(const struct list *header_list, const char *header_name)
1437 struct list_entry *cur_entry;
1441 assert(header_list);
1442 assert(header_name);
1443 length = strlen(header_name);
1445 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1449 if (!strncmpic(cur_entry->str, header_name, length))
1452 * Found: return pointer to start of value
1454 ret = (char *) (cur_entry->str + length);
1455 while (*ret && ijb_isspace(*ret)) ret++;
1469 /*********************************************************************
1471 * Function : scan_headers
1473 * Description : Scans headers, applies tags and updates action bits.
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * Returns : JB_ERR_OK
1480 *********************************************************************/
1481 static jb_err scan_headers(struct client_state *csp)
1483 struct list_entry *h; /* Header */
1484 jb_err err = JB_ERR_OK;
1486 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1488 /* Header crunch()ed in previous run? -> ignore */
1489 if (h->str == NULL) continue;
1490 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1491 err = header_tagger(csp, h->str);
1498 /*********************************************************************
1502 * Description : add, delete or modify lines in the HTTP header streams.
1503 * On entry, it receives a linked list of headers space
1504 * that was allocated dynamically (both the list nodes
1505 * and the header contents).
1507 * As a side effect it frees the space used by the original
1510 * XXX: should be split to remove the first_run hack.
1513 * 1 : pats = list of patterns to match against headers
1514 * 2 : more_headers = list of functions to add more
1515 * headers (client or server)
1516 * 3 : csp = Current client state (buffers, headers, etc...)
1518 * Returns : JB_ERR_OK in case off success, or
1519 * JB_ERR_MEMORY on out-of-memory error.
1521 *********************************************************************/
1522 jb_err sed(const struct parsers pats[],
1523 const add_header_func_ptr more_headers[],
1524 struct client_state *csp)
1526 struct list_entry *p;
1527 const struct parsers *v;
1528 const add_header_func_ptr *f;
1529 jb_err err = JB_ERR_OK;
1533 * If filtering is enabled, sed is run twice,
1534 * but most of the work needs to be done only once.
1536 first_run = (more_headers != NULL ) ? 1 : 0;
1538 if (first_run) /* Parse and print */
1542 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1544 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1546 /* Header crunch()ed in previous run? -> ignore */
1547 if (p->str == NULL) continue;
1549 /* Does the current parser handle this header? */
1550 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1552 err = v->parser(csp, (char **)&(p->str));
1556 /* place any additional headers on the csp->headers list */
1557 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1562 else /* Parse only */
1565 * The second run is only needed if the body was modified
1566 * and the content-lenght has changed.
1568 if (strncmpic(csp->http->cmd, "HEAD", 4))
1570 /*XXX: Code duplication */
1571 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1573 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1575 /* Header crunch()ed in previous run? -> ignore */
1576 if (p->str == NULL) continue;
1578 /* Does the current parser handle this header? */
1579 if (strncmpic(p->str, v->str, v->len) == 0)
1581 err = v->parser(csp, (char **)&(p->str));
1593 /*********************************************************************
1595 * Function : header_tagger
1597 * Description : Executes all text substitutions from applying
1598 * tag actions and saves the result as tag.
1600 * XXX: Shares enough code with filter_header() and
1601 * pcrs_filter_response() to warrant some helper functions.
1604 * 1 : csp = Current client state (buffers, headers, etc...)
1605 * 2 : header = Header that is used as tagger input
1607 * Returns : JB_ERR_OK on success and always succeeds
1609 *********************************************************************/
1610 static jb_err header_tagger(struct client_state *csp, char *header)
1612 int wanted_filter_type;
1613 int multi_action_index;
1617 struct file_list *fl;
1618 struct re_filterfile_spec *b;
1619 struct list_entry *tag_name;
1621 int found_filters = 0;
1622 const size_t header_length = strlen(header);
1624 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1626 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1627 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1631 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1632 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1635 /* Check if there are any filters */
1636 for (i = 0; i < MAX_AF_FILES; i++)
1649 if (0 == found_filters)
1651 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1655 for (i = 0; i < MAX_AF_FILES; i++)
1658 if ((NULL == fl) || (NULL == fl->f))
1661 * Either there are no filter files
1662 * left, or this filter file just
1663 * contains no valid filters.
1665 * Continue to be sure we don't miss
1666 * valid filter files that are chained
1667 * after empty or invalid ones.
1672 /* For all filters, */
1673 for (b = fl->f; b; b = b->next)
1675 if (b->type != wanted_filter_type)
1677 /* skip the ones we don't care about, */
1680 /* leaving only taggers that could apply, of which we use the ones, */
1681 for (tag_name = csp->action->multi[multi_action_index]->first;
1682 NULL != tag_name; tag_name = tag_name->next)
1684 /* that do apply, and */
1685 if (strcmp(b->name, tag_name->str) == 0)
1687 char *modified_tag = NULL;
1689 size_t size = header_length;
1690 pcrs_job *joblist = b->joblist;
1692 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1694 if (NULL == joblist)
1696 log_error(LOG_LEVEL_RE_FILTER,
1697 "Tagger %s has empty joblist. Nothing to do.", b->name);
1701 /* execute their pcrs_joblist on the header. */
1702 for (job = joblist; NULL != job; job = job->next)
1704 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1708 /* Success, continue with the modified version. */
1717 /* Tagger doesn't match */
1720 /* Regex failure, log it but continue anyway. */
1721 log_error(LOG_LEVEL_ERROR,
1722 "Problems with tagger \'%s\' and header \'%s\': %s",
1723 b->name, *header, pcrs_strerror(hits));
1725 freez(modified_tag);
1729 if (b->dynamic) pcrs_free_joblist(joblist);
1731 /* If this tagger matched */
1737 * There is to technical limitation which makes
1738 * it impossible to use empty tags, but I assume
1739 * no one would do it intentionally.
1742 log_error(LOG_LEVEL_INFO,
1743 "Tagger \'%s\' created an empty tag. Ignored.",
1748 if (!list_contains_item(csp->tags, tag))
1750 if (JB_ERR_OK != enlist(csp->tags, tag))
1752 log_error(LOG_LEVEL_ERROR,
1753 "Insufficient memory to add tag \'%s\', "
1754 "based on tagger \'%s\' and header \'%s\'",
1755 tag, b->name, *header);
1759 char *action_message;
1761 * update the action bits right away, to make
1762 * tagging based on tags set by earlier taggers
1763 * of the same kind possible.
1765 if (update_action_bits_for_tag(csp, tag))
1767 action_message = "Action bits updated accordingly.";
1771 action_message = "No action bits update necessary.";
1774 log_error(LOG_LEVEL_HEADER,
1775 "Tagger \'%s\' added tag \'%s\'. %s",
1776 b->name, tag, action_message);
1781 /* XXX: Is this log-worthy? */
1782 log_error(LOG_LEVEL_HEADER,
1783 "Tagger \'%s\' didn't add tag \'%s\'. "
1784 "Tag already present", b->name, tag);
1787 } /* if the tagger matched */
1788 } /* if the tagger applies */
1789 } /* for every tagger that could apply */
1790 } /* for all filters */
1791 } /* for all filter files */
1796 /* here begins the family of parser functions that reformat header lines */
1798 /*********************************************************************
1800 * Function : filter_header
1802 * Description : Executes all text substitutions from all applying
1803 * +(server|client)-header-filter actions on the header.
1804 * Most of the code was copied from pcrs_filter_response,
1805 * including the rather short variable names
1808 * 1 : csp = Current client state (buffers, headers, etc...)
1809 * 2 : header = On input, pointer to header to modify.
1810 * On output, pointer to the modified header, or NULL
1811 * to remove the header. This function frees the
1812 * original string if necessary.
1814 * Returns : JB_ERR_OK on success and always succeeds
1816 *********************************************************************/
1817 static jb_err filter_header(struct client_state *csp, char **header)
1821 size_t size = strlen(*header);
1823 char *newheader = NULL;
1826 struct file_list *fl;
1827 struct re_filterfile_spec *b;
1828 struct list_entry *filtername;
1830 int i, found_filters = 0;
1831 int wanted_filter_type;
1832 int multi_action_index;
1834 if (csp->flags & CSP_FLAG_NO_FILTERING)
1839 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1841 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1842 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1846 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1847 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1851 * Need to check the set of re_filterfiles...
1853 for (i = 0; i < MAX_AF_FILES; i++)
1866 if (0 == found_filters)
1868 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1872 for (i = 0; i < MAX_AF_FILES; i++)
1875 if ((NULL == fl) || (NULL == fl->f))
1878 * Either there are no filter files
1879 * left, or this filter file just
1880 * contains no valid filters.
1882 * Continue to be sure we don't miss
1883 * valid filter files that are chained
1884 * after empty or invalid ones.
1889 * For all applying +filter actions, look if a filter by that
1890 * name exists and if yes, execute its pcrs_joblist on the
1893 for (b = fl->f; b; b = b->next)
1895 if (b->type != wanted_filter_type)
1897 /* Skip other filter types */
1901 for (filtername = csp->action->multi[multi_action_index]->first;
1902 filtername ; filtername = filtername->next)
1904 if (strcmp(b->name, filtername->str) == 0)
1906 int current_hits = 0;
1907 pcrs_job *joblist = b->joblist;
1909 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1911 if (NULL == joblist)
1913 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1917 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1918 *header, size, b->name);
1920 /* Apply all jobs from the joblist */
1921 for (job = joblist; NULL != job; job = job->next)
1923 matches = pcrs_execute(job, *header, size, &newheader, &size);
1926 current_hits += matches;
1927 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1929 *header = newheader;
1931 else if ( 0 == matches )
1933 /* Filter doesn't change header */
1939 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1940 *header, b->name, pcrs_strerror(matches));
1941 if (newheader != NULL)
1943 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1949 if (b->dynamic) pcrs_free_joblist(joblist);
1951 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1952 hits += current_hits;
1959 * Additionally checking for hits is important because if
1960 * the continue hack is triggered, server headers can
1961 * arrive empty to separate multiple heads from each other.
1963 if ((0 == size) && hits)
1965 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1973 /*********************************************************************
1975 * Function : connection
1977 * Description : Makes sure that the value of the Connection: header
1978 * is "close" and signals connection_close_adder
1982 * 1 : csp = Current client state (buffers, headers, etc...)
1983 * 2 : header = On input, pointer to header to modify.
1984 * On output, pointer to the modified header, or NULL
1985 * to remove the header. This function frees the
1986 * original string if necessary.
1988 * Returns : JB_ERR_OK on success, or
1989 * JB_ERR_MEMORY on out-of-memory error.
1991 *********************************************************************/
1992 static jb_err connection(struct client_state *csp, char **header)
1994 char *old_header = *header;
1996 /* Do we have a 'Connection: close' header? */
1997 if (strcmpic(*header, "Connection: close"))
1999 /* No, create one */
2000 *header = strdup("Connection: close");
2003 return JB_ERR_MEMORY;
2005 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2009 /* Signal connection_close_adder() to return early. */
2010 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2012 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2016 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2023 /*********************************************************************
2025 * Function : crumble
2027 * Description : This is called if a header matches a pattern to "crunch"
2030 * 1 : csp = Current client state (buffers, headers, etc...)
2031 * 2 : header = On input, pointer to header to modify.
2032 * On output, pointer to the modified header, or NULL
2033 * to remove the header. This function frees the
2034 * original string if necessary.
2036 * Returns : JB_ERR_OK on success, or
2037 * JB_ERR_MEMORY on out-of-memory error.
2039 *********************************************************************/
2040 static jb_err crumble(struct client_state *csp, char **header)
2042 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2048 /*********************************************************************
2050 * Function : crunch_server_header
2052 * Description : Crunch server header if it matches a string supplied by the
2053 * user. Called from `sed'.
2056 * 1 : csp = Current client state (buffers, headers, etc...)
2057 * 2 : header = On input, pointer to header to modify.
2058 * On output, pointer to the modified header, or NULL
2059 * to remove the header. This function frees the
2060 * original string if necessary.
2062 * Returns : JB_ERR_OK on success and always succeeds
2064 *********************************************************************/
2065 static jb_err crunch_server_header(struct client_state *csp, char **header)
2067 const char *crunch_pattern;
2069 /* Do we feel like crunching? */
2070 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2072 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2074 /* Is the current header the lucky one? */
2075 if (strstr(*header, crunch_pattern))
2077 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2086 /*********************************************************************
2088 * Function : server_content_type
2090 * Description : Set the content-type for filterable types (text/.*,
2091 * .*xml.*, javascript and image/gif) unless filtering has been
2092 * forbidden (CT_TABOO) while parsing earlier headers.
2093 * NOTE: Since text/plain is commonly used by web servers
2094 * for files whose correct type is unknown, we don't
2095 * set CT_TEXT for it.
2098 * 1 : csp = Current client state (buffers, headers, etc...)
2099 * 2 : header = On input, pointer to header to modify.
2100 * On output, pointer to the modified header, or NULL
2101 * to remove the header. This function frees the
2102 * original string if necessary.
2104 * Returns : JB_ERR_OK on success, or
2105 * JB_ERR_MEMORY on out-of-memory error.
2107 *********************************************************************/
2108 static jb_err server_content_type(struct client_state *csp, char **header)
2110 /* Remove header if it isn't the first Content-Type header */
2111 if ((csp->content_type & CT_DECLARED))
2114 * Another, slightly slower, way to see if
2115 * we already parsed another Content-Type header.
2117 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2119 log_error(LOG_LEVEL_ERROR,
2120 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2128 * Signal that the Content-Type has been set.
2130 csp->content_type |= CT_DECLARED;
2132 if (!(csp->content_type & CT_TABOO))
2134 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2135 || strstr(*header, "xml")
2136 || strstr(*header, "application/x-javascript"))
2138 csp->content_type |= CT_TEXT;
2140 else if (strstr(*header, " image/gif"))
2142 csp->content_type |= CT_GIF;
2144 else if (strstr(*header, " image/jpeg"))
2146 csp->content_type |= CT_JPEG;
2151 * Are we messing with the content type?
2153 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2156 * Make sure the user doesn't accidently
2157 * change the content type of binary documents.
2159 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2162 *header = strdup("Content-Type: ");
2163 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2167 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2168 return JB_ERR_MEMORY;
2170 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2174 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2175 "Enable force-text-mode if you know what you're doing.", *header);
2183 /*********************************************************************
2185 * Function : server_transfer_coding
2187 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2188 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2189 * - Remove header if body was chunked but has been
2190 * de-chunked for filtering.
2193 * 1 : csp = Current client state (buffers, headers, etc...)
2194 * 2 : header = On input, pointer to header to modify.
2195 * On output, pointer to the modified header, or NULL
2196 * to remove the header. This function frees the
2197 * original string if necessary.
2199 * Returns : JB_ERR_OK on success, or
2200 * JB_ERR_MEMORY on out-of-memory error.
2202 *********************************************************************/
2203 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2206 * Turn off pcrs and gif filtering if body compressed
2208 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2212 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2214 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2215 csp->http->cmd, *header);
2216 #endif /* def FEATURE_ZLIB */
2217 csp->content_type = CT_TABOO;
2221 * Raise flag if body chunked
2223 if (strstr(*header, "chunked"))
2225 csp->flags |= CSP_FLAG_CHUNKED;
2228 * If the body was modified, it has been de-chunked first
2229 * and the header must be removed.
2231 * FIXME: If there is more than one transfer encoding,
2232 * only the "chunked" part should be removed here.
2234 if (csp->flags & CSP_FLAG_MODIFIED)
2236 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2245 /*********************************************************************
2247 * Function : server_content_encoding
2249 * Description : This function is run twice for each request,
2250 * unless FEATURE_ZLIB and filtering are disabled.
2252 * The first run is used to check if the content
2253 * is compressed, if FEATURE_ZLIB is disabled
2254 * filtering is then disabled as well, if FEATURE_ZLIB
2255 * is enabled the content is marked for decompression.
2257 * The second run is used to remove the Content-Encoding
2258 * header if the decompression was successful.
2261 * 1 : csp = Current client state (buffers, headers, etc...)
2262 * 2 : header = On input, pointer to header to modify.
2263 * On output, pointer to the modified header, or NULL
2264 * to remove the header. This function frees the
2265 * original string if necessary.
2267 * Returns : JB_ERR_OK on success, or
2268 * JB_ERR_MEMORY on out-of-memory error.
2270 *********************************************************************/
2271 static jb_err server_content_encoding(struct client_state *csp, char **header)
2274 if ((csp->flags & CSP_FLAG_MODIFIED)
2275 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2278 * We successfully decompressed the content,
2279 * and have to clean the header now, so the
2280 * client no longer expects compressed data..
2282 * XXX: There is a difference between cleaning
2283 * and removing it completely.
2285 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2288 else if (strstr(*header, "gzip"))
2290 /* Mark for gzip decompression */
2291 csp->content_type |= CT_GZIP;
2293 else if (strstr(*header, "deflate"))
2295 /* Mark for zlib decompression */
2296 csp->content_type |= CT_DEFLATE;
2298 else if (strstr(*header, "compress"))
2301 * We can't decompress this; therefore we can't filter
2304 csp->content_type |= CT_TABOO;
2306 #else /* !defined(FEATURE_ZLIB) */
2307 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2310 * Body is compressed, turn off pcrs and gif filtering.
2312 csp->content_type |= CT_TABOO;
2315 * Log a warning if the user expects the content to be filtered.
2317 if ((csp->rlist != NULL) &&
2318 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2320 log_error(LOG_LEVEL_INFO,
2321 "Compressed content detected, content filtering disabled. "
2322 "Consider recompiling Privoxy with zlib support or "
2323 "enable the prevent-compression action.");
2326 #endif /* defined(FEATURE_ZLIB) */
2333 /*********************************************************************
2335 * Function : server_content_length
2337 * Description : Adjust Content-Length header if we modified
2341 * 1 : csp = Current client state (buffers, headers, etc...)
2342 * 2 : header = On input, pointer to header to modify.
2343 * On output, pointer to the modified header, or NULL
2344 * to remove the header. This function frees the
2345 * original string if necessary.
2347 * Returns : JB_ERR_OK on success, or
2348 * JB_ERR_MEMORY on out-of-memory error.
2350 *********************************************************************/
2351 static jb_err server_content_length(struct client_state *csp, char **header)
2353 const size_t max_header_length = 80;
2355 /* Regenerate header if the content was modified. */
2356 if (csp->flags & CSP_FLAG_MODIFIED)
2359 *header = (char *) zalloc(max_header_length);
2360 if (*header == NULL)
2362 return JB_ERR_MEMORY;
2365 snprintf(*header, max_header_length, "Content-Length: %d",
2366 (int)csp->content_length);
2367 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2368 (int)csp->content_length);
2375 /*********************************************************************
2377 * Function : server_content_md5
2379 * Description : Crumble any Content-MD5 headers if the document was
2380 * modified. FIXME: Should we re-compute instead?
2383 * 1 : csp = Current client state (buffers, headers, etc...)
2384 * 2 : header = On input, pointer to header to modify.
2385 * On output, pointer to the modified header, or NULL
2386 * to remove the header. This function frees the
2387 * original string if necessary.
2389 * Returns : JB_ERR_OK on success, or
2390 * JB_ERR_MEMORY on out-of-memory error.
2392 *********************************************************************/
2393 static jb_err server_content_md5(struct client_state *csp, char **header)
2395 if (csp->flags & CSP_FLAG_MODIFIED)
2397 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2405 /*********************************************************************
2407 * Function : server_content_disposition
2409 * Description : If enabled, blocks or modifies the "content-disposition" header.
2410 * Called from `sed'.
2413 * 1 : csp = Current client state (buffers, headers, etc...)
2414 * 2 : header = On input, pointer to header to modify.
2415 * On output, pointer to the modified header, or NULL
2416 * to remove the header. This function frees the
2417 * original string if necessary.
2419 * Returns : JB_ERR_OK on success, or
2420 * JB_ERR_MEMORY on out-of-memory error.
2422 *********************************************************************/
2423 static jb_err server_content_disposition(struct client_state *csp, char **header)
2428 * Are we messing with the content-disposition header?
2430 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2436 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2438 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2441 * Blocking content-disposition header
2443 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2450 * Replacing content-disposition header
2453 *header = strdup("content-disposition: ");
2454 string_append(header, newval);
2456 if (*header == NULL)
2458 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2462 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2465 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2469 /*********************************************************************
2471 * Function : server_last_modified
2473 * Description : Changes Last-Modified header to the actual date
2474 * to help hide-if-modified-since.
2475 * Called from `sed'.
2478 * 1 : csp = Current client state (buffers, headers, etc...)
2479 * 2 : header = On input, pointer to header to modify.
2480 * On output, pointer to the modified header, or NULL
2481 * to remove the header. This function frees the
2482 * original string if necessary.
2484 * Returns : JB_ERR_OK on success, or
2485 * JB_ERR_MEMORY on out-of-memory error.
2487 *********************************************************************/
2488 static jb_err server_last_modified(struct client_state *csp, char **header)
2491 char buf[BUFFER_SIZE];
2494 #ifdef HAVE_GMTIME_R
2497 struct tm *timeptr = NULL;
2498 time_t now, last_modified;
2500 long int days, hours, minutes, seconds;
2503 * Are we messing with the Last-Modified header?
2505 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2511 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2513 if (0 == strcmpic(newval, "block") )
2516 * Blocking Last-Modified header. Useless but why not.
2518 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2522 else if (0 == strcmpic(newval, "reset-to-request-time"))
2525 * Setting Last-Modified Header to now.
2527 get_http_time(0, buf);
2529 *header = strdup("Last-Modified: ");
2530 string_append(header, buf);
2532 if (*header == NULL)
2534 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2538 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2541 else if (0 == strcmpic(newval, "randomize"))
2543 const char *header_time = *header + sizeof("Last-Modified:");
2545 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2547 #ifdef HAVE_GMTIME_R
2548 timeptr = gmtime_r(&now, &gmt);
2549 #elif FEATURE_PTHREAD
2550 pthread_mutex_lock(&gmtime_mutex);
2551 timeptr = gmtime(&now);
2552 pthread_mutex_unlock(&gmtime_mutex);
2554 timeptr = gmtime(&now);
2556 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2558 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2563 rtime = (long int)difftime(now, last_modified);
2566 rtime = pick_from_range(rtime);
2567 last_modified += rtime;
2568 #ifdef HAVE_GMTIME_R
2569 timeptr = gmtime_r(&last_modified, &gmt);
2570 #elif FEATURE_PTHREAD
2571 pthread_mutex_lock(&gmtime_mutex);
2572 timeptr = gmtime(&last_modified);
2573 pthread_mutex_unlock(&gmtime_mutex);
2575 timeptr = gmtime(&last_modified);
2577 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2579 *header = strdup("Last-Modified: ");
2580 string_append(header, newheader);
2582 if (*header == NULL)
2584 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2585 return JB_ERR_MEMORY;
2588 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2590 days = rtime / (3600 * 24);
2591 hours = rtime / 3600 % 24;
2592 minutes = rtime / 60 % 60;
2593 seconds = rtime % 60;
2595 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2596 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2597 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2602 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2611 /*********************************************************************
2613 * Function : client_accept_encoding
2615 * Description : Rewrite the client's Accept-Encoding header so that
2616 * if doesn't allow compression, if the action applies.
2617 * Note: For HTTP/1.0 the absence of the header is enough.
2620 * 1 : csp = Current client state (buffers, headers, etc...)
2621 * 2 : header = On input, pointer to header to modify.
2622 * On output, pointer to the modified header, or NULL
2623 * to remove the header. This function frees the
2624 * original string if necessary.
2626 * Returns : JB_ERR_OK on success, or
2627 * JB_ERR_MEMORY on out-of-memory error.
2629 *********************************************************************/
2630 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2632 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2634 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2638 /* Temporarily disable the correct behaviour to
2639 * work around a PHP bug.
2641 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2643 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2644 * if (*header == NULL)
2646 * return JB_ERR_MEMORY;
2657 /*********************************************************************
2659 * Function : client_te
2661 * Description : Rewrite the client's TE header so that
2662 * if doesn't allow compression, if the action applies.
2665 * 1 : csp = Current client state (buffers, headers, etc...)
2666 * 2 : header = On input, pointer to header to modify.
2667 * On output, pointer to the modified header, or NULL
2668 * to remove the header. This function frees the
2669 * original string if necessary.
2671 * Returns : JB_ERR_OK on success, or
2672 * JB_ERR_MEMORY on out-of-memory error.
2674 *********************************************************************/
2675 static jb_err client_te(struct client_state *csp, char **header)
2677 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2680 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2687 /*********************************************************************
2689 * Function : client_referrer
2691 * Description : Handle the "referer" config setting properly.
2692 * Called from `sed'.
2695 * 1 : csp = Current client state (buffers, headers, etc...)
2696 * 2 : header = On input, pointer to header to modify.
2697 * On output, pointer to the modified header, or NULL
2698 * to remove the header. This function frees the
2699 * original string if necessary.
2701 * Returns : JB_ERR_OK on success, or
2702 * JB_ERR_MEMORY on out-of-memory error.
2704 *********************************************************************/
2705 static jb_err client_referrer(struct client_state *csp, char **header)
2707 const char *parameter;
2708 /* booleans for parameters we have to check multiple times */
2709 int parameter_conditional_block;
2710 int parameter_conditional_forge;
2712 #ifdef FEATURE_FORCE_LOAD
2714 * Since the referrer can include the prefix even
2715 * if the request itself is non-forced, we must
2716 * clean it unconditionally.
2718 * XXX: strclean is too broad
2720 strclean(*header, FORCE_PREFIX);
2721 #endif /* def FEATURE_FORCE_LOAD */
2723 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2725 /* Nothing left to do */
2729 parameter = csp->action->string[ACTION_STRING_REFERER];
2730 assert(parameter != NULL);
2731 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2732 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2734 if (!parameter_conditional_block && !parameter_conditional_forge)
2737 * As conditional-block and conditional-forge are the only
2738 * parameters that rely on the original referrer, we can
2739 * remove it now for all the others.
2744 if (0 == strcmpic(parameter, "block"))
2746 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2749 else if (parameter_conditional_block || parameter_conditional_forge)
2751 return handle_conditional_hide_referrer_parameter(header,
2752 csp->http->hostport, parameter_conditional_block);
2754 else if (0 == strcmpic(parameter, "forge"))
2756 return create_forged_referrer(header, csp->http->hostport);
2760 /* interpret parameter as user-supplied referer to fake */
2761 return create_fake_referrer(header, parameter);
2766 /*********************************************************************
2768 * Function : client_accept_language
2770 * Description : Handle the "Accept-Language" config setting properly.
2771 * Called from `sed'.
2774 * 1 : csp = Current client state (buffers, headers, etc...)
2775 * 2 : header = On input, pointer to header to modify.
2776 * On output, pointer to the modified header, or NULL
2777 * to remove the header. This function frees the
2778 * original string if necessary.
2780 * Returns : JB_ERR_OK on success, or
2781 * JB_ERR_MEMORY on out-of-memory error.
2783 *********************************************************************/
2784 static jb_err client_accept_language(struct client_state *csp, char **header)
2789 * Are we messing with the Accept-Language?
2791 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2793 /*I don't think so*/
2797 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2799 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2802 * Blocking Accept-Language header
2804 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2811 * Replacing Accept-Language header
2814 *header = strdup("Accept-Language: ");
2815 string_append(header, newval);
2817 if (*header == NULL)
2819 log_error(LOG_LEVEL_ERROR,
2820 "Insufficent memory. Accept-Language header crunched without replacement.");
2824 log_error(LOG_LEVEL_HEADER,
2825 "Accept-Language header crunched and replaced with: %s", *header);
2828 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2832 /*********************************************************************
2834 * Function : crunch_client_header
2836 * Description : Crunch client header if it matches a string supplied by the
2837 * user. Called from `sed'.
2840 * 1 : csp = Current client state (buffers, headers, etc...)
2841 * 2 : header = On input, pointer to header to modify.
2842 * On output, pointer to the modified header, or NULL
2843 * to remove the header. This function frees the
2844 * original string if necessary.
2846 * Returns : JB_ERR_OK on success and always succeeds
2848 *********************************************************************/
2849 static jb_err crunch_client_header(struct client_state *csp, char **header)
2851 const char *crunch_pattern;
2853 /* Do we feel like crunching? */
2854 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2856 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2858 /* Is the current header the lucky one? */
2859 if (strstr(*header, crunch_pattern))
2861 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2869 /*********************************************************************
2871 * Function : client_uagent
2873 * Description : Handle the "user-agent" config setting properly
2874 * and remember its original value to enable browser
2875 * bug workarounds. Called from `sed'.
2878 * 1 : csp = Current client state (buffers, headers, etc...)
2879 * 2 : header = On input, pointer to header to modify.
2880 * On output, pointer to the modified header, or NULL
2881 * to remove the header. This function frees the
2882 * original string if necessary.
2884 * Returns : JB_ERR_OK on success, or
2885 * JB_ERR_MEMORY on out-of-memory error.
2887 *********************************************************************/
2888 static jb_err client_uagent(struct client_state *csp, char **header)
2892 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2897 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2904 *header = strdup("User-Agent: ");
2905 string_append(header, newval);
2907 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2909 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2913 /*********************************************************************
2915 * Function : client_ua
2917 * Description : Handle "ua-" headers properly. Called from `sed'.
2920 * 1 : csp = Current client state (buffers, headers, etc...)
2921 * 2 : header = On input, pointer to header to modify.
2922 * On output, pointer to the modified header, or NULL
2923 * to remove the header. This function frees the
2924 * original string if necessary.
2926 * Returns : JB_ERR_OK on success, or
2927 * JB_ERR_MEMORY on out-of-memory error.
2929 *********************************************************************/
2930 static jb_err client_ua(struct client_state *csp, char **header)
2932 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2934 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2942 /*********************************************************************
2944 * Function : client_from
2946 * Description : Handle the "from" config setting properly.
2947 * Called from `sed'.
2950 * 1 : csp = Current client state (buffers, headers, etc...)
2951 * 2 : header = On input, pointer to header to modify.
2952 * On output, pointer to the modified header, or NULL
2953 * to remove the header. This function frees the
2954 * original string if necessary.
2956 * Returns : JB_ERR_OK on success, or
2957 * JB_ERR_MEMORY on out-of-memory error.
2959 *********************************************************************/
2960 static jb_err client_from(struct client_state *csp, char **header)
2964 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2971 newval = csp->action->string[ACTION_STRING_FROM];
2974 * Are we blocking the e-mail address?
2976 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2978 log_error(LOG_LEVEL_HEADER, "crunched From!");
2982 log_error(LOG_LEVEL_HEADER, " modified");
2984 *header = strdup("From: ");
2985 string_append(header, newval);
2987 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2991 /*********************************************************************
2993 * Function : client_send_cookie
2995 * Description : Crunches the "cookie" header if necessary.
2996 * Called from `sed'.
2998 * XXX: Stupid name, doesn't send squat.
3001 * 1 : csp = Current client state (buffers, headers, etc...)
3002 * 2 : header = On input, pointer to header to modify.
3003 * On output, pointer to the modified header, or NULL
3004 * to remove the header. This function frees the
3005 * original string if necessary.
3007 * Returns : JB_ERR_OK on success, or
3008 * JB_ERR_MEMORY on out-of-memory error.
3010 *********************************************************************/
3011 static jb_err client_send_cookie(struct client_state *csp, char **header)
3013 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3015 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3023 /*********************************************************************
3025 * Function : client_x_forwarded
3027 * Description : Handle the "x-forwarded-for" config setting properly,
3028 * also used in the add_client_headers list. Called from `sed'.
3031 * 1 : csp = Current client state (buffers, headers, etc...)
3032 * 2 : header = On input, pointer to header to modify.
3033 * On output, pointer to the modified header, or NULL
3034 * to remove the header. This function frees the
3035 * original string if necessary.
3037 * Returns : JB_ERR_OK on success, or
3038 * JB_ERR_MEMORY on out-of-memory error.
3040 *********************************************************************/
3041 jb_err client_x_forwarded(struct client_state *csp, char **header)
3043 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3045 /* Save it so we can re-add it later */
3046 freez(csp->x_forwarded);
3047 csp->x_forwarded = *header;
3050 * Always set *header = NULL, since this information
3051 * will be sent at the end of the header.
3058 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3065 /*********************************************************************
3067 * Function : client_max_forwards
3069 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3070 * from the value of the Max-Forwards header field.
3073 * 1 : csp = Current client state (buffers, headers, etc...)
3074 * 2 : header = On input, pointer to header to modify.
3075 * On output, pointer to the modified header, or NULL
3076 * to remove the header. This function frees the
3077 * original string if necessary.
3079 * Returns : JB_ERR_OK on success, or
3080 * JB_ERR_MEMORY on out-of-memory error.
3082 *********************************************************************/
3083 static jb_err client_max_forwards(struct client_state *csp, char **header)
3087 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3088 (0 == strcmpic(csp->http->gpc, "options")))
3090 assert(*(*header+12) == ':');
3091 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3093 if (max_forwards > 0)
3095 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3096 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3097 csp->http->gpc, max_forwards);
3099 else if (max_forwards < 0)
3101 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3107 * Not supposed to be reached. direct_response() which
3108 * was already called earlier in chat() should have
3109 * intercepted the request.
3111 log_error(LOG_LEVEL_ERROR,
3112 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3113 assert(max_forwards != 0);
3118 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3127 /*********************************************************************
3129 * Function : client_host
3131 * Description : If the request URI did not contain host and
3132 * port information, parse and evaluate the Host
3135 * Also, kill ill-formed HOST: headers as sent by
3136 * Apple's iTunes software when used with a proxy.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK on success, or
3146 * JB_ERR_MEMORY on out-of-memory error.
3148 *********************************************************************/
3149 static jb_err client_host(struct client_state *csp, char **header)
3154 * If the header field name is all upper-case, chances are that it's
3155 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3156 * not a problem -- they are regenerated later.
3158 if ((*header)[1] == 'O')
3160 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3165 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3166 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3169 if (NULL == (p = strdup((*header)+6)))
3171 return JB_ERR_MEMORY;
3174 if (NULL == (q = strdup(p)))
3177 return JB_ERR_MEMORY;
3180 freez(csp->http->hostport);
3181 csp->http->hostport = p;
3182 freez(csp->http->host);
3183 csp->http->host = q;
3184 q = strchr(csp->http->host, ':');
3187 /* Terminate hostname and evaluate port string */
3189 csp->http->port = atoi(q);
3193 csp->http->port = csp->http->ssl ? 443 : 80;
3196 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3197 csp->http->hostport, csp->http->host, csp->http->port);
3200 /* Signal client_host_adder() to return right away */
3201 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3207 /*********************************************************************
3209 * Function : client_if_modified_since
3211 * Description : Remove or modify the If-Modified-Since header.
3214 * 1 : csp = Current client state (buffers, headers, etc...)
3215 * 2 : header = On input, pointer to header to modify.
3216 * On output, pointer to the modified header, or NULL
3217 * to remove the header. This function frees the
3218 * original string if necessary.
3220 * Returns : JB_ERR_OK on success, or
3221 * JB_ERR_MEMORY on out-of-memory error.
3223 *********************************************************************/
3224 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3227 #ifdef HAVE_GMTIME_R
3230 struct tm *timeptr = NULL;
3234 long int hours, minutes, seconds;
3238 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3241 * The client got an error message because of a temporary problem,
3242 * the problem is gone and the client now tries to revalidate our
3243 * error message on the real server. The revalidation would always
3244 * end with the transmission of the whole document and there is
3245 * no need to expose the bogus If-Modified-Since header.
3247 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3250 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3252 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3254 if ((0 == strcmpic(newval, "block")))
3256 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3259 else /* add random value */
3261 const char *header_time = *header + sizeof("If-Modified-Since:");
3263 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3265 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3270 rtime = strtol(newval, &endptr, 0);
3273 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3274 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3281 rtime = pick_from_range(rtime);
3285 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3288 tm += rtime * (negative ? -1 : 1);
3289 #ifdef HAVE_GMTIME_R
3290 timeptr = gmtime_r(&tm, &gmt);
3291 #elif FEATURE_PTHREAD
3292 pthread_mutex_lock(&gmtime_mutex);
3293 timeptr = gmtime(&tm);
3294 pthread_mutex_unlock(&gmtime_mutex);
3296 timeptr = gmtime(&tm);
3298 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3301 *header = strdup("If-Modified-Since: ");
3302 string_append(header, newheader);
3304 if (*header == NULL)
3306 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3307 return JB_ERR_MEMORY;
3310 if (LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3312 hours = rtime / 3600;
3313 minutes = rtime / 60 % 60;
3314 seconds = rtime % 60;
3316 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3317 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3318 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3328 /*********************************************************************
3330 * Function : client_if_none_match
3332 * Description : Remove the If-None-Match header.
3335 * 1 : csp = Current client state (buffers, headers, etc...)
3336 * 2 : header = On input, pointer to header to modify.
3337 * On output, pointer to the modified header, or NULL
3338 * to remove the header. This function frees the
3339 * original string if necessary.
3341 * Returns : JB_ERR_OK on success, or
3342 * JB_ERR_MEMORY on out-of-memory error.
3344 *********************************************************************/
3345 static jb_err client_if_none_match(struct client_state *csp, char **header)
3347 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3349 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3357 /*********************************************************************
3359 * Function : client_x_filter
3361 * Description : Disables filtering if the client set "X-Filter: No".
3362 * Called from `sed'.
3365 * 1 : csp = Current client state (buffers, headers, etc...)
3366 * 2 : header = On input, pointer to header to modify.
3367 * On output, pointer to the modified header, or NULL
3368 * to remove the header. This function frees the
3369 * original string if necessary.
3371 * Returns : JB_ERR_OK on success
3373 *********************************************************************/
3374 jb_err client_x_filter(struct client_state *csp, char **header)
3376 if ( 0 == strcmpic(*header, "X-Filter: No"))
3378 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3380 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3384 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3386 log_error(LOG_LEVEL_HEADER,
3387 "force-text-mode overruled the client's request to fetch without filtering!");
3391 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3392 csp->flags |= CSP_FLAG_NO_FILTERING;
3393 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3395 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3402 /* the following functions add headers directly to the header list */
3404 /*********************************************************************
3406 * Function : client_host_adder
3408 * Description : Adds the Host: header field if it is missing.
3409 * Called from `sed'.
3412 * 1 : csp = Current client state (buffers, headers, etc...)
3414 * Returns : JB_ERR_OK on success, or
3415 * JB_ERR_MEMORY on out-of-memory error.
3417 *********************************************************************/
3418 static jb_err client_host_adder(struct client_state *csp)
3423 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3425 /* Header already set by the client, nothing to do. */
3429 if ( !csp->http->hostport || !*(csp->http->hostport))
3431 /* XXX: When does this happen and why is it OK? */
3432 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3437 * remove 'user:pass@' from 'proto://user:pass@host'
3439 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3445 p = csp->http->hostport;
3448 /* XXX: Just add it, we already made sure that it will be unique */
3449 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3450 err = enlist_unique_header(csp->headers, "Host", p);
3456 /*********************************************************************
3458 * Function : client_cookie_adder
3460 * Description : Used in the add_client_headers list to add "wafers".
3461 * Called from `sed'.
3464 * 1 : csp = Current client state (buffers, headers, etc...)
3466 * Returns : JB_ERR_OK on success, or
3467 * JB_ERR_MEMORY on out-of-memory error.
3469 *********************************************************************/
3470 jb_err client_cookie_adder(struct client_state *csp)
3473 struct list_entry *wafer;
3474 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3477 if (NULL == wafer_list)
3483 tmp = strdup("Cookie: ");
3485 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3487 if (wafer != wafer_list)
3489 /* As this isn't the first wafer, we need a delimiter. */
3490 string_append(&tmp, "; ");
3492 string_join(&tmp, cookie_encode(wafer->str));
3497 return JB_ERR_MEMORY;
3500 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3501 err = enlist(csp->headers, tmp);
3508 /*********************************************************************
3510 * Function : client_accept_encoding_adder
3512 * Description : Add an Accept-Encoding header to the client's request
3513 * that disables compression if the action applies, and
3514 * the header is not already there. Called from `sed'.
3515 * Note: For HTTP/1.0, the absence of the header is enough.
3518 * 1 : csp = Current client state (buffers, headers, etc...)
3520 * Returns : JB_ERR_OK on success, or
3521 * JB_ERR_MEMORY on out-of-memory error.
3523 *********************************************************************/
3524 static jb_err client_accept_encoding_adder(struct client_state *csp)
3526 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3527 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3529 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3537 /*********************************************************************
3539 * Function : client_xtra_adder
3541 * Description : Used in the add_client_headers list. Called from `sed'.
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_xtra_adder(struct client_state *csp)
3552 struct list_entry *lst;
3555 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3556 lst ; lst = lst->next)
3558 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3559 err = enlist(csp->headers, lst->str);
3571 /*********************************************************************
3573 * Function : client_x_forwarded_adder
3575 * Description : Used in the add_client_headers list. Called from `sed'.
3578 * 1 : csp = Current client state (buffers, headers, etc...)
3580 * Returns : JB_ERR_OK on success, or
3581 * JB_ERR_MEMORY on out-of-memory error.
3583 *********************************************************************/
3584 static jb_err client_x_forwarded_adder(struct client_state *csp)
3589 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3594 if (csp->x_forwarded)
3596 p = strdup(csp->x_forwarded);
3597 string_append(&p, ", ");
3601 p = strdup("X-Forwarded-For: ");
3603 string_append(&p, csp->ip_addr_str);
3607 return JB_ERR_MEMORY;
3610 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3611 err = enlist(csp->headers, p);
3618 /*********************************************************************
3620 * Function : connection_close_adder
3622 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3623 * support. Adds a "Connection: close" header to csp->headers
3624 * unless the header was already present. Called from `sed'.
3626 * FIXME: This whole function shouldn't be neccessary!
3629 * 1 : csp = Current client state (buffers, headers, etc...)
3631 * Returns : JB_ERR_OK on success, or
3632 * JB_ERR_MEMORY on out-of-memory error.
3634 *********************************************************************/
3635 static jb_err connection_close_adder(struct client_state *csp)
3637 const unsigned int flags = csp->flags;
3640 * Return right away if
3642 * - we're parsing server headers and the server header
3643 * "Connection: close" is already set, or if
3645 * - we're parsing client headers and the client header
3646 * "Connection: close" is already set.
3648 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3649 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3650 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3651 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3656 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3658 return enlist(csp->headers, "Connection: close");
3662 /*********************************************************************
3664 * Function : server_http
3666 * Description : - Save the HTTP Status into csp->http->status
3667 * - Set CT_TABOO to prevent filtering if the answer
3668 * is a partial range (HTTP status 206)
3669 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3673 * 1 : csp = Current client state (buffers, headers, etc...)
3674 * 2 : header = On input, pointer to header to modify.
3675 * On output, pointer to the modified header, or NULL
3676 * to remove the header. This function frees the
3677 * original string if necessary.
3679 * Returns : JB_ERR_OK on success, or
3680 * JB_ERR_MEMORY on out-of-memory error.
3682 *********************************************************************/
3683 static jb_err server_http(struct client_state *csp, char **header)
3685 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3686 if (csp->http->status == 206)
3688 csp->content_type = CT_TABOO;
3691 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3693 /* XXX: Should we do a real validity check here? */
3694 if (strlen(*header) > 8)
3697 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3702 * XXX: Should we block the request or
3703 * enlist a valid status code line here?
3705 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3706 "Downgrading to HTTP/1.0 impossible.");
3714 /*********************************************************************
3716 * Function : server_set_cookie
3718 * Description : Handle the server "cookie" header properly.
3719 * Log cookie to the jar file. Then "crunch",
3720 * accept or rewrite it to a session cookie.
3721 * Called from `sed'.
3723 * TODO: Allow the user to specify a new expiration
3724 * time to cause the cookie to expire even before the
3725 * browser is closed.
3728 * 1 : csp = Current client state (buffers, headers, etc...)
3729 * 2 : header = On input, pointer to header to modify.
3730 * On output, pointer to the modified header, or NULL
3731 * to remove the header. This function frees the
3732 * original string if necessary.
3734 * Returns : JB_ERR_OK on success, or
3735 * JB_ERR_MEMORY on out-of-memory error.
3737 *********************************************************************/
3738 static jb_err server_set_cookie(struct client_state *csp, char **header)
3745 #ifdef FEATURE_COOKIE_JAR
3746 if (csp->config->jar)
3749 * Write timestamp into outbuf.
3751 * Complex because not all OSs have tm_gmtoff or
3752 * the %z field in strftime()
3754 char tempbuf[ BUFFER_SIZE ];
3756 #ifdef HAVE_LOCALTIME_R
3757 tm_now = *localtime_r(&now, &tm_now);
3758 #elif FEATURE_PTHREAD
3759 pthread_mutex_lock(&localtime_mutex);
3760 tm_now = *localtime (&now);
3761 pthread_mutex_unlock(&localtime_mutex);
3763 tm_now = *localtime (&now);
3765 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3767 /* strlen("set-cookie: ") = 12 */
3768 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3770 #endif /* def FEATURE_COOKIE_JAR */
3772 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3774 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3777 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3779 /* Flag whether or not to log a message */
3782 /* A variable to store the tag we're working on */
3785 /* Skip "Set-Cookie:" (11 characters) in header */
3786 cur_tag = *header + 11;
3788 /* skip whitespace between "Set-Cookie:" and value */
3789 while (*cur_tag && ijb_isspace(*cur_tag))
3794 /* Loop through each tag in the cookie */
3798 char *next_tag = strchr(cur_tag, ';');
3799 if (next_tag != NULL)
3801 /* Skip the ';' character itself */
3804 /* skip whitespace ";" and start of tag */
3805 while (*next_tag && ijb_isspace(*next_tag))
3812 /* "Next tag" is the end of the string */
3813 next_tag = cur_tag + strlen(cur_tag);
3817 * Check the expiration date to see
3818 * if the cookie is still valid, if yes,
3819 * rewrite it to a session cookie.
3821 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3823 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3825 /* Did we detect the date properly? */
3826 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3829 * Nope, treat it as if it was still valid.
3831 * XXX: Should we remove the whole cookie instead?
3833 log_error(LOG_LEVEL_ERROR,
3834 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3835 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3841 * Yes. Check if the cookie is still valid.
3843 * If the cookie is already expired it's probably
3844 * a delete cookie and even if it isn't, the browser
3845 * will discard it anyway.
3849 * XXX: timegm() isn't available on some AmigaOS
3850 * versions and our replacement doesn't work.
3852 * Our options are to either:
3854 * - disable session-cookies-only completely if timegm
3857 * - to simply remove all expired tags, like it has
3858 * been done until Privoxy 3.0.6 and to live with
3859 * the consequence that it can cause login/logout
3860 * problems on servers that don't validate their
3861 * input properly, or
3863 * - to replace it with mktime in which
3864 * case there is a slight chance of valid cookies
3865 * passing as already expired.
3867 * This is the way it's currently done and it's not
3868 * as bad as it sounds. If the missing GMT offset is
3869 * enough to change the result of the expiration check
3870 * the cookie will be only valid for a few hours
3871 * anyway, which in many cases will be shorter
3872 * than a browser session.
3874 if (cookie_time - now < 0)
3876 log_error(LOG_LEVEL_HEADER,
3877 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3878 /* Just in case some clown sets more then one expiration date */
3884 * Still valid, delete expiration date by copying
3885 * the rest of the string over it.
3887 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3888 * since the behaviour of strcpy is undefined for overlapping
3891 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3893 /* That changed the header, need to issue a log message */
3897 * Note that the next tag has now been moved to *cur_tag,
3898 * so we do not need to update the cur_tag pointer.
3906 /* Move on to next cookie tag */
3913 assert(NULL != *header);
3914 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3923 #ifdef FEATURE_FORCE_LOAD
3924 /*********************************************************************
3926 * Function : strclean
3928 * Description : In-Situ-Eliminate all occurances of substring in
3932 * 1 : string = string to clean
3933 * 2 : substring = substring to eliminate
3935 * Returns : Number of eliminations
3937 *********************************************************************/
3938 int strclean(const char *string, const char *substring)
3944 len = strlen(substring);
3946 while((pos = strstr(string, substring)) != NULL)
3953 while (*p++ != '\0');
3960 #endif /* def FEATURE_FORCE_LOAD */
3963 /*********************************************************************
3965 * Function : parse_header_time
3967 * Description : Parses time formats used in HTTP header strings
3968 * to get the numerical respresentation.
3971 * 1 : header_time = HTTP header time as string.
3972 * 2 : result = storage for header_time in seconds
3974 * Returns : JB_ERR_OK if the time format was recognized, or
3975 * JB_ERR_PARSE otherwise.
3977 *********************************************************************/
3978 static jb_err parse_header_time(const char *header_time, time_t *result)
3983 * Zero out gmt to prevent time zone offsets.
3985 * While this is only necessary on some platforms
3986 * (mingw32 for example), I don't know how to
3987 * detect these automatically and doing it everywhere
3990 memset(&gmt, 0, sizeof(gmt));
3992 /* Tue, 02 Jun 2037 20:00:00 */
3993 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3994 /* Tue, 02-Jun-2037 20:00:00 */
3995 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3996 /* Tue, 02-Jun-37 20:00:00 */
3997 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3998 /* Tuesday, 02-Jun-2037 20:00:00 */
3999 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4000 /* Tuesday Jun 02 20:00:00 2037 */
4001 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4003 return JB_ERR_PARSE;
4006 *result = timegm(&gmt);
4013 /*********************************************************************
4015 * Function : get_destination_from_headers
4017 * Description : Parse the "Host:" header to get the request's destination.
4018 * Only needed if the client's request was forcefully
4019 * redirected into Privoxy.
4021 * Code mainly copied from client_host() which is currently
4022 * run too late for this purpose.
4025 * 1 : headers = List of headers (one of them hopefully being
4026 * the "Host:" header)
4027 * 2 : http = storage for the result (host, port and hostport).
4029 * Returns : JB_ERR_MEMORY in case of memory problems,
4030 * JB_ERR_PARSE if the host header couldn't be found,
4031 * JB_ERR_OK otherwise.
4033 *********************************************************************/
4034 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4040 host = get_header_value(headers, "Host:");
4044 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4045 return JB_ERR_PARSE;
4048 if (NULL == (p = strdup((host))))
4050 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4051 return JB_ERR_MEMORY;
4054 if (NULL == (q = strdup(p)))
4057 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4058 return JB_ERR_MEMORY;
4061 freez(http->hostport);
4065 q = strchr(http->host, ':');
4068 /* Terminate hostname and evaluate port string */
4070 http->port = atoi(q);
4074 http->port = http->ssl ? 443 : 80;
4077 /* Rebuild request URL */
4079 http->url = strdup(http->ssl ? "https://" : "http://");
4080 string_append(&http->url, http->hostport);
4081 string_append(&http->url, http->path);
4082 if (http->url == NULL)
4084 return JB_ERR_MEMORY;
4087 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4095 /*********************************************************************
4097 * Function : create_forged_referrer
4099 * Description : Helper for client_referrer to forge a referer as
4100 * 'http://[hostname:port/' to fool stupid
4101 * checks for in-site links
4104 * 1 : header = Pointer to header pointer
4105 * 2 : hostport = Host and optionally port as string
4107 * Returns : JB_ERR_OK in case of success, or
4108 * JB_ERR_MEMORY in case of memory problems.
4110 *********************************************************************/
4111 static jb_err create_forged_referrer(char **header, const char *hostport)
4113 assert(NULL == *header);
4115 *header = strdup("Referer: http://");
4116 string_append(header, hostport);
4117 string_append(header, "/");
4119 if (NULL == *header)
4121 return JB_ERR_MEMORY;
4124 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4131 /*********************************************************************
4133 * Function : create_fake_referrer
4135 * Description : Helper for client_referrer to create a fake referrer
4136 * based on a string supplied by the user.
4139 * 1 : header = Pointer to header pointer
4140 * 2 : hosthost = Referrer to fake
4142 * Returns : JB_ERR_OK in case of success, or
4143 * JB_ERR_MEMORY in case of memory problems.
4145 *********************************************************************/
4146 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4148 assert(NULL == *header);
4150 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4152 log_error(LOG_LEVEL_HEADER,
4153 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4155 *header = strdup("Referer: ");
4156 string_append(header, fake_referrer);
4158 if (NULL == *header)
4160 return JB_ERR_MEMORY;
4163 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4170 /*********************************************************************
4172 * Function : handle_conditional_hide_referrer_parameter
4174 * Description : Helper for client_referrer to crunch or forge
4175 * the referrer header if the host has changed.
4178 * 1 : header = Pointer to header pointer
4179 * 2 : host = The target host (may include the port)
4180 * 3 : parameter_conditional_block = Boolean to signal
4181 * if we're in conditional-block mode. If not set,
4182 * we're in conditional-forge mode.
4184 * Returns : JB_ERR_OK in case of success, or
4185 * JB_ERR_MEMORY in case of memory problems.
4187 *********************************************************************/
4188 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4189 const char *host, const int parameter_conditional_block)
4191 char *referer = strdup(*header);
4192 const size_t hostlenght = strlen(host);
4194 if (NULL == referer)
4197 return JB_ERR_MEMORY;
4200 /* referer begins with 'Referer: http[s]://' */
4201 if (hostlenght < (strlen(referer)-17))
4204 * Shorten referer to make sure the referer is blocked
4205 * if www.example.org/www.example.com-shall-see-the-referer/
4206 * links to www.example.com/
4208 referer[hostlenght+17] = '\0';
4210 if (NULL == strstr(referer, host))
4212 /* Host has changed */
4213 if (parameter_conditional_block)
4215 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4222 return create_forged_referrer(header, host);