1 const char parsers_rcs[] = "$Id: parsers.c,v 1.106 2007/08/18 14:30:32 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.106 2007/08/18 14:30:32 fabiankeil
48 * Let content-type-overwrite{} honour force-text-mode again.
50 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
51 * - Add prototpyes for the header parsers and make them static.
52 * - Comment out client_accept_encoding_adder() which isn't used right now.
54 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
55 * Move the ACTION_FORCE_TEXT_MODE check out of
56 * server_content_type(). Signal other functions
57 * whether or not a content type has been declared.
58 * Part of the fix for BR#1750917.
60 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
61 * Change sed() to return a jb_err in preparation for forward-override{}.
63 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
64 * Adjust "X-Filter: No" to disable dedicated header filters.
66 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
67 * Streamline client_cookie_adder().
69 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
70 * Make sure filters with dynamic jobs actually use them.
72 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
73 * - Introduce dynamic pcrs jobs that can resolve variables.
74 * - Remove unnecessary update_action_bits_for_all_tags() call.
76 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
77 * - Make tagging based on tags set by earlier taggers
78 * of the same kind possible.
79 * - Log whether or not new tags cause action bits updates
80 * (in which case a matching tag-pattern section exists).
81 * - Log if the user tries to set a tag that is already set.
83 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
84 * Introduce tags as alternative way to specify which
85 * actions apply to a request. At the moment tags can be
86 * created based on client and server headers.
88 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
89 * Log a warning if the content is compressed, filtering is
90 * enabled and Privoxy was compiled without zlib support.
93 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
94 * - Fix warnings when compiled with glibc.
95 * - Don't use crumble() for cookie crunching.
96 * - Move cookie time parsing into parse_header_time().
97 * - Let parse_header_time() return a jb_err code
98 * instead of a pointer that can only be used to
99 * check for NULL anyway.
101 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
102 * - Add better protection against malicious gzip headers.
103 * - Stop logging the first hundred bytes of decompressed content.
104 * It looks like it's working and there is always debug 16.
105 * - Log the content size after decompression in decompress_iob()
106 * instead of pcrs_filter_response().
108 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
109 * - Use dedicated header filter actions instead of abusing "filter".
110 * Replace "filter-client-headers" and "filter-client-headers"
111 * with "server-header-filter" and "client-header-filter".
112 * - Remove filter_client_header() and filter_client_header(),
113 * filter_header() now checks the shiny new
114 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
116 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
117 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
118 * - Handle "Cookie:" and "Connection:" headers a bit smarter
119 * (don't crunch them just to recreate them later on).
120 * - Add another non-standard time format for the cookie
121 * expiration date detection.
122 * - Fix a valgrind warning.
124 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
125 * Improve cookie expiration date detection.
127 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
128 * Don't run server_content_length() the first time
129 * sed() parses server headers; only adjust the
130 * Content-Length header if the page was modified.
132 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
133 * Fix log messages regarding the cookie time format
134 * (cookie and request URL were mixed up).
136 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
137 * - Let decompress_iob()
138 * - not corrupt the content if decompression fails
139 * early. (the first byte(s) were lost).
140 * - use pointer arithmetics with defined outcome for
142 * - Use a different kludge to remember a failed decompression.
144 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
145 * Search for Max-Forwards headers case-insensitive,
146 * don't generate the "501 unsupported" message for invalid
147 * Max-Forwards values and don't increase negative ones.
149 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
150 * - Let server_set_cookie() check the expiration date
151 * of cookies and don't touch the ones that are already
152 * expired. Fixes problems with low quality web applications
153 * as described in BR 932612.
155 * - Adjust comment in client_max_forwards to reality;
156 * remove invalid Max-Forwards headers.
158 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
159 * Stop filter_header() from unintentionally removing
160 * empty header lines that were enlisted by the continue
163 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
164 * - Repeat the request URL before logging any headers.
165 * Makes reading the log easier in case of simultaneous requests.
166 * - If there are more than one Content-Type headers in one request,
167 * use the first one and remove the others.
168 * - Remove "newval" variable in server_content_type().
169 * It's only used once.
171 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
172 * Correct a cast, check inflateEnd() exit code
173 * to see if we have to, replace sprintf calls
176 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
177 * Integrate a modified version of Wil Mahan's
178 * zlib patch (PR #895531).
180 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
181 * Skip empty filter files in filter_header()
182 * but don't ignore the ones that come afterwards.
183 * Fixes BR 1619208, this time for real.
185 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
186 * Reverted parts of my last commit
187 * to keep error handling working.
189 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
190 * Fixed gcc43 conversion warnings.
192 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
193 * Bringing back the "useless" localtime() call
194 * I removed in revision 1.67. On some platforms
195 * it's necessary to prevent time zone offsets.
197 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
198 * Rebuild request URL in get_destination_from_headers()
199 * to make sure redirect{pcrs command} works as expected
200 * for intercepted requests.
202 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
203 * Added get_destination_from_headers().
205 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
206 * Make pthread mutex locking more generic. Instead of
207 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
208 * and use mutex locking unless there is an _r function
209 * available. Better safe than sorry.
211 * Fixes "./configure --disable-pthread" and should result
212 * in less threading-related problems on pthread-using platforms,
213 * but it still doesn't fix BR#1122404.
215 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
216 * The special header "X-Filter: No" now disables
217 * header filtering as well.
219 * Revision 1.73 2006/09/23 13:26:38 roro
220 * Replace TABs by spaces in source code.
222 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
223 * Don't print a log message every time filter_headers is
224 * entered or left. It only creates noise without any real
227 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
228 * Fix +hide-if-modified-since{-n}.
230 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
231 * Have hide-if-modified-since interpret the random
232 * range value as minutes instead of hours. Allows
233 * more fine-grained configuration.
235 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
236 * Always have parse_header_time return a pointer
237 * that actual makes sense, even though we currently
238 * only need it to detect problems.
240 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
241 * Added config option enable-remote-http-toggle
242 * to specify if Privoxy should recognize special
243 * headers (currently only X-Filter) to change its
244 * behaviour. Disabled by default.
246 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
247 * After filtering de-chunked instances, remove
248 * "Transfer-Encoding" header entirely instead of changing
249 * it to "Transfer-Encoding: identity", which is invalid.
250 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
252 * Don't use localtime in parse_header_time. An empty time struct
253 * is good enough, it gets overwritten by strptime anyway.
255 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
256 * Use gmtime_r if available, fallback to gmtime with mutex
257 * protection for MacOSX and use vanilla gmtime for the rest.
259 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
260 * Changed client_referrer to use the right type (size_t) for
261 * hostlenght and to shorten the temporary referrer string with
262 * '\0' instead of adding a useless line break.
264 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
265 * - Back to timegm() using GnuPG's replacement if necessary.
266 * Using mktime() and localtime() could add a on hour offset if
267 * the randomize factor was big enough to lead to a summer/wintertime
270 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
272 * - Moved randomization code into pick_from_range().
274 * - Changed parse_header_time definition.
275 * time_t isn't guaranteed to be signed and
276 * if it isn't, -1 isn't available as error code.
277 * Changed some variable types in client_if_modified_since()
278 * because of the same reason.
280 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
281 * OS/2 compilation compatibility fixups
283 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
284 * Changed include from strptime.c to strptime.h
286 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
287 * Split filter-headers{} into filter-client-headers{}
288 * and filter-server-headers{}.
289 * Added parse_header_time() to share some code.
290 * Replaced timegm() with mktime().
292 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
293 * Windows service integration
295 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
296 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
298 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
299 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
300 * with what was really the latest development (the v_3_0_branch branch)
302 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
303 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
305 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
306 * Add the ability to check jpeg images for invalid
307 * lengths of comment blocks. Defensive strategy
308 * against the exploit:
309 * Microsoft Security Bulletin MS04-028
310 * Buffer Overrun in JPEG Processing (GDI+) Could
311 * Allow Code Execution (833987)
312 * Enabled with +inspect-jpegs in actions files.
314 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
315 * Excluded text/plain objects from filtering. This fixes a
316 * couple of client-crashing, download corruption and
317 * Privoxy performance issues, whose root cause lies in
318 * web servers labelling content of unknown type as text/plain.
320 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
321 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
323 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
324 * Completing the previous change
326 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
327 * Added temporary workaround for bug in PHP < 4.2.3
329 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
330 * 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.
332 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
333 * Fix typo: supressed -> suppressed
335 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
336 * Improved cookie logging
338 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
339 * Added basic support for OPTIONS and TRACE HTTP methods:
340 * - New parser function client_max_forwards which decrements
341 * the Max-Forwards HTTP header field of OPTIONS and TRACE
342 * requests by one before forwarding
343 * - New parser function client_host which extracts the host
344 * and port information from the HTTP header field if the
345 * request URI was not absolute
346 * - Don't crumble and re-add the Host: header, but only generate
347 * and append if missing
349 * Revision 1.56 2002/05/12 15:34:22 jongfoster
350 * Fixing typo in a comment
352 * Revision 1.55 2002/05/08 16:01:07 oes
353 * Optimized add_to_iob:
354 * - Use realloc instead of malloc(), memcpy(), free()
355 * - Expand to powers of two if possible, to get
356 * O(log n) reallocs instead of O(n).
357 * - Moved check for buffer limit here from chat
358 * - Report failure via returncode
360 * Revision 1.54 2002/04/02 15:03:16 oes
361 * Tiny code cosmetics
363 * Revision 1.53 2002/03/26 22:29:55 swa
364 * we have a new homepage!
366 * Revision 1.52 2002/03/24 13:25:43 swa
367 * name change related issues
369 * Revision 1.51 2002/03/13 00:27:05 jongfoster
372 * Revision 1.50 2002/03/12 01:45:35 oes
373 * More verbose logging
375 * Revision 1.49 2002/03/09 20:03:52 jongfoster
376 * - Making various functions return int rather than size_t.
377 * (Undoing a recent change). Since size_t is unsigned on
378 * Windows, functions like read_socket that return -1 on
379 * error cannot return a size_t.
381 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
382 * crashes, and also frequently caused JB to jump to 100%
383 * CPU and stay there. (Because it thought it had just
384 * read ((unsigned)-1) == 4Gb of data...)
386 * - The signature of write_socket has changed, it now simply
387 * returns success=0/failure=nonzero.
389 * - Trying to get rid of a few warnings --with-debug on
390 * Windows, I've introduced a new type "jb_socket". This is
391 * used for the socket file descriptors. On Windows, this
392 * is SOCKET (a typedef for unsigned). Everywhere else, it's
393 * an int. The error value can't be -1 any more, so it's
394 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
395 * Windows it maps to the #define INVALID_SOCKET.)
397 * - The signature of bind_port has changed.
399 * Revision 1.48 2002/03/07 03:46:53 oes
400 * Fixed compiler warnings etc
402 * Revision 1.47 2002/02/20 23:15:13 jongfoster
403 * Parsing functions now handle out-of-memory gracefully by returning
406 * Revision 1.46 2002/01/17 21:03:47 jongfoster
407 * Moving all our URL and URL pattern parsing code to urlmatch.c.
409 * Revision 1.45 2002/01/09 14:33:03 oes
410 * Added support for localtime_r.
412 * Revision 1.44 2001/12/14 01:22:54 steudten
413 * Remove 'user:pass@' from 'proto://user:pass@host' for the
414 * new added header 'Host: ..'. (See Req ID 491818)
416 * Revision 1.43 2001/11/23 00:26:38 jongfoster
417 * Fixing two really stupid errors in my previous commit
419 * Revision 1.42 2001/11/22 21:59:30 jongfoster
420 * Adding code to handle +no-cookies-keep
422 * Revision 1.41 2001/11/05 23:43:05 steudten
423 * Add time+date to log files.
425 * Revision 1.40 2001/10/26 20:13:09 jongfoster
426 * ctype.h is needed in Windows, too.
428 * Revision 1.39 2001/10/26 17:40:04 oes
429 * Introduced get_header_value()
430 * Removed http->user_agent, csp->referrer and csp->accept_types
431 * Removed client_accept()
433 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
434 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
435 * threads to call select() simultaneously. So, it's time to do a real, live,
436 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
437 * (native). Both versions will work, but using __OS2__ offers multi-threading.
439 * Revision 1.37 2001/10/23 21:36:02 jongfoster
440 * Documenting sed()'s error behaviou (doc change only)
442 * Revision 1.36 2001/10/13 12:51:51 joergs
443 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
444 * force-load), instead crumble Host: and add it (again) in client_host_adder
445 * (in case we get a HTTP/1.0 request without Host: header and forward it to
446 * a HTTP/1.1 server/proxy).
448 * Revision 1.35 2001/10/09 22:39:21 jongfoster
449 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
452 * Revision 1.34 2001/10/07 18:50:55 oes
453 * Added server_content_encoding, renamed server_transfer_encoding
455 * Revision 1.33 2001/10/07 18:04:49 oes
456 * Changed server_http11 to server_http and its pattern to "HTTP".
457 * Additional functionality: it now saves the HTTP status into
458 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
460 * Revision 1.32 2001/10/07 15:43:28 oes
461 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
462 * client_te and client_accept_encoding_adder, triggered by the new
463 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
464 * changed to allow only identity and chunked, and the TE header is
465 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
467 * parse_http_request no longer does anything than parsing. The rewriting
468 * of http->cmd and version mangling are gone. It now also recognizes
469 * the put and delete methods and saves the url in http->url. Removed
472 * renamed content_type and content_length to have the server_ prefix
474 * server_content_type now only works if csp->content_type != CT_TABOO
476 * added server_transfer_encoding, which
477 * - Sets CT_TABOO to prohibit filtering if encoding compresses
478 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
479 * - Change from "chunked" to "identity" if body was chunked
480 * but has been de-chunked for filtering.
482 * added server_content_md5 which crunches any Content-MD5 headers
483 * if the body was modified.
485 * made server_http11 conditional on +downgrade action
487 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
489 * Revision 1.31 2001/10/05 14:25:02 oes
490 * Crumble Keep-Alive from Server
492 * Revision 1.30 2001/09/29 12:56:03 joergs
493 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
495 * Revision 1.29 2001/09/24 21:09:24 jongfoster
496 * Fixing 2 memory leaks that Guy spotted, where the paramater to
497 * enlist() was not being free()d.
499 * Revision 1.28 2001/09/22 16:32:28 jongfoster
500 * Removing unused #includes.
502 * Revision 1.27 2001/09/20 15:45:25 steudten
504 * add casting from size_t to int for printf()
505 * remove local variable shadow s2
507 * Revision 1.26 2001/09/16 17:05:14 jongfoster
508 * Removing unused #include showarg.h
510 * Revision 1.25 2001/09/16 13:21:27 jongfoster
511 * Changes to use new list functions.
513 * Revision 1.24 2001/09/13 23:05:50 jongfoster
514 * Changing the string paramater to the header parsers a "const".
516 * Revision 1.23 2001/09/12 18:08:19 steudten
518 * In parse_http_request() header rewriting miss the host value, so
519 * from http://www.mydomain.com the result was just " / " not
520 * http://www.mydomain.com/ in case we forward.
522 * Revision 1.22 2001/09/10 10:58:53 oes
523 * Silenced compiler warnings
525 * Revision 1.21 2001/07/31 14:46:00 oes
526 * - Persistant connections now suppressed
527 * - sed() no longer appends empty header to csp->headers
529 * Revision 1.20 2001/07/30 22:08:36 jongfoster
530 * Tidying up #defines:
531 * - All feature #defines are now of the form FEATURE_xxx
532 * - Permanently turned off WIN_GUI_EDIT
533 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
535 * Revision 1.19 2001/07/25 17:21:54 oes
536 * client_uagent now saves copy of User-Agent: header value
538 * Revision 1.18 2001/07/13 14:02:46 oes
539 * - Included fix to repair broken HTTP requests that
540 * don't contain a path, not even '/'.
541 * - Removed all #ifdef PCRS
542 * - content_type now always inspected and classified as
543 * text, gif or other.
544 * - formatting / comments
546 * Revision 1.17 2001/06/29 21:45:41 oes
547 * Indentation, CRLF->LF, Tab-> Space
549 * Revision 1.16 2001/06/29 13:32:42 oes
551 * - Adapted free_http_request
552 * - Removed logentry from cancelled commit
554 * Revision 1.15 2001/06/03 19:12:38 oes
555 * deleted const struct interceptors
557 * Revision 1.14 2001/06/01 18:49:17 jongfoster
558 * Replaced "list_share" with "list" - the tiny memory gain was not
559 * worth the extra complexity.
561 * Revision 1.13 2001/05/31 21:30:33 jongfoster
562 * Removed list code - it's now in list.[ch]
563 * Renamed "permission" to "action", and changed many features
564 * to use the actions file rather than the global config.
566 * Revision 1.12 2001/05/31 17:33:13 oes
570 * Revision 1.11 2001/05/29 20:11:19 joergs
571 * '/ * inside comment' warning removed.
573 * Revision 1.10 2001/05/29 09:50:24 jongfoster
574 * Unified blocklist/imagelist/permissionslist.
575 * File format is still under discussion, but the internal changes
578 * Also modified interceptor behaviour:
579 * - We now intercept all URLs beginning with one of the following
580 * prefixes (and *only* these prefixes):
582 * * http://ijbswa.sf.net/config/
583 * * http://ijbswa.sourceforge.net/config/
584 * - New interceptors "home page" - go to http://i.j.b/ to see it.
585 * - Internal changes so that intercepted and fast redirect pages
586 * are not replaced with an image.
587 * - Interceptors now have the option to send a binary page direct
588 * to the client. (i.e. ijb-send-banner uses this)
589 * - Implemented show-url-info interceptor. (Which is why I needed
590 * the above interceptors changes - a typical URL is
591 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
592 * The previous mechanism would not have intercepted that, and
593 * if it had been intercepted then it then it would have replaced
596 * Revision 1.9 2001/05/28 17:26:33 jongfoster
597 * Fixing segfault if last header was crunched.
598 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
599 * can use the cross-platform sprintf() instead.)
601 * Revision 1.8 2001/05/27 22:17:04 oes
603 * - re_process_buffer no longer writes the modified buffer
604 * to the client, which was very ugly. It now returns the
605 * buffer, which it is then written by chat.
607 * - content_length now adjusts the Content-Length: header
608 * for modified documents rather than crunch()ing it.
609 * (Length info in csp->content_length, which is 0 for
610 * unmodified documents)
612 * - For this to work, sed() is called twice when filtering.
614 * Revision 1.7 2001/05/27 13:19:06 oes
615 * Patched Joergs solution for the content-length in.
617 * Revision 1.6 2001/05/26 13:39:32 jongfoster
618 * Only crunches Content-Length header if applying RE filtering.
619 * Without this fix, Microsoft Windows Update wouldn't work.
621 * Revision 1.5 2001/05/26 00:28:36 jongfoster
622 * Automatic reloading of config file.
623 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
624 * Most of the global variables have been moved to a new
625 * struct configuration_spec, accessed through csp->config->globalname
626 * Most of the globals remaining are used by the Win32 GUI.
628 * Revision 1.4 2001/05/22 18:46:04 oes
630 * - Enabled filtering banners by size rather than URL
631 * by adding patterns that replace all standard banner
632 * sizes with the "Junkbuster" gif to the re_filterfile
634 * - Enabled filtering WebBugs by providing a pattern
635 * which kills all 1x1 images
637 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
638 * which is selected by the (nonstandard and therefore
639 * capital) letter 'U' in the option string.
640 * It causes the quantifiers to be ungreedy by default.
641 * Appending a ? turns back to greedy (!).
643 * - Added a new interceptor ijb-send-banner, which
644 * sends back the "Junkbuster" gif. Without imagelist or
645 * MSIE detection support, or if tinygif = 1, or the
646 * URL isn't recognized as an imageurl, a lame HTML
647 * explanation is sent instead.
649 * - Added new feature, which permits blocking remote
650 * script redirects and firing back a local redirect
652 * The feature is conditionally compiled, i.e. it
653 * can be disabled with --disable-fast-redirects,
654 * plus it must be activated by a "fast-redirects"
655 * line in the config file, has its own log level
656 * and of course wants to be displayed by show-proxy-args
657 * Note: Boy, all the #ifdefs in 1001 locations and
658 * all the fumbling with configure.in and acconfig.h
659 * were *way* more work than the feature itself :-(
661 * - Because a generic redirect template was needed for
662 * this, tinygif = 3 now uses the same.
664 * - Moved GIFs, and other static HTTP response templates
669 * - Removed some >400 CRs again (Jon, you really worked
672 * Revision 1.3 2001/05/20 01:21:20 jongfoster
673 * Version 2.9.4 checkin.
674 * - Merged popupfile and cookiefile, and added control over PCRS
675 * filtering, in new "permissionsfile".
676 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
677 * file error you now get a message box (in the Win32 GUI) rather
678 * than the program exiting with no explanation.
679 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
681 * - Removed tabs from "config"
682 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
683 * - Bumped up version number.
685 * Revision 1.2 2001/05/17 23:02:36 oes
686 * - Made referrer option accept 'L' as a substitute for '§'
688 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
689 * Initial import of version 2.9.3 source tree
692 *********************************************************************/
699 #include <sys/types.h>
709 * Convince GNU's libc to provide a strptime prototype.
712 #endif /*__GLIBC__ */
719 #if !defined(_WIN32) && !defined(__OS2__)
725 #ifdef FEATURE_PTHREAD
727 /* jcc.h is for mutex semapores only */
728 #endif /* def FEATURE_PTHREAD */
734 #include "jbsockets.h"
735 #include "miscutil.h"
740 #ifndef HAVE_STRPTIME
741 #include "strptime.h"
744 const char parsers_h_rcs[] = PARSERS_H_VERSION;
746 /* Fix a problem with Solaris. There should be no effect on other
748 * Solaris's isspace() is a macro which uses its argument directly
749 * as an array index. Therefore we need to make sure that high-bit
750 * characters generate +ve values, and ideally we also want to make
751 * the argument match the declared parameter type of "int".
753 * Why did they write a character function that can't take a simple
754 * "char" argument? Doh!
756 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
757 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
759 static jb_err scan_headers(struct client_state *csp);
760 static jb_err header_tagger(struct client_state *csp, char *header);
761 static jb_err parse_header_time(const char *header_time, time_t *result);
763 static jb_err crumble (struct client_state *csp, char **header);
764 static jb_err connection (struct client_state *csp, char **header);
765 static jb_err filter_header (struct client_state *csp, char **header);
766 static jb_err client_referrer (struct client_state *csp, char **header);
767 static jb_err client_uagent (struct client_state *csp, char **header);
768 static jb_err client_ua (struct client_state *csp, char **header);
769 static jb_err client_from (struct client_state *csp, char **header);
770 static jb_err client_send_cookie (struct client_state *csp, char **header);
771 static jb_err client_x_forwarded (struct client_state *csp, char **header);
772 static jb_err client_accept_encoding (struct client_state *csp, char **header);
773 static jb_err client_te (struct client_state *csp, char **header);
774 static jb_err client_max_forwards (struct client_state *csp, char **header);
775 static jb_err client_host (struct client_state *csp, char **header);
776 static jb_err client_if_modified_since (struct client_state *csp, char **header);
777 static jb_err client_accept_language (struct client_state *csp, char **header);
778 static jb_err client_if_none_match (struct client_state *csp, char **header);
779 static jb_err crunch_client_header (struct client_state *csp, char **header);
780 static jb_err client_x_filter (struct client_state *csp, char **header);
781 static jb_err server_set_cookie (struct client_state *csp, char **header);
782 static jb_err server_content_type (struct client_state *csp, char **header);
783 static jb_err server_content_length (struct client_state *csp, char **header);
784 static jb_err server_content_md5 (struct client_state *csp, char **header);
785 static jb_err server_content_encoding (struct client_state *csp, char **header);
786 static jb_err server_transfer_coding (struct client_state *csp, char **header);
787 static jb_err server_http (struct client_state *csp, char **header);
788 static jb_err crunch_server_header (struct client_state *csp, char **header);
789 static jb_err server_last_modified (struct client_state *csp, char **header);
790 static jb_err server_content_disposition(struct client_state *csp, char **header);
792 static jb_err client_host_adder (struct client_state *csp);
793 static jb_err client_cookie_adder (struct client_state *csp);
794 static jb_err client_xtra_adder (struct client_state *csp);
795 static jb_err client_x_forwarded_adder(struct client_state *csp);
796 static jb_err connection_close_adder (struct client_state *csp);
798 const struct parsers client_patterns[] = {
799 { "referer:", 8, client_referrer },
800 { "user-agent:", 11, client_uagent },
801 { "ua-", 3, client_ua },
802 { "from:", 5, client_from },
803 { "cookie:", 7, client_send_cookie },
804 { "x-forwarded-for:", 16, client_x_forwarded },
805 { "Accept-Encoding:", 16, client_accept_encoding },
806 { "TE:", 3, client_te },
807 { "Host:", 5, client_host },
808 { "if-modified-since:", 18, client_if_modified_since },
809 { "Keep-Alive:", 11, crumble },
810 { "connection:", 11, connection },
811 { "proxy-connection:", 17, crumble },
812 { "max-forwards:", 13, client_max_forwards },
813 { "Accept-Language:", 16, client_accept_language },
814 { "if-none-match:", 14, client_if_none_match },
815 { "X-Filter:", 9, client_x_filter },
816 { "*", 0, crunch_client_header },
817 { "*", 0, filter_header },
821 const struct parsers server_patterns[] = {
822 { "HTTP/", 5, server_http },
823 { "set-cookie:", 11, server_set_cookie },
824 { "connection:", 11, connection },
825 { "Content-Type:", 13, server_content_type },
826 { "Content-MD5:", 12, server_content_md5 },
827 { "Content-Encoding:", 17, server_content_encoding },
828 { "Transfer-Encoding:", 18, server_transfer_coding },
829 { "Keep-Alive:", 11, crumble },
830 { "content-disposition:", 20, server_content_disposition },
831 { "Last-Modified:", 14, server_last_modified },
832 { "*", 0, crunch_server_header },
833 { "*", 0, filter_header },
837 const struct parsers server_patterns_light[] = {
838 { "Content-Length:", 15, server_content_length },
839 { "Transfer-Encoding:", 18, server_transfer_coding },
841 { "Content-Encoding:", 17, server_content_encoding },
842 #endif /* def FEATURE_ZLIB */
846 const add_header_func_ptr add_client_headers[] = {
849 client_x_forwarded_adder,
851 /* Temporarily disabled: client_accept_encoding_adder, */
852 connection_close_adder,
857 const add_header_func_ptr add_server_headers[] = {
858 connection_close_adder,
862 /*********************************************************************
864 * Function : flush_socket
866 * Description : Write any pending "buffered" content.
869 * 1 : fd = file descriptor of the socket to read
870 * 2 : csp = Current client state (buffers, headers, etc...)
872 * Returns : On success, the number of bytes written are returned (zero
873 * indicates nothing was written). On error, -1 is returned,
874 * and errno is set appropriately. If count is zero and the
875 * file descriptor refers to a regular file, 0 will be
876 * returned without causing any other effect. For a special
877 * file, the results are not portable.
879 *********************************************************************/
880 int flush_socket(jb_socket fd, struct client_state *csp)
882 struct iob *iob = csp->iob;
883 int len = iob->eod - iob->cur;
890 if (write_socket(fd, iob->cur, (size_t)len))
894 iob->eod = iob->cur = iob->buf;
900 /*********************************************************************
902 * Function : add_to_iob
904 * Description : Add content to the buffered page, expanding the
905 * buffer if necessary.
908 * 1 : csp = Current client state (buffers, headers, etc...)
909 * 2 : buf = holds the content to be added to the page
910 * 3 : n = number of bytes to be added
912 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
913 * or buffer limit reached.
915 *********************************************************************/
916 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
918 struct iob *iob = csp->iob;
919 size_t used, offset, need, want;
922 if (n <= 0) return JB_ERR_OK;
924 used = (size_t)(iob->eod - iob->buf);
925 offset = (size_t)(iob->cur - iob->buf);
926 need = used + (size_t)n + 1;
929 * If the buffer can't hold the new data, extend it first.
930 * Use the next power of two if possible, else use the actual need.
932 if (need > csp->config->buffer_limit)
934 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
935 return JB_ERR_MEMORY;
938 if (need > iob->size)
940 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
942 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
946 else if (NULL != (p = (char *)realloc(iob->buf, need)))
952 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
953 return JB_ERR_MEMORY;
956 /* Update the iob pointers */
957 iob->cur = p + offset;
962 /* copy the new data into the iob buffer */
963 memcpy(iob->eod, buf, (size_t)n);
965 /* point to the end of the data */
968 /* null terminate == cheap insurance */
977 /*********************************************************************
979 * Function : decompress_iob
981 * Description : Decompress buffered page, expanding the
982 * buffer as necessary. csp->iob->cur
983 * should point to the the beginning of the
984 * compressed data block.
987 * 1 : csp = Current client state (buffers, headers, etc...)
989 * Returns : JB_ERR_OK on success,
990 * JB_ERR_MEMORY if out-of-memory limit reached, and
991 * JB_ERR_COMPRESS if error decompressing buffer.
993 *********************************************************************/
994 jb_err decompress_iob(struct client_state *csp)
996 char *buf; /* new, uncompressed buffer */
997 char *cur; /* Current iob position (to keep the original
998 * iob->cur unmodified if we return early) */
999 size_t bufsize; /* allocated size of the new buffer */
1000 size_t old_size; /* Content size before decompression */
1001 size_t skip_size; /* Number of bytes at the beginning of the iob
1002 that we should NOT decompress. */
1003 int status; /* return status of the inflate() call */
1004 z_stream zstr; /* used by calls to zlib */
1006 assert(csp->iob->cur - csp->iob->buf > 0);
1007 assert(csp->iob->eod - csp->iob->cur > 0);
1009 bufsize = csp->iob->size;
1010 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1011 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1013 cur = csp->iob->cur;
1018 * This is to protect the parsing of gzipped data,
1019 * but it should(?) be valid for deflated data also.
1021 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1022 return JB_ERR_COMPRESS;
1025 if (csp->content_type & CT_GZIP)
1028 * Our task is slightly complicated by the facts that data
1029 * compressed by gzip does not include a zlib header, and
1030 * that there is no easily accessible interface in zlib to
1031 * handle a gzip header. We strip off the gzip header by
1032 * hand, and later inform zlib not to expect a header.
1036 * Strip off the gzip header. Please see RFC 1952 for more
1037 * explanation of the appropriate fields.
1039 if ((*cur++ != (char)0x1f)
1040 || (*cur++ != (char)0x8b)
1041 || (*cur++ != Z_DEFLATED))
1043 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1044 return JB_ERR_COMPRESS;
1050 * XXX: These magic numbers should be replaced
1051 * with macros to give a better idea what they do.
1055 /* The gzip header has reserved bits set; bail out. */
1056 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1057 return JB_ERR_COMPRESS;
1061 /* Skip extra fields if necessary. */
1065 * Skip a given number of bytes, specified
1066 * as a 16-bit little-endian value.
1069 * XXX: This code used to be:
1071 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1073 * which I had to change into:
1075 * cur += *cur++ + (*cur++ << 8);
1077 * at which point gcc43 finally noticed that the value
1078 * of cur is undefined (it depends on which of the
1079 * summands is evaluated first).
1081 * I haven't come across a site where this
1082 * code is actually executed yet, but I hope
1086 skip_bytes = *cur++;
1087 skip_bytes = *cur++ << 8;
1089 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1092 * The number of bytes to skip should be positive
1093 * and we'd like to stay in the buffer.
1095 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1097 log_error (LOG_LEVEL_ERROR,
1098 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1100 return JB_ERR_COMPRESS;
1102 log_error (LOG_LEVEL_INFO,
1103 "Skipping %d bytes for gzip compression. Does this sound right?",
1108 /* Skip the filename if necessary. */
1111 /* A null-terminated string is supposed to follow. */
1112 while (*cur++ && (cur < csp->iob->eod));
1116 /* Skip the comment if necessary. */
1119 /* A null-terminated string is supposed to follow. */
1120 while (*cur++ && (cur < csp->iob->eod));
1123 /* Skip the CRC if necessary. */
1129 if (cur >= csp->iob->eod)
1132 * If the current position pointer reached or passed
1133 * the buffer end, we were obviously tricked to skip
1136 log_error (LOG_LEVEL_ERROR,
1137 "Malformed gzip header detected. Aborting decompression.");
1138 return JB_ERR_COMPRESS;
1142 else if (csp->content_type & CT_DEFLATE)
1145 * XXX: The debug level should be lowered
1146 * before the next stable release.
1148 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1150 * In theory (that is, according to RFC 1950), deflate-compressed
1151 * data should begin with a two-byte zlib header and have an
1152 * adler32 checksum at the end. It seems that in practice only
1153 * the raw compressed data is sent. Note that this means that
1154 * we are not RFC 1950-compliant here, but the advantage is that
1155 * this actually works. :)
1157 * We add a dummy null byte to tell zlib where the data ends,
1158 * and later inform it not to expect a header.
1160 * Fortunately, add_to_iob() has thoughtfully null-terminated
1161 * the buffer; we can just increment the end pointer to include
1168 log_error (LOG_LEVEL_ERROR,
1169 "Unable to determine compression format for decompression");
1170 return JB_ERR_COMPRESS;
1173 /* Set up the fields required by zlib. */
1174 zstr.next_in = (Bytef *)cur;
1175 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1176 zstr.zalloc = Z_NULL;
1177 zstr.zfree = Z_NULL;
1178 zstr.opaque = Z_NULL;
1181 * Passing -MAX_WBITS to inflateInit2 tells the library
1182 * that there is no zlib header.
1184 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1186 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1187 return JB_ERR_COMPRESS;
1191 * Next, we allocate new storage for the inflated data.
1192 * We don't modify the existing iob yet, so in case there
1193 * is error in decompression we can recover gracefully.
1195 buf = zalloc (bufsize);
1198 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1199 return JB_ERR_MEMORY;
1202 assert(bufsize >= skip_size);
1203 memcpy(buf, csp->iob->buf, skip_size);
1204 zstr.avail_out = bufsize - skip_size;
1205 zstr.next_out = (Bytef *)buf + skip_size;
1207 /* Try to decompress the whole stream in one shot. */
1208 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1210 /* We need to allocate more memory for the output buffer. */
1212 char *tmpbuf; /* used for realloc'ing the buffer */
1213 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1216 * If zlib wants more data then there's a problem, because
1217 * the complete compressed file should have been buffered.
1219 if (0 == zstr.avail_in)
1221 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1222 return JB_ERR_COMPRESS;
1226 * If we tried the limit and still didn't have enough
1227 * memory, just give up.
1229 if (bufsize == csp->config->buffer_limit)
1231 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1232 return JB_ERR_MEMORY;
1235 /* Try doubling the buffer size each time. */
1238 /* Don't exceed the buffer limit. */
1239 if (bufsize > csp->config->buffer_limit)
1241 bufsize = csp->config->buffer_limit;
1244 /* Try to allocate the new buffer. */
1245 tmpbuf = realloc(buf, bufsize);
1248 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1250 return JB_ERR_MEMORY;
1254 char *oldnext_out = (char *)zstr.next_out;
1257 * Update the fields for inflate() to use the new
1258 * buffer, which may be in a location different from
1261 zstr.avail_out += bufsize - oldbufsize;
1262 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1265 * Compare with an uglier method of calculating these values
1266 * that doesn't require the extra oldbufsize variable.
1268 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1269 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1270 assert(zstr.avail_out > 0);
1276 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1278 log_error(LOG_LEVEL_ERROR,
1279 "Inconsistent stream state after decompression: %s", zstr.msg);
1281 * XXX: Intentionally no return.
1283 * According to zlib.h, Z_STREAM_ERROR is returned
1284 * "if the stream state was inconsistent".
1286 * I assume in this case inflate()'s status
1287 * would also be something different than Z_STREAM_END
1288 * so this check should be redundant, but lets see.
1292 if (status != Z_STREAM_END)
1294 /* We failed to decompress the stream. */
1295 log_error(LOG_LEVEL_ERROR,
1296 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1297 return JB_ERR_COMPRESS;
1301 * Finally, we can actually update the iob, since the
1302 * decompression was successful. First, free the old
1305 freez(csp->iob->buf);
1307 /* Now, update the iob to use the new buffer. */
1308 csp->iob->buf = buf;
1309 csp->iob->cur = csp->iob->buf + skip_size;
1310 csp->iob->eod = (char *)zstr.next_out;
1311 csp->iob->size = bufsize;
1314 * Make sure the new uncompressed iob obeys some minimal
1315 * consistency conditions.
1317 if ((csp->iob->buf < csp->iob->cur)
1318 && (csp->iob->cur <= csp->iob->eod)
1319 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1321 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1324 log_error(LOG_LEVEL_RE_FILTER,
1325 "Decompression successful. Old size: %d, new size: %d.",
1326 old_size, new_size);
1330 /* zlib thinks this is OK, so lets do the same. */
1331 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1336 /* It seems that zlib did something weird. */
1337 log_error(LOG_LEVEL_ERROR,
1338 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1339 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1340 csp->iob->eod, csp->iob->buf + csp->iob->size);
1341 return JB_ERR_COMPRESS;
1347 #endif /* defined(FEATURE_ZLIB) */
1350 /*********************************************************************
1352 * Function : get_header
1354 * Description : This (odd) routine will parse the csp->iob
1357 * 1 : csp = Current client state (buffers, headers, etc...)
1359 * Returns : Any one of the following:
1361 * 1) a pointer to a dynamically allocated string that contains a header line
1362 * 2) NULL indicating that the end of the header was reached
1363 * 3) "" indicating that the end of the iob was reached before finding
1364 * a complete header line.
1366 *********************************************************************/
1367 char *get_header(struct client_state *csp)
1373 if ((iob->cur == NULL)
1374 || ((p = strchr(iob->cur, '\n')) == NULL))
1376 return(""); /* couldn't find a complete header */
1381 ret = strdup(iob->cur);
1384 /* FIXME No way to handle error properly */
1385 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1390 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1392 /* is this a blank line (i.e. the end of the header) ? */
1404 /*********************************************************************
1406 * Function : get_header_value
1408 * Description : Get the value of a given header from a chained list
1409 * of header lines or return NULL if no such header is
1410 * present in the list.
1413 * 1 : header_list = pointer to list
1414 * 2 : header_name = string with name of header to look for.
1415 * Trailing colon required, capitalization
1418 * Returns : NULL if not found, else value of header
1420 *********************************************************************/
1421 char *get_header_value(const struct list *header_list, const char *header_name)
1423 struct list_entry *cur_entry;
1427 assert(header_list);
1428 assert(header_name);
1429 length = strlen(header_name);
1431 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1435 if (!strncmpic(cur_entry->str, header_name, length))
1438 * Found: return pointer to start of value
1440 ret = (char *) (cur_entry->str + length);
1441 while (*ret && ijb_isspace(*ret)) ret++;
1455 /*********************************************************************
1457 * Function : scan_headers
1459 * Description : Scans headers, applies tags and updates action bits.
1462 * 1 : csp = Current client state (buffers, headers, etc...)
1464 * Returns : JB_ERR_OK
1466 *********************************************************************/
1467 static jb_err scan_headers(struct client_state *csp)
1469 struct list_entry *h; /* Header */
1470 jb_err err = JB_ERR_OK;
1472 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1474 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1476 /* Header crunch()ed in previous run? -> ignore */
1477 if (h->str == NULL) continue;
1478 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1479 err = header_tagger(csp, h->str);
1486 /*********************************************************************
1490 * Description : add, delete or modify lines in the HTTP header streams.
1491 * On entry, it receives a linked list of headers space
1492 * that was allocated dynamically (both the list nodes
1493 * and the header contents).
1495 * As a side effect it frees the space used by the original
1499 * 1 : pats = list of patterns to match against headers
1500 * 2 : more_headers = list of functions to add more
1501 * headers (client or server)
1502 * 3 : csp = Current client state (buffers, headers, etc...)
1504 * Returns : JB_ERR_OK in case off success, or
1505 * JB_ERR_MEMORY on out-of-memory error.
1507 *********************************************************************/
1508 jb_err sed(const struct parsers pats[],
1509 const add_header_func_ptr more_headers[],
1510 struct client_state *csp)
1512 struct list_entry *p;
1513 const struct parsers *v;
1514 const add_header_func_ptr *f;
1515 jb_err err = JB_ERR_OK;
1519 * If filtering is enabled, sed is run twice,
1520 * but most of the work needs to be done only once.
1522 first_run = (more_headers != NULL ) ? 1 : 0;
1524 if (first_run) /* Parse and print */
1528 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1530 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1532 /* Header crunch()ed in previous run? -> ignore */
1533 if (p->str == NULL) continue;
1535 /* Does the current parser handle this header? */
1536 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1538 err = v->parser(csp, (char **)&(p->str));
1542 /* place any additional headers on the csp->headers list */
1543 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1548 else /* Parse only */
1551 * The second run is only needed if the body was modified
1552 * and the content-lenght has changed.
1554 if (strncmpic(csp->http->cmd, "HEAD", 4))
1556 /*XXX: Code duplication */
1557 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1559 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1561 /* Header crunch()ed in previous run? -> ignore */
1562 if (p->str == NULL) continue;
1564 /* Does the current parser handle this header? */
1565 if (strncmpic(p->str, v->str, v->len) == 0)
1567 err = v->parser(csp, (char **)&(p->str));
1579 /*********************************************************************
1581 * Function : header_tagger
1583 * Description : Executes all text substitutions from applying
1584 * tag actions and saves the result as tag.
1586 * XXX: Shares enough code with filter_header() and
1587 * pcrs_filter_response() to warrant some helper functions.
1590 * 1 : csp = Current client state (buffers, headers, etc...)
1591 * 2 : header = Header that is used as tagger input
1593 * Returns : JB_ERR_OK on success and always succeeds
1595 *********************************************************************/
1596 static jb_err header_tagger(struct client_state *csp, char *header)
1598 int wanted_filter_type;
1599 int multi_action_index;
1603 struct file_list *fl;
1604 struct re_filterfile_spec *b;
1605 struct list_entry *tag_name;
1607 int found_filters = 0;
1608 const size_t header_length = strlen(header);
1610 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1612 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1613 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1617 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1618 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1621 /* Check if there are any filters */
1622 for (i = 0; i < MAX_AF_FILES; i++)
1635 if (0 == found_filters)
1637 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1641 for (i = 0; i < MAX_AF_FILES; i++)
1644 if ((NULL == fl) || (NULL == fl->f))
1647 * Either there are no filter files
1648 * left, or this filter file just
1649 * contains no valid filters.
1651 * Continue to be sure we don't miss
1652 * valid filter files that are chained
1653 * after empty or invalid ones.
1658 /* For all filters, */
1659 for (b = fl->f; b; b = b->next)
1661 if (b->type != wanted_filter_type)
1663 /* skip the ones we don't care about, */
1666 /* leaving only taggers that could apply, of which we use the ones, */
1667 for (tag_name = csp->action->multi[multi_action_index]->first;
1668 NULL != tag_name; tag_name = tag_name->next)
1670 /* that do apply, and */
1671 if (strcmp(b->name, tag_name->str) == 0)
1673 char *modified_tag = NULL;
1675 size_t size = header_length;
1676 pcrs_job *joblist = b->joblist;
1678 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1680 if (NULL == joblist)
1682 log_error(LOG_LEVEL_RE_FILTER,
1683 "Tagger %s has empty joblist. Nothing to do.", b->name);
1687 /* execute their pcrs_joblist on the header. */
1688 for (job = joblist; NULL != job; job = job->next)
1690 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1694 /* Success, continue with the modified version. */
1703 /* Tagger doesn't match */
1706 /* Regex failure, log it but continue anyway. */
1707 log_error(LOG_LEVEL_ERROR,
1708 "Problems with tagger \'%s\' and header \'%s\': %s",
1709 b->name, *header, pcrs_strerror(hits));
1711 freez(modified_tag);
1715 if (b->dynamic) pcrs_free_joblist(joblist);
1717 /* If this tagger matched */
1723 * There is to technical limitation which makes
1724 * it impossible to use empty tags, but I assume
1725 * no one would do it intentionally.
1728 log_error(LOG_LEVEL_INFO,
1729 "Tagger \'%s\' created an empty tag. Ignored.",
1734 if (!list_contains_item(csp->tags, tag))
1736 if (JB_ERR_OK != enlist(csp->tags, tag))
1738 log_error(LOG_LEVEL_ERROR,
1739 "Insufficient memory to add tag \'%s\', "
1740 "based on tagger \'%s\' and header \'%s\'",
1741 tag, b->name, *header);
1745 char *action_message;
1747 * update the action bits right away, to make
1748 * tagging based on tags set by earlier taggers
1749 * of the same kind possible.
1751 if (update_action_bits_for_tag(csp, tag))
1753 action_message = "Action bits updated accordingly.";
1757 action_message = "No action bits update necessary.";
1760 log_error(LOG_LEVEL_HEADER,
1761 "Tagger \'%s\' added tag \'%s\'. %s",
1762 b->name, tag, action_message);
1767 /* XXX: Is this log-worthy? */
1768 log_error(LOG_LEVEL_HEADER,
1769 "Tagger \'%s\' didn't add tag \'%s\'. "
1770 "Tag already present", b->name, tag);
1773 } /* if the tagger matched */
1774 } /* if the tagger applies */
1775 } /* for every tagger that could apply */
1776 } /* for all filters */
1777 } /* for all filter files */
1782 /* here begins the family of parser functions that reformat header lines */
1784 /*********************************************************************
1786 * Function : filter_header
1788 * Description : Executes all text substitutions from all applying
1789 * +(server|client)-header-filter actions on the header.
1790 * Most of the code was copied from pcrs_filter_response,
1791 * including the rather short variable names
1794 * 1 : csp = Current client state (buffers, headers, etc...)
1795 * 2 : header = On input, pointer to header to modify.
1796 * On output, pointer to the modified header, or NULL
1797 * to remove the header. This function frees the
1798 * original string if necessary.
1800 * Returns : JB_ERR_OK on success and always succeeds
1802 *********************************************************************/
1803 static jb_err filter_header(struct client_state *csp, char **header)
1807 size_t size = strlen(*header);
1809 char *newheader = NULL;
1812 struct file_list *fl;
1813 struct re_filterfile_spec *b;
1814 struct list_entry *filtername;
1816 int i, found_filters = 0;
1817 int wanted_filter_type;
1818 int multi_action_index;
1820 if (csp->flags & CSP_FLAG_NO_FILTERING)
1825 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1827 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1828 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1832 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1833 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1837 * Need to check the set of re_filterfiles...
1839 for (i = 0; i < MAX_AF_FILES; i++)
1852 if (0 == found_filters)
1854 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1858 for (i = 0; i < MAX_AF_FILES; i++)
1861 if ((NULL == fl) || (NULL == fl->f))
1864 * Either there are no filter files
1865 * left, or this filter file just
1866 * contains no valid filters.
1868 * Continue to be sure we don't miss
1869 * valid filter files that are chained
1870 * after empty or invalid ones.
1875 * For all applying +filter actions, look if a filter by that
1876 * name exists and if yes, execute its pcrs_joblist on the
1879 for (b = fl->f; b; b = b->next)
1881 if (b->type != wanted_filter_type)
1883 /* Skip other filter types */
1887 for (filtername = csp->action->multi[multi_action_index]->first;
1888 filtername ; filtername = filtername->next)
1890 if (strcmp(b->name, filtername->str) == 0)
1892 int current_hits = 0;
1893 pcrs_job *joblist = b->joblist;
1895 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1897 if (NULL == joblist)
1899 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1903 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1904 *header, size, b->name);
1906 /* Apply all jobs from the joblist */
1907 for (job = joblist; NULL != job; job = job->next)
1909 matches = pcrs_execute(job, *header, size, &newheader, &size);
1912 current_hits += matches;
1913 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1915 *header = newheader;
1917 else if ( 0 == matches )
1919 /* Filter doesn't change header */
1925 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1926 *header, b->name, pcrs_strerror(matches));
1927 if( newheader != NULL)
1929 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1935 if (b->dynamic) pcrs_free_joblist(joblist);
1937 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1938 hits += current_hits;
1945 * Additionally checking for hits is important because if
1946 * the continue hack is triggered, server headers can
1947 * arrive empty to separate multiple heads from each other.
1949 if ((0 == size) && hits)
1951 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1959 /*********************************************************************
1961 * Function : connection
1963 * Description : Makes sure that the value of the Connection: header
1964 * is "close" and signals connection_close_adder
1968 * 1 : csp = Current client state (buffers, headers, etc...)
1969 * 2 : header = On input, pointer to header to modify.
1970 * On output, pointer to the modified header, or NULL
1971 * to remove the header. This function frees the
1972 * original string if necessary.
1974 * Returns : JB_ERR_OK on success, or
1975 * JB_ERR_MEMORY on out-of-memory error.
1977 *********************************************************************/
1978 static jb_err connection(struct client_state *csp, char **header)
1980 char *old_header = *header;
1982 /* Do we have a 'Connection: close' header? */
1983 if (strcmpic(*header, "Connection: close"))
1985 /* No, create one */
1986 *header = strdup("Connection: close");
1989 return JB_ERR_MEMORY;
1991 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1995 /* Signal connection_close_adder() to return early. */
1996 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1998 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2002 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2009 /*********************************************************************
2011 * Function : crumble
2013 * Description : This is called if a header matches a pattern to "crunch"
2016 * 1 : csp = Current client state (buffers, headers, etc...)
2017 * 2 : header = On input, pointer to header to modify.
2018 * On output, pointer to the modified header, or NULL
2019 * to remove the header. This function frees the
2020 * original string if necessary.
2022 * Returns : JB_ERR_OK on success, or
2023 * JB_ERR_MEMORY on out-of-memory error.
2025 *********************************************************************/
2026 static jb_err crumble(struct client_state *csp, char **header)
2028 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2033 /*********************************************************************
2035 * Function : crunch_server_header
2037 * Description : Crunch server header if it matches a string supplied by the
2038 * user. Called from `sed'.
2041 * 1 : csp = Current client state (buffers, headers, etc...)
2042 * 2 : header = On input, pointer to header to modify.
2043 * On output, pointer to the modified header, or NULL
2044 * to remove the header. This function frees the
2045 * original string if necessary.
2047 * Returns : JB_ERR_OK on success and always succeeds
2049 *********************************************************************/
2050 static jb_err crunch_server_header(struct client_state *csp, char **header)
2052 const char *crunch_pattern;
2054 /* Do we feel like crunching? */
2055 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2057 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2059 /* Is the current header the lucky one? */
2060 if (strstr(*header, crunch_pattern))
2062 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2071 /*********************************************************************
2073 * Function : server_content_type
2075 * Description : Set the content-type for filterable types (text/.*,
2076 * .*xml.*, javascript and image/gif) unless filtering has been
2077 * forbidden (CT_TABOO) while parsing earlier headers.
2078 * NOTE: Since text/plain is commonly used by web servers
2079 * for files whose correct type is unknown, we don't
2080 * set CT_TEXT for it.
2083 * 1 : csp = Current client state (buffers, headers, etc...)
2084 * 2 : header = On input, pointer to header to modify.
2085 * On output, pointer to the modified header, or NULL
2086 * to remove the header. This function frees the
2087 * original string if necessary.
2089 * Returns : JB_ERR_OK on success, or
2090 * JB_ERR_MEMORY on out-of-memory error.
2092 *********************************************************************/
2093 static jb_err server_content_type(struct client_state *csp, char **header)
2095 /* Remove header if it isn't the first Content-Type header */
2096 if ((csp->content_type & CT_DECLARED))
2099 * Another, slightly slower, way to see if
2100 * we already parsed another Content-Type header.
2102 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2104 log_error(LOG_LEVEL_ERROR,
2105 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2113 * Signal that the Content-Type has been set.
2115 csp->content_type |= CT_DECLARED;
2117 if (!(csp->content_type & CT_TABOO))
2119 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2120 || strstr(*header, "xml")
2121 || strstr(*header, "application/x-javascript"))
2123 csp->content_type |= CT_TEXT;
2125 else if (strstr(*header, " image/gif"))
2127 csp->content_type |= CT_GIF;
2129 else if (strstr(*header, " image/jpeg"))
2131 csp->content_type |= CT_JPEG;
2136 * Are we messing with the content type?
2138 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2141 * Make sure the user doesn't accidently
2142 * change the content type of binary documents.
2144 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2147 *header = strdup("Content-Type: ");
2148 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2152 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2153 return JB_ERR_MEMORY;
2155 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2159 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2160 "Enable force-text-mode if you know what you're doing.", *header);
2168 /*********************************************************************
2170 * Function : server_transfer_coding
2172 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2173 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2174 * - Remove header if body was chunked but has been
2175 * de-chunked for filtering.
2178 * 1 : csp = Current client state (buffers, headers, etc...)
2179 * 2 : header = On input, pointer to header to modify.
2180 * On output, pointer to the modified header, or NULL
2181 * to remove the header. This function frees the
2182 * original string if necessary.
2184 * Returns : JB_ERR_OK on success, or
2185 * JB_ERR_MEMORY on out-of-memory error.
2187 *********************************************************************/
2188 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2191 * Turn off pcrs and gif filtering if body compressed
2193 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2197 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2199 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2200 csp->http->cmd, *header);
2201 #endif /* def FEATURE_ZLIB */
2202 csp->content_type = CT_TABOO;
2206 * Raise flag if body chunked
2208 if (strstr(*header, "chunked"))
2210 csp->flags |= CSP_FLAG_CHUNKED;
2213 * If the body was modified, it has been de-chunked first
2214 * and the header must be removed.
2216 * FIXME: If there is more than one transfer encoding,
2217 * only the "chunked" part should be removed here.
2219 if (csp->flags & CSP_FLAG_MODIFIED)
2221 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2230 /*********************************************************************
2232 * Function : server_content_encoding
2234 * Description : This function is run twice for each request,
2235 * unless FEATURE_ZLIB and filtering are disabled.
2237 * The first run is used to check if the content
2238 * is compressed, if FEATURE_ZLIB is disabled
2239 * filtering is then disabled as well, if FEATURE_ZLIB
2240 * is enabled the content is marked for decompression.
2242 * The second run is used to remove the Content-Encoding
2243 * header if the decompression was successful.
2246 * 1 : csp = Current client state (buffers, headers, etc...)
2247 * 2 : header = On input, pointer to header to modify.
2248 * On output, pointer to the modified header, or NULL
2249 * to remove the header. This function frees the
2250 * original string if necessary.
2252 * Returns : JB_ERR_OK on success, or
2253 * JB_ERR_MEMORY on out-of-memory error.
2255 *********************************************************************/
2256 static jb_err server_content_encoding(struct client_state *csp, char **header)
2259 if ((csp->flags & CSP_FLAG_MODIFIED)
2260 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2263 * We successfully decompressed the content,
2264 * and have to clean the header now, so the
2265 * client no longer expects compressed data..
2267 * XXX: There is a difference between cleaning
2268 * and removing it completely.
2270 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2273 else if (strstr(*header, "gzip"))
2275 /* Mark for gzip decompression */
2276 csp->content_type |= CT_GZIP;
2278 else if (strstr(*header, "deflate"))
2280 /* Mark for zlib decompression */
2281 csp->content_type |= CT_DEFLATE;
2283 else if (strstr(*header, "compress"))
2286 * We can't decompress this; therefore we can't filter
2289 csp->content_type |= CT_TABOO;
2291 #else /* !defined(FEATURE_ZLIB) */
2292 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2295 * Body is compressed, turn off pcrs and gif filtering.
2297 csp->content_type |= CT_TABOO;
2300 * Log a warning if the user expects the content to be filtered.
2302 if ((csp->rlist != NULL) &&
2303 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2305 log_error(LOG_LEVEL_INFO,
2306 "Compressed content detected, content filtering disabled. "
2307 "Consider recompiling Privoxy with zlib support or "
2308 "enable the prevent-compression action.");
2311 #endif /* defined(FEATURE_ZLIB) */
2318 /*********************************************************************
2320 * Function : server_content_length
2322 * Description : Adjust Content-Length header if we modified
2326 * 1 : csp = Current client state (buffers, headers, etc...)
2327 * 2 : header = On input, pointer to header to modify.
2328 * On output, pointer to the modified header, or NULL
2329 * to remove the header. This function frees the
2330 * original string if necessary.
2332 * Returns : JB_ERR_OK on success, or
2333 * JB_ERR_MEMORY on out-of-memory error.
2335 *********************************************************************/
2336 static jb_err server_content_length(struct client_state *csp, char **header)
2338 const size_t max_header_length = 80;
2340 /* Regenerate header if the content was modified. */
2341 if (csp->flags & CSP_FLAG_MODIFIED)
2344 *header = (char *) zalloc(max_header_length);
2345 if (*header == NULL)
2347 return JB_ERR_MEMORY;
2350 snprintf(*header, max_header_length, "Content-Length: %d",
2351 (int)csp->content_length);
2352 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2353 (int)csp->content_length);
2360 /*********************************************************************
2362 * Function : server_content_md5
2364 * Description : Crumble any Content-MD5 headers if the document was
2365 * modified. FIXME: Should we re-compute instead?
2368 * 1 : csp = Current client state (buffers, headers, etc...)
2369 * 2 : header = On input, pointer to header to modify.
2370 * On output, pointer to the modified header, or NULL
2371 * to remove the header. This function frees the
2372 * original string if necessary.
2374 * Returns : JB_ERR_OK on success, or
2375 * JB_ERR_MEMORY on out-of-memory error.
2377 *********************************************************************/
2378 static jb_err server_content_md5(struct client_state *csp, char **header)
2380 if (csp->flags & CSP_FLAG_MODIFIED)
2382 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2389 /*********************************************************************
2391 * Function : server_content_disposition
2393 * Description : If enabled, blocks or modifies the "content-disposition" header.
2394 * Called from `sed'.
2397 * 1 : csp = Current client state (buffers, headers, etc...)
2398 * 2 : header = On input, pointer to header to modify.
2399 * On output, pointer to the modified header, or NULL
2400 * to remove the header. This function frees the
2401 * original string if necessary.
2403 * Returns : JB_ERR_OK on success, or
2404 * JB_ERR_MEMORY on out-of-memory error.
2406 *********************************************************************/
2407 static jb_err server_content_disposition(struct client_state *csp, char **header)
2412 * Are we messing with the content-disposition header?
2414 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2420 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2422 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2425 * Blocking content-disposition header
2427 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2434 * Replacing content-disposition header
2437 *header = strdup("content-disposition: ");
2438 string_append(header, newval);
2440 if (*header == NULL)
2442 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2446 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2449 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2452 /*********************************************************************
2454 * Function : server_last_modified
2456 * Description : Changes Last-Modified header to the actual date
2457 * to help hide-if-modified-since.
2458 * Called from `sed'.
2461 * 1 : csp = Current client state (buffers, headers, etc...)
2462 * 2 : header = On input, pointer to header to modify.
2463 * On output, pointer to the modified header, or NULL
2464 * to remove the header. This function frees the
2465 * original string if necessary.
2467 * Returns : JB_ERR_OK on success, or
2468 * JB_ERR_MEMORY on out-of-memory error.
2470 *********************************************************************/
2471 static jb_err server_last_modified(struct client_state *csp, char **header)
2474 char buf[BUFFER_SIZE];
2477 #ifdef HAVE_GMTIME_R
2480 struct tm *timeptr = NULL;
2481 time_t now, last_modified;
2483 long int days, hours, minutes, seconds;
2486 * Are we messing with the Last-Modified header?
2488 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2494 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2496 if (0 == strcmpic(newval, "block") )
2499 * Blocking Last-Modified header. Useless but why not.
2501 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2505 else if (0 == strcmpic(newval, "reset-to-request-time"))
2508 * Setting Last-Modified Header to now.
2510 get_http_time(0, buf);
2512 *header = strdup("Last-Modified: ");
2513 string_append(header, buf);
2515 if (*header == NULL)
2517 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2521 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2524 else if (0 == strcmpic(newval, "randomize"))
2526 const char *header_time = *header + sizeof("Last-Modified:");
2528 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2530 #ifdef HAVE_GMTIME_R
2531 timeptr = gmtime_r(&now, &gmt);
2532 #elif FEATURE_PTHREAD
2533 pthread_mutex_lock(&gmtime_mutex);
2534 timeptr = gmtime(&now);
2535 pthread_mutex_unlock(&gmtime_mutex);
2537 timeptr = gmtime(&now);
2539 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2541 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2546 rtime = (long int)difftime(now, last_modified);
2549 rtime = pick_from_range(rtime);
2550 last_modified += rtime;
2551 #ifdef HAVE_GMTIME_R
2552 timeptr = gmtime_r(&last_modified, &gmt);
2553 #elif FEATURE_PTHREAD
2554 pthread_mutex_lock(&gmtime_mutex);
2555 timeptr = gmtime(&last_modified);
2556 pthread_mutex_unlock(&gmtime_mutex);
2558 timeptr = gmtime(&last_modified);
2560 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2562 *header = strdup("Last-Modified: ");
2563 string_append(header, newheader);
2565 if (*header == NULL)
2567 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2568 return JB_ERR_MEMORY;
2571 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2573 days = rtime / (3600 * 24);
2574 hours = rtime / 3600 % 24;
2575 minutes = rtime / 60 % 60;
2576 seconds = rtime % 60;
2578 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2579 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2580 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2585 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2594 /*********************************************************************
2596 * Function : client_accept_encoding
2598 * Description : Rewrite the client's Accept-Encoding header so that
2599 * if doesn't allow compression, if the action applies.
2600 * Note: For HTTP/1.0 the absence of the header is enough.
2603 * 1 : csp = Current client state (buffers, headers, etc...)
2604 * 2 : header = On input, pointer to header to modify.
2605 * On output, pointer to the modified header, or NULL
2606 * to remove the header. This function frees the
2607 * original string if necessary.
2609 * Returns : JB_ERR_OK on success, or
2610 * JB_ERR_MEMORY on out-of-memory error.
2612 *********************************************************************/
2613 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2615 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2617 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2621 /* Temporarily disable the correct behaviour to
2622 * work around a PHP bug.
2624 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2626 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2627 * if (*header == NULL)
2629 * return JB_ERR_MEMORY;
2640 /*********************************************************************
2642 * Function : client_te
2644 * Description : Rewrite the client's TE header so that
2645 * if doesn't allow compression, if the action applies.
2648 * 1 : csp = Current client state (buffers, headers, etc...)
2649 * 2 : header = On input, pointer to header to modify.
2650 * On output, pointer to the modified header, or NULL
2651 * to remove the header. This function frees the
2652 * original string if necessary.
2654 * Returns : JB_ERR_OK on success, or
2655 * JB_ERR_MEMORY on out-of-memory error.
2657 *********************************************************************/
2658 static jb_err client_te(struct client_state *csp, char **header)
2660 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2663 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2669 /*********************************************************************
2671 * Function : client_referrer
2673 * Description : Handle the "referer" config setting properly.
2674 * Called from `sed'.
2677 * 1 : csp = Current client state (buffers, headers, etc...)
2678 * 2 : header = On input, pointer to header to modify.
2679 * On output, pointer to the modified header, or NULL
2680 * to remove the header. This function frees the
2681 * original string if necessary.
2683 * Returns : JB_ERR_OK on success, or
2684 * JB_ERR_MEMORY on out-of-memory error.
2686 *********************************************************************/
2687 static jb_err client_referrer(struct client_state *csp, char **header)
2694 #ifdef FEATURE_FORCE_LOAD
2695 /* Since the referrer can include the prefix even
2696 * if the request itself is non-forced, we must
2697 * clean it unconditionally
2699 strclean(*header, FORCE_PREFIX);
2700 #endif /* def FEATURE_FORCE_LOAD */
2703 * Are we sending referer?
2705 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2710 newval = csp->action->string[ACTION_STRING_REFERER];
2712 if ((0 != strcmpic(newval, "conditional-block")))
2716 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2721 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2724 else if (0 == strcmpic(newval, "conditional-block"))
2727 * Block referer if host has changed.
2730 if (NULL == (host = strdup(csp->http->hostport)))
2733 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2734 return JB_ERR_MEMORY;
2736 if (NULL == (referer = strdup(*header)))
2740 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2741 return JB_ERR_MEMORY;
2743 hostlenght = strlen(host);
2744 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2746 /*Shorten referer to make sure the referer is blocked
2747 *if www.example.org/www.example.com-shall-see-the-referer/
2748 *links to www.example.com/
2750 referer[hostlenght+17] = '\0';
2752 if ( 0 == strstr(referer, host)) /*Host has changed*/
2754 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2759 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2765 else if (0 != strcmpic(newval, "forge"))
2768 * We have a specific (fixed) referer we want to send.
2770 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2772 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2774 *header = strdup("Referer: ");
2775 string_append(header, newval);
2776 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2778 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2783 * Forge a referer as http://[hostname:port of REQUEST]/
2784 * to fool stupid checks for in-site links
2787 *header = strdup("Referer: http://");
2788 string_append(header, csp->http->hostport);
2789 string_append(header, "/");
2790 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2792 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2796 /*********************************************************************
2798 * Function : client_accept_language
2800 * Description : Handle the "Accept-Language" config setting properly.
2801 * Called from `sed'.
2804 * 1 : csp = Current client state (buffers, headers, etc...)
2805 * 2 : header = On input, pointer to header to modify.
2806 * On output, pointer to the modified header, or NULL
2807 * to remove the header. This function frees the
2808 * original string if necessary.
2810 * Returns : JB_ERR_OK on success, or
2811 * JB_ERR_MEMORY on out-of-memory error.
2813 *********************************************************************/
2814 static jb_err client_accept_language(struct client_state *csp, char **header)
2819 * Are we messing with the Accept-Language?
2821 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2823 /*I don't think so*/
2827 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2829 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2832 * Blocking Accept-Language header
2834 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2841 * Replacing Accept-Language header
2844 *header = strdup("Accept-Language: ");
2845 string_append(header, newval);
2847 if (*header == NULL)
2849 log_error(LOG_LEVEL_ERROR,
2850 "Insufficent memory. Accept-Language header crunched without replacement.");
2854 log_error(LOG_LEVEL_HEADER,
2855 "Accept-Language header crunched and replaced with: %s", *header);
2858 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2862 /*********************************************************************
2864 * Function : crunch_client_header
2866 * Description : Crunch client header if it matches a string supplied by the
2867 * user. Called from `sed'.
2870 * 1 : csp = Current client state (buffers, headers, etc...)
2871 * 2 : header = On input, pointer to header to modify.
2872 * On output, pointer to the modified header, or NULL
2873 * to remove the header. This function frees the
2874 * original string if necessary.
2876 * Returns : JB_ERR_OK on success and always succeeds
2878 *********************************************************************/
2879 static jb_err crunch_client_header(struct client_state *csp, char **header)
2881 const char *crunch_pattern;
2883 /* Do we feel like crunching? */
2884 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2886 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2888 /* Is the current header the lucky one? */
2889 if (strstr(*header, crunch_pattern))
2891 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2899 /*********************************************************************
2901 * Function : client_uagent
2903 * Description : Handle the "user-agent" config setting properly
2904 * and remember its original value to enable browser
2905 * bug workarounds. Called from `sed'.
2908 * 1 : csp = Current client state (buffers, headers, etc...)
2909 * 2 : header = On input, pointer to header to modify.
2910 * On output, pointer to the modified header, or NULL
2911 * to remove the header. This function frees the
2912 * original string if necessary.
2914 * Returns : JB_ERR_OK on success, or
2915 * JB_ERR_MEMORY on out-of-memory error.
2917 *********************************************************************/
2918 static jb_err client_uagent(struct client_state *csp, char **header)
2922 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2927 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2934 *header = strdup("User-Agent: ");
2935 string_append(header, newval);
2937 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2939 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2942 /*********************************************************************
2944 * Function : client_ua
2946 * Description : Handle "ua-" headers properly. Called from `sed'.
2949 * 1 : csp = Current client state (buffers, headers, etc...)
2950 * 2 : header = On input, pointer to header to modify.
2951 * On output, pointer to the modified header, or NULL
2952 * to remove the header. This function frees the
2953 * original string if necessary.
2955 * Returns : JB_ERR_OK on success, or
2956 * JB_ERR_MEMORY on out-of-memory error.
2958 *********************************************************************/
2959 static jb_err client_ua(struct client_state *csp, char **header)
2961 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2963 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2971 /*********************************************************************
2973 * Function : client_from
2975 * Description : Handle the "from" config setting properly.
2976 * Called from `sed'.
2979 * 1 : csp = Current client state (buffers, headers, etc...)
2980 * 2 : header = On input, pointer to header to modify.
2981 * On output, pointer to the modified header, or NULL
2982 * to remove the header. This function frees the
2983 * original string if necessary.
2985 * Returns : JB_ERR_OK on success, or
2986 * JB_ERR_MEMORY on out-of-memory error.
2988 *********************************************************************/
2989 static jb_err client_from(struct client_state *csp, char **header)
2993 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3000 newval = csp->action->string[ACTION_STRING_FROM];
3003 * Are we blocking the e-mail address?
3005 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3007 log_error(LOG_LEVEL_HEADER, "crunched From!");
3011 log_error(LOG_LEVEL_HEADER, " modified");
3013 *header = strdup("From: ");
3014 string_append(header, newval);
3016 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3020 /*********************************************************************
3022 * Function : client_send_cookie
3024 * Description : Crunches the "cookie" header if necessary.
3025 * Called from `sed'.
3027 * XXX: Stupid name, doesn't send squat.
3030 * 1 : csp = Current client state (buffers, headers, etc...)
3031 * 2 : header = On input, pointer to header to modify.
3032 * On output, pointer to the modified header, or NULL
3033 * to remove the header. This function frees the
3034 * original string if necessary.
3036 * Returns : JB_ERR_OK on success, or
3037 * JB_ERR_MEMORY on out-of-memory error.
3039 *********************************************************************/
3040 static jb_err client_send_cookie(struct client_state *csp, char **header)
3042 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3044 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3052 /*********************************************************************
3054 * Function : client_x_forwarded
3056 * Description : Handle the "x-forwarded-for" config setting properly,
3057 * also used in the add_client_headers list. Called from `sed'.
3060 * 1 : csp = Current client state (buffers, headers, etc...)
3061 * 2 : header = On input, pointer to header to modify.
3062 * On output, pointer to the modified header, or NULL
3063 * to remove the header. This function frees the
3064 * original string if necessary.
3066 * Returns : JB_ERR_OK on success, or
3067 * JB_ERR_MEMORY on out-of-memory error.
3069 *********************************************************************/
3070 jb_err client_x_forwarded(struct client_state *csp, char **header)
3072 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3074 /* Save it so we can re-add it later */
3075 freez(csp->x_forwarded);
3076 csp->x_forwarded = *header;
3079 * Always set *header = NULL, since this information
3080 * will be sent at the end of the header.
3087 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3094 /*********************************************************************
3096 * Function : client_max_forwards
3098 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3099 * from the value of the Max-Forwards header field.
3102 * 1 : csp = Current client state (buffers, headers, etc...)
3103 * 2 : header = On input, pointer to header to modify.
3104 * On output, pointer to the modified header, or NULL
3105 * to remove the header. This function frees the
3106 * original string if necessary.
3108 * Returns : JB_ERR_OK on success, or
3109 * JB_ERR_MEMORY on out-of-memory error.
3111 *********************************************************************/
3112 static jb_err client_max_forwards(struct client_state *csp, char **header)
3116 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3117 (0 == strcmpic(csp->http->gpc, "options")))
3119 assert(*(*header+12) == ':');
3120 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3122 if (max_forwards > 0)
3124 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3125 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3126 csp->http->gpc, max_forwards);
3128 else if (max_forwards < 0)
3130 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3136 * Not supposed to be reached. direct_response() which
3137 * was already called earlier in chat() should have
3138 * intercepted the request.
3140 log_error(LOG_LEVEL_ERROR,
3141 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3142 assert(max_forwards != 0);
3147 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3156 /*********************************************************************
3158 * Function : client_host
3160 * Description : If the request URI did not contain host and
3161 * port information, parse and evaluate the Host
3164 * Also, kill ill-formed HOST: headers as sent by
3165 * Apple's iTunes software when used with a proxy.
3168 * 1 : csp = Current client state (buffers, headers, etc...)
3169 * 2 : header = On input, pointer to header to modify.
3170 * On output, pointer to the modified header, or NULL
3171 * to remove the header. This function frees the
3172 * original string if necessary.
3174 * Returns : JB_ERR_OK on success, or
3175 * JB_ERR_MEMORY on out-of-memory error.
3177 *********************************************************************/
3178 static jb_err client_host(struct client_state *csp, char **header)
3183 * If the header field name is all upper-case, chances are that it's
3184 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3185 * not a problem -- they are regenerated later.
3187 if ((*header)[1] == 'O')
3189 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3194 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3195 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3198 if (NULL == (p = strdup((*header)+6)))
3200 return JB_ERR_MEMORY;
3203 if (NULL == (q = strdup(p)))
3206 return JB_ERR_MEMORY;
3209 freez(csp->http->hostport);
3210 csp->http->hostport = p;
3211 freez(csp->http->host);
3212 csp->http->host = q;
3213 q = strchr(csp->http->host, ':');
3216 /* Terminate hostname and evaluate port string */
3218 csp->http->port = atoi(q);
3222 csp->http->port = csp->http->ssl ? 443 : 80;
3225 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3226 csp->http->hostport, csp->http->host, csp->http->port);
3229 /* Signal client_host_adder() to return right away */
3230 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3235 /*********************************************************************
3237 * Function : client_if_modified_since
3239 * Description : Remove or modify the If-Modified-Since header.
3242 * 1 : csp = Current client state (buffers, headers, etc...)
3243 * 2 : header = On input, pointer to header to modify.
3244 * On output, pointer to the modified header, or NULL
3245 * to remove the header. This function frees the
3246 * original string if necessary.
3248 * Returns : JB_ERR_OK on success, or
3249 * JB_ERR_MEMORY on out-of-memory error.
3251 *********************************************************************/
3252 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3255 #ifdef HAVE_GMTIME_R
3258 struct tm *timeptr = NULL;
3262 long int hours, minutes, seconds;
3266 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3269 * The client got an error message because of a temporary problem,
3270 * the problem is gone and the client now tries to revalidate our
3271 * error message on the real server. The revalidation would always
3272 * end with the transmission of the whole document and there is
3273 * no need to expose the bogus If-Modified-Since header.
3275 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3278 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3280 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3282 if ((0 == strcmpic(newval, "block")))
3284 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3287 else /* add random value */
3289 const char *header_time = *header + sizeof("If-Modified-Since:");
3291 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3293 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3298 rtime = strtol(newval, &endptr, 0);
3301 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3302 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3309 rtime = pick_from_range(rtime);
3313 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3316 tm += rtime * (negative ? -1 : 1);
3317 #ifdef HAVE_GMTIME_R
3318 timeptr = gmtime_r(&tm, &gmt);
3319 #elif FEATURE_PTHREAD
3320 pthread_mutex_lock(&gmtime_mutex);
3321 timeptr = gmtime(&tm);
3322 pthread_mutex_unlock(&gmtime_mutex);
3324 timeptr = gmtime(&tm);
3326 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3329 *header = strdup("If-Modified-Since: ");
3330 string_append(header, newheader);
3332 if (*header == NULL)
3334 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3335 return JB_ERR_MEMORY;
3338 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3340 hours = rtime / 3600;
3341 minutes = rtime / 60 % 60;
3342 seconds = rtime % 60;
3344 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3345 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3346 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3355 /*********************************************************************
3357 * Function : client_if_none_match
3359 * Description : Remove the If-None-Match header.
3362 * 1 : csp = Current client state (buffers, headers, etc...)
3363 * 2 : header = On input, pointer to header to modify.
3364 * On output, pointer to the modified header, or NULL
3365 * to remove the header. This function frees the
3366 * original string if necessary.
3368 * Returns : JB_ERR_OK on success, or
3369 * JB_ERR_MEMORY on out-of-memory error.
3371 *********************************************************************/
3372 static jb_err client_if_none_match(struct client_state *csp, char **header)
3374 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3376 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3383 /*********************************************************************
3385 * Function : client_x_filter
3387 * Description : Disables filtering if the client set "X-Filter: No".
3388 * Called from `sed'.
3391 * 1 : csp = Current client state (buffers, headers, etc...)
3392 * 2 : header = On input, pointer to header to modify.
3393 * On output, pointer to the modified header, or NULL
3394 * to remove the header. This function frees the
3395 * original string if necessary.
3397 * Returns : JB_ERR_OK on success
3399 *********************************************************************/
3400 jb_err client_x_filter(struct client_state *csp, char **header)
3402 if ( 0 == strcmpic(*header, "X-Filter: No"))
3404 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3406 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3410 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3412 log_error(LOG_LEVEL_HEADER,
3413 "force-text-mode overruled the client's request to fetch without filtering!");
3417 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3418 csp->flags |= CSP_FLAG_NO_FILTERING;
3419 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3421 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3428 /* the following functions add headers directly to the header list */
3430 /*********************************************************************
3432 * Function : client_host_adder
3434 * Description : Adds the Host: header field if it is missing.
3435 * Called from `sed'.
3438 * 1 : csp = Current client state (buffers, headers, etc...)
3440 * Returns : JB_ERR_OK on success, or
3441 * JB_ERR_MEMORY on out-of-memory error.
3443 *********************************************************************/
3444 static jb_err client_host_adder(struct client_state *csp)
3449 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3451 /* Header already set by the client, nothing to do. */
3455 if ( !csp->http->hostport || !*(csp->http->hostport))
3457 /* XXX: When does this happen and why is it OK? */
3458 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3463 * remove 'user:pass@' from 'proto://user:pass@host'
3465 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3471 p = csp->http->hostport;
3474 /* XXX: Just add it, we already made sure that it will be unique */
3475 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3476 err = enlist_unique_header(csp->headers, "Host", p);
3482 /*********************************************************************
3484 * Function : client_cookie_adder
3486 * Description : Used in the add_client_headers list to add "wafers".
3487 * Called from `sed'.
3490 * 1 : csp = Current client state (buffers, headers, etc...)
3492 * Returns : JB_ERR_OK on success, or
3493 * JB_ERR_MEMORY on out-of-memory error.
3495 *********************************************************************/
3496 jb_err client_cookie_adder(struct client_state *csp)
3499 struct list_entry *wafer;
3500 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3503 if (NULL == wafer_list)
3509 tmp = strdup("Cookie: ");
3511 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3513 if (wafer != wafer_list)
3515 /* As this isn't the first wafer, we need a delimiter. */
3516 string_append(&tmp, "; ");
3518 string_join(&tmp, cookie_encode(wafer->str));
3523 return JB_ERR_MEMORY;
3526 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3527 err = enlist(csp->headers, tmp);
3533 /*********************************************************************
3535 * Function : client_accept_encoding_adder
3537 * Description : Add an Accept-Encoding header to the client's request
3538 * that disables compression if the action applies, and
3539 * the header is not already there. Called from `sed'.
3540 * Note: For HTTP/1.0, the absence of the header is enough.
3543 * 1 : csp = Current client state (buffers, headers, etc...)
3545 * Returns : JB_ERR_OK on success, or
3546 * JB_ERR_MEMORY on out-of-memory error.
3548 *********************************************************************/
3549 static jb_err client_accept_encoding_adder(struct client_state *csp)
3551 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3552 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3554 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3561 /*********************************************************************
3563 * Function : client_xtra_adder
3565 * Description : Used in the add_client_headers list. Called from `sed'.
3568 * 1 : csp = Current client state (buffers, headers, etc...)
3570 * Returns : JB_ERR_OK on success, or
3571 * JB_ERR_MEMORY on out-of-memory error.
3573 *********************************************************************/
3574 static jb_err client_xtra_adder(struct client_state *csp)
3576 struct list_entry *lst;
3579 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3580 lst ; lst = lst->next)
3582 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3583 err = enlist(csp->headers, lst->str);
3595 /*********************************************************************
3597 * Function : client_x_forwarded_adder
3599 * Description : Used in the add_client_headers list. Called from `sed'.
3602 * 1 : csp = Current client state (buffers, headers, etc...)
3604 * Returns : JB_ERR_OK on success, or
3605 * JB_ERR_MEMORY on out-of-memory error.
3607 *********************************************************************/
3608 static jb_err client_x_forwarded_adder(struct client_state *csp)
3613 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3618 if (csp->x_forwarded)
3620 p = strdup(csp->x_forwarded);
3621 string_append(&p, ", ");
3625 p = strdup("X-Forwarded-For: ");
3627 string_append(&p, csp->ip_addr_str);
3631 return JB_ERR_MEMORY;
3634 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3635 err = enlist(csp->headers, p);
3642 /*********************************************************************
3644 * Function : connection_close_adder
3646 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3647 * support. Adds a "Connection: close" header to csp->headers
3648 * unless the header was already present. Called from `sed'.
3650 * FIXME: This whole function shouldn't be neccessary!
3653 * 1 : csp = Current client state (buffers, headers, etc...)
3655 * Returns : JB_ERR_OK on success, or
3656 * JB_ERR_MEMORY on out-of-memory error.
3658 *********************************************************************/
3659 static jb_err connection_close_adder(struct client_state *csp)
3661 const unsigned int flags = csp->flags;
3664 * Return right away if
3666 * - we're parsing server headers and the server header
3667 * "Connection: close" is already set, or if
3669 * - we're parsing client headers and the client header
3670 * "Connection: close" is already set.
3672 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3673 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3674 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3675 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3680 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3682 return enlist(csp->headers, "Connection: close");
3686 /*********************************************************************
3688 * Function : server_http
3690 * Description : - Save the HTTP Status into csp->http->status
3691 * - Set CT_TABOO to prevent filtering if the answer
3692 * is a partial range (HTTP status 206)
3693 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3697 * 1 : csp = Current client state (buffers, headers, etc...)
3698 * 2 : header = On input, pointer to header to modify.
3699 * On output, pointer to the modified header, or NULL
3700 * to remove the header. This function frees the
3701 * original string if necessary.
3703 * Returns : JB_ERR_OK on success, or
3704 * JB_ERR_MEMORY on out-of-memory error.
3706 *********************************************************************/
3707 static jb_err server_http(struct client_state *csp, char **header)
3709 /* XXX: Doesn't belong here. */
3710 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3711 if (csp->http->status == 206)
3713 csp->content_type = CT_TABOO;
3716 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3718 /* XXX: Should we do a real validity check here? */
3719 if (strlen(*header) > 8)
3722 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3727 * XXX: Should we block the request or
3728 * enlist a valid status code line here?
3730 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3731 "Downgrading to HTTP/1.0 impossible.");
3739 /*********************************************************************
3741 * Function : server_set_cookie
3743 * Description : Handle the server "cookie" header properly.
3744 * Log cookie to the jar file. Then "crunch",
3745 * accept or rewrite it to a session cookie.
3746 * Called from `sed'.
3748 * TODO: Allow the user to specify a new expiration
3749 * time to cause the cookie to expire even before the
3750 * browser is closed.
3753 * 1 : csp = Current client state (buffers, headers, etc...)
3754 * 2 : header = On input, pointer to header to modify.
3755 * On output, pointer to the modified header, or NULL
3756 * to remove the header. This function frees the
3757 * original string if necessary.
3759 * Returns : JB_ERR_OK on success, or
3760 * JB_ERR_MEMORY on out-of-memory error.
3762 *********************************************************************/
3763 static jb_err server_set_cookie(struct client_state *csp, char **header)
3770 #ifdef FEATURE_COOKIE_JAR
3771 if (csp->config->jar)
3774 * Write timestamp into outbuf.
3776 * Complex because not all OSs have tm_gmtoff or
3777 * the %z field in strftime()
3779 char tempbuf[ BUFFER_SIZE ];
3781 #ifdef HAVE_LOCALTIME_R
3782 tm_now = *localtime_r(&now, &tm_now);
3783 #elif FEATURE_PTHREAD
3784 pthread_mutex_lock(&localtime_mutex);
3785 tm_now = *localtime (&now);
3786 pthread_mutex_unlock(&localtime_mutex);
3788 tm_now = *localtime (&now);
3790 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3792 /* strlen("set-cookie: ") = 12 */
3793 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3795 #endif /* def FEATURE_COOKIE_JAR */
3797 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3799 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3802 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3804 /* Flag whether or not to log a message */
3807 /* A variable to store the tag we're working on */
3810 /* Skip "Set-Cookie:" (11 characters) in header */
3811 cur_tag = *header + 11;
3813 /* skip whitespace between "Set-Cookie:" and value */
3814 while (*cur_tag && ijb_isspace(*cur_tag))
3819 /* Loop through each tag in the cookie */
3823 char *next_tag = strchr(cur_tag, ';');
3824 if (next_tag != NULL)
3826 /* Skip the ';' character itself */
3829 /* skip whitespace ";" and start of tag */
3830 while (*next_tag && ijb_isspace(*next_tag))
3837 /* "Next tag" is the end of the string */
3838 next_tag = cur_tag + strlen(cur_tag);
3842 * Check the expiration date to see
3843 * if the cookie is still valid, if yes,
3844 * rewrite it to a session cookie.
3846 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3848 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3850 /* Did we detect the date properly? */
3851 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3854 * Nope, treat it as if it was still valid.
3856 * XXX: Should we remove the whole cookie instead?
3858 log_error(LOG_LEVEL_ERROR,
3859 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3860 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3866 * Yes. Check if the cookie is still valid.
3868 * If the cookie is already expired it's probably
3869 * a delete cookie and even if it isn't, the browser
3870 * will discard it anyway.
3874 * XXX: timegm() isn't available on some AmigaOS
3875 * versions and our replacement doesn't work.
3877 * Our options are to either:
3879 * - disable session-cookies-only completely if timegm
3882 * - to simply remove all expired tags, like it has
3883 * been done until Privoxy 3.0.6 and to live with
3884 * the consequence that it can cause login/logout
3885 * problems on servers that don't validate their
3886 * input properly, or
3888 * - to replace it with mktime in which
3889 * case there is a slight chance of valid cookies
3890 * passing as already expired.
3892 * This is the way it's currently done and it's not
3893 * as bad as it sounds. If the missing GMT offset is
3894 * enough to change the result of the expiration check
3895 * the cookie will be only valid for a few hours
3896 * anyway, which in many cases will be shorter
3897 * than a browser session.
3899 if (cookie_time - now < 0)
3901 log_error(LOG_LEVEL_HEADER,
3902 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3903 /* Just in case some clown sets more then one expiration date */
3909 * Still valid, delete expiration date by copying
3910 * the rest of the string over it.
3912 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3913 * since the behaviour of strcpy is undefined for overlapping
3916 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3918 /* That changed the header, need to issue a log message */
3922 * Note that the next tag has now been moved to *cur_tag,
3923 * so we do not need to update the cur_tag pointer.
3931 /* Move on to next cookie tag */
3938 assert(NULL != *header);
3939 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3948 #ifdef FEATURE_FORCE_LOAD
3949 /*********************************************************************
3951 * Function : strclean
3953 * Description : In-Situ-Eliminate all occurances of substring in
3957 * 1 : string = string to clean
3958 * 2 : substring = substring to eliminate
3960 * Returns : Number of eliminations
3962 *********************************************************************/
3963 int strclean(const char *string, const char *substring)
3969 len = strlen(substring);
3971 while((pos = strstr(string, substring)) != NULL)
3978 while (*p++ != '\0');
3985 #endif /* def FEATURE_FORCE_LOAD */
3987 /*********************************************************************
3989 * Function : parse_header_time
3991 * Description : Parses time formats used in HTTP header strings
3992 * to get the numerical respresentation.
3995 * 1 : header_time = HTTP header time as string.
3996 * 2 : result = storage for header_time in seconds
3998 * Returns : JB_ERR_OK if the time format was recognized, or
3999 * JB_ERR_PARSE otherwise.
4001 *********************************************************************/
4002 static jb_err parse_header_time(const char *header_time, time_t *result)
4007 * Zero out gmt to prevent time zone offsets.
4009 * While this is only necessary on some platforms
4010 * (mingw32 for example), I don't know how to
4011 * detect these automatically and doing it everywhere
4014 memset(&gmt, 0, sizeof(gmt));
4016 /* Tue, 02 Jun 2037 20:00:00 */
4017 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4018 /* Tue, 02-Jun-2037 20:00:00 */
4019 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4020 /* Tue, 02-Jun-37 20:00:00 */
4021 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4022 /* Tuesday, 02-Jun-2037 20:00:00 */
4023 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4024 /* Tuesday Jun 02 20:00:00 2037 */
4025 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4027 return JB_ERR_PARSE;
4030 *result = timegm(&gmt);
4036 /*********************************************************************
4038 * Function : get_destination_from_headers
4040 * Description : Parse the "Host:" header to get the request's destination.
4041 * Only needed if the client's request was forcefully
4042 * redirected into Privoxy.
4044 * Code mainly copied from client_host() which is currently
4045 * run too late for this purpose.
4048 * 1 : headers = List of headers (one of them hopefully being
4049 * the "Host:" header)
4050 * 2 : http = storage for the result (host, port and hostport).
4052 * Returns : JB_ERR_MEMORY in case of memory problems,
4053 * JB_ERR_PARSE if the host header couldn't be found,
4054 * JB_ERR_OK otherwise.
4056 *********************************************************************/
4057 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4063 host = get_header_value(headers, "Host:");
4067 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4068 return JB_ERR_PARSE;
4071 if (NULL == (p = strdup((host))))
4073 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4074 return JB_ERR_MEMORY;
4077 if (NULL == (q = strdup(p)))
4080 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4081 return JB_ERR_MEMORY;
4084 freez(http->hostport);
4088 q = strchr(http->host, ':');
4091 /* Terminate hostname and evaluate port string */
4093 http->port = atoi(q);
4097 http->port = http->ssl ? 443 : 80;
4100 /* Rebuild request URL */
4102 http->url = strdup(http->ssl ? "https://" : "http://");
4103 string_append(&http->url, http->hostport);
4104 string_append(&http->url, http->path);
4105 if (http->url == NULL)
4107 return JB_ERR_MEMORY;
4110 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",