1 const char parsers_rcs[] = "$Id: parsers.c,v 1.95 2007/03/25 14:26:40 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.95 2007/03/25 14:26:40 fabiankeil
48 * - Fix warnings when compiled with glibc.
49 * - Don't use crumble() for cookie crunching.
50 * - Move cookie time parsing into parse_header_time().
51 * - Let parse_header_time() return a jb_err code
52 * instead of a pointer that can only be used to
53 * check for NULL anyway.
55 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
56 * - Add better protection against malicious gzip headers.
57 * - Stop logging the first hundred bytes of decompressed content.
58 * It looks like it's working and there is always debug 16.
59 * - Log the content size after decompression in decompress_iob()
60 * instead of pcrs_filter_response().
62 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
63 * - Use dedicated header filter actions instead of abusing "filter".
64 * Replace "filter-client-headers" and "filter-client-headers"
65 * with "server-header-filter" and "client-header-filter".
66 * - Remove filter_client_header() and filter_client_header(),
67 * filter_header() now checks the shiny new
68 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
70 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
71 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
72 * - Handle "Cookie:" and "Connection:" headers a bit smarter
73 * (don't crunch them just to recreate them later on).
74 * - Add another non-standard time format for the cookie
75 * expiration date detection.
76 * - Fix a valgrind warning.
78 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
79 * Improve cookie expiration date detection.
81 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
82 * Don't run server_content_length() the first time
83 * sed() parses server headers; only adjust the
84 * Content-Length header if the page was modified.
86 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
87 * Fix log messages regarding the cookie time format
88 * (cookie and request URL were mixed up).
90 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
91 * - Let decompress_iob()
92 * - not corrupt the content if decompression fails
93 * early. (the first byte(s) were lost).
94 * - use pointer arithmetics with defined outcome for
96 * - Use a different kludge to remember a failed decompression.
98 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
99 * Search for Max-Forwards headers case-insensitive,
100 * don't generate the "501 unsupported" message for invalid
101 * Max-Forwards values and don't increase negative ones.
103 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
104 * - Let server_set_cookie() check the expiration date
105 * of cookies and don't touch the ones that are already
106 * expired. Fixes problems with low quality web applications
107 * as described in BR 932612.
109 * - Adjust comment in client_max_forwards to reality;
110 * remove invalid Max-Forwards headers.
112 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
113 * Stop filter_header() from unintentionally removing
114 * empty header lines that were enlisted by the continue
117 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
118 * - Repeat the request URL before logging any headers.
119 * Makes reading the log easier in case of simultaneous requests.
120 * - If there are more than one Content-Type headers in one request,
121 * use the first one and remove the others.
122 * - Remove "newval" variable in server_content_type().
123 * It's only used once.
125 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
126 * Correct a cast, check inflateEnd() exit code
127 * to see if we have to, replace sprintf calls
130 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
131 * Integrate a modified version of Wil Mahan's
132 * zlib patch (PR #895531).
134 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
135 * Skip empty filter files in filter_header()
136 * but don't ignore the ones that come afterwards.
137 * Fixes BR 1619208, this time for real.
139 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
140 * Reverted parts of my last commit
141 * to keep error handling working.
143 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
144 * Fixed gcc43 conversion warnings.
146 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
147 * Bringing back the "useless" localtime() call
148 * I removed in revision 1.67. On some platforms
149 * it's necessary to prevent time zone offsets.
151 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
152 * Rebuild request URL in get_destination_from_headers()
153 * to make sure redirect{pcrs command} works as expected
154 * for intercepted requests.
156 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
157 * Added get_destination_from_headers().
159 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
160 * Make pthread mutex locking more generic. Instead of
161 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
162 * and use mutex locking unless there is an _r function
163 * available. Better safe than sorry.
165 * Fixes "./configure --disable-pthread" and should result
166 * in less threading-related problems on pthread-using platforms,
167 * but it still doesn't fix BR#1122404.
169 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
170 * The special header "X-Filter: No" now disables
171 * header filtering as well.
173 * Revision 1.73 2006/09/23 13:26:38 roro
174 * Replace TABs by spaces in source code.
176 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
177 * Don't print a log message every time filter_headers is
178 * entered or left. It only creates noise without any real
181 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
182 * Fix +hide-if-modified-since{-n}.
184 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
185 * Have hide-if-modified-since interpret the random
186 * range value as minutes instead of hours. Allows
187 * more fine-grained configuration.
189 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
190 * Always have parse_header_time return a pointer
191 * that actual makes sense, even though we currently
192 * only need it to detect problems.
194 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
195 * Added config option enable-remote-http-toggle
196 * to specify if Privoxy should recognize special
197 * headers (currently only X-Filter) to change its
198 * behaviour. Disabled by default.
200 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
201 * After filtering de-chunked instances, remove
202 * "Transfer-Encoding" header entirely instead of changing
203 * it to "Transfer-Encoding: identity", which is invalid.
204 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
206 * Don't use localtime in parse_header_time. An empty time struct
207 * is good enough, it gets overwritten by strptime anyway.
209 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
210 * Use gmtime_r if available, fallback to gmtime with mutex
211 * protection for MacOSX and use vanilla gmtime for the rest.
213 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
214 * Changed client_referrer to use the right type (size_t) for
215 * hostlenght and to shorten the temporary referrer string with
216 * '\0' instead of adding a useless line break.
218 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
219 * - Back to timegm() using GnuPG's replacement if necessary.
220 * Using mktime() and localtime() could add a on hour offset if
221 * the randomize factor was big enough to lead to a summer/wintertime
224 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
226 * - Moved randomization code into pick_from_range().
228 * - Changed parse_header_time definition.
229 * time_t isn't guaranteed to be signed and
230 * if it isn't, -1 isn't available as error code.
231 * Changed some variable types in client_if_modified_since()
232 * because of the same reason.
234 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
235 * OS/2 compilation compatibility fixups
237 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
238 * Changed include from strptime.c to strptime.h
240 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
241 * Split filter-headers{} into filter-client-headers{}
242 * and filter-server-headers{}.
243 * Added parse_header_time() to share some code.
244 * Replaced timegm() with mktime().
246 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
247 * Windows service integration
249 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
250 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
252 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
253 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
254 * with what was really the latest development (the v_3_0_branch branch)
256 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
257 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
259 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
260 * Add the ability to check jpeg images for invalid
261 * lengths of comment blocks. Defensive strategy
262 * against the exploit:
263 * Microsoft Security Bulletin MS04-028
264 * Buffer Overrun in JPEG Processing (GDI+) Could
265 * Allow Code Execution (833987)
266 * Enabled with +inspect-jpegs in actions files.
268 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
269 * Excluded text/plain objects from filtering. This fixes a
270 * couple of client-crashing, download corruption and
271 * Privoxy performance issues, whose root cause lies in
272 * web servers labelling content of unknown type as text/plain.
274 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
275 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
277 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
278 * Completing the previous change
280 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
281 * Added temporary workaround for bug in PHP < 4.2.3
283 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
284 * 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.
286 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
287 * Fix typo: supressed -> suppressed
289 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
290 * Improved cookie logging
292 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
293 * Added basic support for OPTIONS and TRACE HTTP methods:
294 * - New parser function client_max_forwards which decrements
295 * the Max-Forwards HTTP header field of OPTIONS and TRACE
296 * requests by one before forwarding
297 * - New parser function client_host which extracts the host
298 * and port information from the HTTP header field if the
299 * request URI was not absolute
300 * - Don't crumble and re-add the Host: header, but only generate
301 * and append if missing
303 * Revision 1.56 2002/05/12 15:34:22 jongfoster
304 * Fixing typo in a comment
306 * Revision 1.55 2002/05/08 16:01:07 oes
307 * Optimized add_to_iob:
308 * - Use realloc instead of malloc(), memcpy(), free()
309 * - Expand to powers of two if possible, to get
310 * O(log n) reallocs instead of O(n).
311 * - Moved check for buffer limit here from chat
312 * - Report failure via returncode
314 * Revision 1.54 2002/04/02 15:03:16 oes
315 * Tiny code cosmetics
317 * Revision 1.53 2002/03/26 22:29:55 swa
318 * we have a new homepage!
320 * Revision 1.52 2002/03/24 13:25:43 swa
321 * name change related issues
323 * Revision 1.51 2002/03/13 00:27:05 jongfoster
326 * Revision 1.50 2002/03/12 01:45:35 oes
327 * More verbose logging
329 * Revision 1.49 2002/03/09 20:03:52 jongfoster
330 * - Making various functions return int rather than size_t.
331 * (Undoing a recent change). Since size_t is unsigned on
332 * Windows, functions like read_socket that return -1 on
333 * error cannot return a size_t.
335 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
336 * crashes, and also frequently caused JB to jump to 100%
337 * CPU and stay there. (Because it thought it had just
338 * read ((unsigned)-1) == 4Gb of data...)
340 * - The signature of write_socket has changed, it now simply
341 * returns success=0/failure=nonzero.
343 * - Trying to get rid of a few warnings --with-debug on
344 * Windows, I've introduced a new type "jb_socket". This is
345 * used for the socket file descriptors. On Windows, this
346 * is SOCKET (a typedef for unsigned). Everywhere else, it's
347 * an int. The error value can't be -1 any more, so it's
348 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
349 * Windows it maps to the #define INVALID_SOCKET.)
351 * - The signature of bind_port has changed.
353 * Revision 1.48 2002/03/07 03:46:53 oes
354 * Fixed compiler warnings etc
356 * Revision 1.47 2002/02/20 23:15:13 jongfoster
357 * Parsing functions now handle out-of-memory gracefully by returning
360 * Revision 1.46 2002/01/17 21:03:47 jongfoster
361 * Moving all our URL and URL pattern parsing code to urlmatch.c.
363 * Revision 1.45 2002/01/09 14:33:03 oes
364 * Added support for localtime_r.
366 * Revision 1.44 2001/12/14 01:22:54 steudten
367 * Remove 'user:pass@' from 'proto://user:pass@host' for the
368 * new added header 'Host: ..'. (See Req ID 491818)
370 * Revision 1.43 2001/11/23 00:26:38 jongfoster
371 * Fixing two really stupid errors in my previous commit
373 * Revision 1.42 2001/11/22 21:59:30 jongfoster
374 * Adding code to handle +no-cookies-keep
376 * Revision 1.41 2001/11/05 23:43:05 steudten
377 * Add time+date to log files.
379 * Revision 1.40 2001/10/26 20:13:09 jongfoster
380 * ctype.h is needed in Windows, too.
382 * Revision 1.39 2001/10/26 17:40:04 oes
383 * Introduced get_header_value()
384 * Removed http->user_agent, csp->referrer and csp->accept_types
385 * Removed client_accept()
387 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
388 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
389 * threads to call select() simultaneously. So, it's time to do a real, live,
390 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
391 * (native). Both versions will work, but using __OS2__ offers multi-threading.
393 * Revision 1.37 2001/10/23 21:36:02 jongfoster
394 * Documenting sed()'s error behaviou (doc change only)
396 * Revision 1.36 2001/10/13 12:51:51 joergs
397 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
398 * force-load), instead crumble Host: and add it (again) in client_host_adder
399 * (in case we get a HTTP/1.0 request without Host: header and forward it to
400 * a HTTP/1.1 server/proxy).
402 * Revision 1.35 2001/10/09 22:39:21 jongfoster
403 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
406 * Revision 1.34 2001/10/07 18:50:55 oes
407 * Added server_content_encoding, renamed server_transfer_encoding
409 * Revision 1.33 2001/10/07 18:04:49 oes
410 * Changed server_http11 to server_http and its pattern to "HTTP".
411 * Additional functionality: it now saves the HTTP status into
412 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
414 * Revision 1.32 2001/10/07 15:43:28 oes
415 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
416 * client_te and client_accept_encoding_adder, triggered by the new
417 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
418 * changed to allow only identity and chunked, and the TE header is
419 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
421 * parse_http_request no longer does anything than parsing. The rewriting
422 * of http->cmd and version mangling are gone. It now also recognizes
423 * the put and delete methods and saves the url in http->url. Removed
426 * renamed content_type and content_length to have the server_ prefix
428 * server_content_type now only works if csp->content_type != CT_TABOO
430 * added server_transfer_encoding, which
431 * - Sets CT_TABOO to prohibit filtering if encoding compresses
432 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
433 * - Change from "chunked" to "identity" if body was chunked
434 * but has been de-chunked for filtering.
436 * added server_content_md5 which crunches any Content-MD5 headers
437 * if the body was modified.
439 * made server_http11 conditional on +downgrade action
441 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
443 * Revision 1.31 2001/10/05 14:25:02 oes
444 * Crumble Keep-Alive from Server
446 * Revision 1.30 2001/09/29 12:56:03 joergs
447 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
449 * Revision 1.29 2001/09/24 21:09:24 jongfoster
450 * Fixing 2 memory leaks that Guy spotted, where the paramater to
451 * enlist() was not being free()d.
453 * Revision 1.28 2001/09/22 16:32:28 jongfoster
454 * Removing unused #includes.
456 * Revision 1.27 2001/09/20 15:45:25 steudten
458 * add casting from size_t to int for printf()
459 * remove local variable shadow s2
461 * Revision 1.26 2001/09/16 17:05:14 jongfoster
462 * Removing unused #include showarg.h
464 * Revision 1.25 2001/09/16 13:21:27 jongfoster
465 * Changes to use new list functions.
467 * Revision 1.24 2001/09/13 23:05:50 jongfoster
468 * Changing the string paramater to the header parsers a "const".
470 * Revision 1.23 2001/09/12 18:08:19 steudten
472 * In parse_http_request() header rewriting miss the host value, so
473 * from http://www.mydomain.com the result was just " / " not
474 * http://www.mydomain.com/ in case we forward.
476 * Revision 1.22 2001/09/10 10:58:53 oes
477 * Silenced compiler warnings
479 * Revision 1.21 2001/07/31 14:46:00 oes
480 * - Persistant connections now suppressed
481 * - sed() no longer appends empty header to csp->headers
483 * Revision 1.20 2001/07/30 22:08:36 jongfoster
484 * Tidying up #defines:
485 * - All feature #defines are now of the form FEATURE_xxx
486 * - Permanently turned off WIN_GUI_EDIT
487 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
489 * Revision 1.19 2001/07/25 17:21:54 oes
490 * client_uagent now saves copy of User-Agent: header value
492 * Revision 1.18 2001/07/13 14:02:46 oes
493 * - Included fix to repair broken HTTP requests that
494 * don't contain a path, not even '/'.
495 * - Removed all #ifdef PCRS
496 * - content_type now always inspected and classified as
497 * text, gif or other.
498 * - formatting / comments
500 * Revision 1.17 2001/06/29 21:45:41 oes
501 * Indentation, CRLF->LF, Tab-> Space
503 * Revision 1.16 2001/06/29 13:32:42 oes
505 * - Adapted free_http_request
506 * - Removed logentry from cancelled commit
508 * Revision 1.15 2001/06/03 19:12:38 oes
509 * deleted const struct interceptors
511 * Revision 1.14 2001/06/01 18:49:17 jongfoster
512 * Replaced "list_share" with "list" - the tiny memory gain was not
513 * worth the extra complexity.
515 * Revision 1.13 2001/05/31 21:30:33 jongfoster
516 * Removed list code - it's now in list.[ch]
517 * Renamed "permission" to "action", and changed many features
518 * to use the actions file rather than the global config.
520 * Revision 1.12 2001/05/31 17:33:13 oes
524 * Revision 1.11 2001/05/29 20:11:19 joergs
525 * '/ * inside comment' warning removed.
527 * Revision 1.10 2001/05/29 09:50:24 jongfoster
528 * Unified blocklist/imagelist/permissionslist.
529 * File format is still under discussion, but the internal changes
532 * Also modified interceptor behaviour:
533 * - We now intercept all URLs beginning with one of the following
534 * prefixes (and *only* these prefixes):
536 * * http://ijbswa.sf.net/config/
537 * * http://ijbswa.sourceforge.net/config/
538 * - New interceptors "home page" - go to http://i.j.b/ to see it.
539 * - Internal changes so that intercepted and fast redirect pages
540 * are not replaced with an image.
541 * - Interceptors now have the option to send a binary page direct
542 * to the client. (i.e. ijb-send-banner uses this)
543 * - Implemented show-url-info interceptor. (Which is why I needed
544 * the above interceptors changes - a typical URL is
545 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
546 * The previous mechanism would not have intercepted that, and
547 * if it had been intercepted then it then it would have replaced
550 * Revision 1.9 2001/05/28 17:26:33 jongfoster
551 * Fixing segfault if last header was crunched.
552 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
553 * can use the cross-platform sprintf() instead.)
555 * Revision 1.8 2001/05/27 22:17:04 oes
557 * - re_process_buffer no longer writes the modified buffer
558 * to the client, which was very ugly. It now returns the
559 * buffer, which it is then written by chat.
561 * - content_length now adjusts the Content-Length: header
562 * for modified documents rather than crunch()ing it.
563 * (Length info in csp->content_length, which is 0 for
564 * unmodified documents)
566 * - For this to work, sed() is called twice when filtering.
568 * Revision 1.7 2001/05/27 13:19:06 oes
569 * Patched Joergs solution for the content-length in.
571 * Revision 1.6 2001/05/26 13:39:32 jongfoster
572 * Only crunches Content-Length header if applying RE filtering.
573 * Without this fix, Microsoft Windows Update wouldn't work.
575 * Revision 1.5 2001/05/26 00:28:36 jongfoster
576 * Automatic reloading of config file.
577 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
578 * Most of the global variables have been moved to a new
579 * struct configuration_spec, accessed through csp->config->globalname
580 * Most of the globals remaining are used by the Win32 GUI.
582 * Revision 1.4 2001/05/22 18:46:04 oes
584 * - Enabled filtering banners by size rather than URL
585 * by adding patterns that replace all standard banner
586 * sizes with the "Junkbuster" gif to the re_filterfile
588 * - Enabled filtering WebBugs by providing a pattern
589 * which kills all 1x1 images
591 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
592 * which is selected by the (nonstandard and therefore
593 * capital) letter 'U' in the option string.
594 * It causes the quantifiers to be ungreedy by default.
595 * Appending a ? turns back to greedy (!).
597 * - Added a new interceptor ijb-send-banner, which
598 * sends back the "Junkbuster" gif. Without imagelist or
599 * MSIE detection support, or if tinygif = 1, or the
600 * URL isn't recognized as an imageurl, a lame HTML
601 * explanation is sent instead.
603 * - Added new feature, which permits blocking remote
604 * script redirects and firing back a local redirect
606 * The feature is conditionally compiled, i.e. it
607 * can be disabled with --disable-fast-redirects,
608 * plus it must be activated by a "fast-redirects"
609 * line in the config file, has its own log level
610 * and of course wants to be displayed by show-proxy-args
611 * Note: Boy, all the #ifdefs in 1001 locations and
612 * all the fumbling with configure.in and acconfig.h
613 * were *way* more work than the feature itself :-(
615 * - Because a generic redirect template was needed for
616 * this, tinygif = 3 now uses the same.
618 * - Moved GIFs, and other static HTTP response templates
623 * - Removed some >400 CRs again (Jon, you really worked
626 * Revision 1.3 2001/05/20 01:21:20 jongfoster
627 * Version 2.9.4 checkin.
628 * - Merged popupfile and cookiefile, and added control over PCRS
629 * filtering, in new "permissionsfile".
630 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
631 * file error you now get a message box (in the Win32 GUI) rather
632 * than the program exiting with no explanation.
633 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
635 * - Removed tabs from "config"
636 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
637 * - Bumped up version number.
639 * Revision 1.2 2001/05/17 23:02:36 oes
640 * - Made referrer option accept 'L' as a substitute for '§'
642 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
643 * Initial import of version 2.9.3 source tree
646 *********************************************************************/
653 #include <sys/types.h>
663 * Convince GNU's libc to provide a strptime prototype.
666 #endif /*__GLIBC__ */
673 #if !defined(_WIN32) && !defined(__OS2__)
679 #ifdef FEATURE_PTHREAD
681 /* jcc.h is for mutex semapores only */
682 #endif /* def FEATURE_PTHREAD */
688 #include "jbsockets.h"
689 #include "miscutil.h"
692 #ifndef HAVE_STRPTIME
693 #include "strptime.h"
696 const char parsers_h_rcs[] = PARSERS_H_VERSION;
698 /* Fix a problem with Solaris. There should be no effect on other
700 * Solaris's isspace() is a macro which uses it's argument directly
701 * as an array index. Therefore we need to make sure that high-bit
702 * characters generate +ve values, and ideally we also want to make
703 * the argument match the declared parameter type of "int".
705 * Why did they write a character function that can't take a simple
706 * "char" argument? Doh!
708 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
709 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
712 const struct parsers client_patterns[] = {
713 { "referer:", 8, client_referrer },
714 { "user-agent:", 11, client_uagent },
715 { "ua-", 3, client_ua },
716 { "from:", 5, client_from },
717 { "cookie:", 7, client_send_cookie },
718 { "x-forwarded-for:", 16, client_x_forwarded },
719 { "Accept-Encoding:", 16, client_accept_encoding },
720 { "TE:", 3, client_te },
721 { "Host:", 5, client_host },
722 { "if-modified-since:", 18, client_if_modified_since },
723 { "Keep-Alive:", 11, crumble },
724 { "connection:", 11, connection },
725 { "proxy-connection:", 17, crumble },
726 { "max-forwards:", 13, client_max_forwards },
727 { "Accept-Language:", 16, client_accept_language },
728 { "if-none-match:", 14, client_if_none_match },
729 { "X-Filter:", 9, client_x_filter },
730 { "*", 0, crunch_client_header },
731 { "*", 0, filter_header },
735 const struct parsers server_patterns[] = {
736 { "HTTP", 4, server_http },
737 { "set-cookie:", 11, server_set_cookie },
738 { "connection:", 11, connection },
739 { "Content-Type:", 13, server_content_type },
740 { "Content-MD5:", 12, server_content_md5 },
741 { "Content-Encoding:", 17, server_content_encoding },
742 { "Transfer-Encoding:", 18, server_transfer_coding },
743 { "Keep-Alive:", 11, crumble },
744 { "content-disposition:", 20, server_content_disposition },
745 { "Last-Modified:", 14, server_last_modified },
746 { "*", 0, crunch_server_header },
747 { "*", 0, filter_header },
751 const struct parsers server_patterns_light[] = {
752 { "Content-Length:", 15, server_content_length },
753 { "Transfer-Encoding:", 18, server_transfer_coding },
755 { "Content-Encoding:", 17, server_content_encoding },
756 #endif /* def FEATURE_ZLIB */
760 const add_header_func_ptr add_client_headers[] = {
763 client_x_forwarded_adder,
765 /* Temporarily disabled: client_accept_encoding_adder, */
766 connection_close_adder,
771 const add_header_func_ptr add_server_headers[] = {
772 connection_close_adder,
776 /*********************************************************************
778 * Function : flush_socket
780 * Description : Write any pending "buffered" content.
783 * 1 : fd = file descriptor of the socket to read
784 * 2 : csp = Current client state (buffers, headers, etc...)
786 * Returns : On success, the number of bytes written are returned (zero
787 * indicates nothing was written). On error, -1 is returned,
788 * and errno is set appropriately. If count is zero and the
789 * file descriptor refers to a regular file, 0 will be
790 * returned without causing any other effect. For a special
791 * file, the results are not portable.
793 *********************************************************************/
794 int flush_socket(jb_socket fd, struct client_state *csp)
796 struct iob *iob = csp->iob;
797 int len = iob->eod - iob->cur;
804 if (write_socket(fd, iob->cur, (size_t)len))
808 iob->eod = iob->cur = iob->buf;
814 /*********************************************************************
816 * Function : add_to_iob
818 * Description : Add content to the buffered page, expanding the
819 * buffer if necessary.
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : buf = holds the content to be added to the page
824 * 3 : n = number of bytes to be added
826 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
827 * or buffer limit reached.
829 *********************************************************************/
830 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
832 struct iob *iob = csp->iob;
833 size_t used, offset, need, want;
836 if (n <= 0) return JB_ERR_OK;
838 used = (size_t)(iob->eod - iob->buf);
839 offset = (size_t)(iob->cur - iob->buf);
840 need = used + (size_t)n + 1;
843 * If the buffer can't hold the new data, extend it first.
844 * Use the next power of two if possible, else use the actual need.
846 if (need > csp->config->buffer_limit)
848 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
849 return JB_ERR_MEMORY;
852 if (need > iob->size)
854 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
856 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
860 else if (NULL != (p = (char *)realloc(iob->buf, need)))
866 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
867 return JB_ERR_MEMORY;
870 /* Update the iob pointers */
871 iob->cur = p + offset;
876 /* copy the new data into the iob buffer */
877 memcpy(iob->eod, buf, (size_t)n);
879 /* point to the end of the data */
882 /* null terminate == cheap insurance */
891 /*********************************************************************
893 * Function : decompress_iob
895 * Description : Decompress buffered page, expanding the
896 * buffer as necessary. csp->iob->cur
897 * should point to the the beginning of the
898 * compressed data block.
901 * 1 : csp = Current client state (buffers, headers, etc...)
903 * Returns : JB_ERR_OK on success,
904 * JB_ERR_MEMORY if out-of-memory limit reached, and
905 * JB_ERR_COMPRESS if error decompressing buffer.
907 *********************************************************************/
908 jb_err decompress_iob(struct client_state *csp)
910 char *buf; /* new, uncompressed buffer */
911 char *cur; /* Current iob position (to keep the original
912 * iob->cur unmodified if we return early) */
913 size_t bufsize; /* allocated size of the new buffer */
914 size_t old_size; /* Content size before decompression */
915 size_t skip_size; /* Number of bytes at the beginning of the iob
916 that we should NOT decompress. */
917 int status; /* return status of the inflate() call */
918 z_stream zstr; /* used by calls to zlib */
920 assert(csp->iob->cur - csp->iob->buf > 0);
921 assert(csp->iob->eod - csp->iob->cur > 0);
923 bufsize = csp->iob->size;
924 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
925 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
932 * This is to protect the parsing of gzipped data,
933 * but it should(?) be valid for deflated data also.
935 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
936 return JB_ERR_COMPRESS;
939 if (csp->content_type & CT_GZIP)
942 * Our task is slightly complicated by the facts that data
943 * compressed by gzip does not include a zlib header, and
944 * that there is no easily accessible interface in zlib to
945 * handle a gzip header. We strip off the gzip header by
946 * hand, and later inform zlib not to expect a header.
950 * Strip off the gzip header. Please see RFC 1952 for more
951 * explanation of the appropriate fields.
953 if ((*cur++ != (char)0x1f)
954 || (*cur++ != (char)0x8b)
955 || (*cur++ != Z_DEFLATED))
957 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
958 return JB_ERR_COMPRESS;
964 * XXX: These magic numbers should be replaced
965 * with macros to give a better idea what they do.
969 /* The gzip header has reserved bits set; bail out. */
970 log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
971 return JB_ERR_COMPRESS;
975 /* Skip extra fields if necessary. */
979 * Skip a given number of bytes, specified
980 * as a 16-bit little-endian value.
983 * XXX: This code used to be:
985 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
987 * which I had to change into:
989 * cur += *cur++ + (*cur++ << 8);
991 * at which point gcc43 finally noticed that the value
992 * of cur is undefined (it depends on which of the
993 * summands is evaluated first).
995 * I haven't come across a site where this
996 * code is actually executed yet, but I hope
1000 skip_bytes = *cur++;
1001 skip_bytes = *cur++ << 8;
1003 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1006 * The number of bytes to skip should be positive
1007 * and we'd like to stay in the buffer.
1009 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1011 log_error (LOG_LEVEL_ERROR,
1012 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1014 return JB_ERR_COMPRESS;
1016 log_error (LOG_LEVEL_INFO,
1017 "Skipping %d bytes for gzip compression. Does this sound right?",
1022 /* Skip the filename if necessary. */
1025 /* A null-terminated string is supposed to follow. */
1026 while (*cur++ && (cur < csp->iob->eod));
1030 /* Skip the comment if necessary. */
1033 /* A null-terminated string is supposed to follow. */
1034 while (*cur++ && (cur < csp->iob->eod));
1037 /* Skip the CRC if necessary. */
1043 if (cur >= csp->iob->eod)
1046 * If the current position pointer reached or passed
1047 * the buffer end, we were obviously tricked to skip
1050 log_error (LOG_LEVEL_ERROR,
1051 "Malformed gzip header detected. Aborting decompression.");
1052 return JB_ERR_COMPRESS;
1056 else if (csp->content_type & CT_DEFLATE)
1059 * XXX: The debug level should be lowered
1060 * before the next stable release.
1062 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1064 * In theory (that is, according to RFC 1950), deflate-compressed
1065 * data should begin with a two-byte zlib header and have an
1066 * adler32 checksum at the end. It seems that in practice only
1067 * the raw compressed data is sent. Note that this means that
1068 * we are not RFC 1950-compliant here, but the advantage is that
1069 * this actually works. :)
1071 * We add a dummy null byte to tell zlib where the data ends,
1072 * and later inform it not to expect a header.
1074 * Fortunately, add_to_iob() has thoughtfully null-terminated
1075 * the buffer; we can just increment the end pointer to include
1082 log_error (LOG_LEVEL_ERROR,
1083 "Unable to determine compression format for decompression");
1084 return JB_ERR_COMPRESS;
1087 /* Set up the fields required by zlib. */
1088 zstr.next_in = (Bytef *)cur;
1089 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1090 zstr.zalloc = Z_NULL;
1091 zstr.zfree = Z_NULL;
1092 zstr.opaque = Z_NULL;
1095 * Passing -MAX_WBITS to inflateInit2 tells the library
1096 * that there is no zlib header.
1098 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1100 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1101 return JB_ERR_COMPRESS;
1105 * Next, we allocate new storage for the inflated data.
1106 * We don't modify the existing iob yet, so in case there
1107 * is error in decompression we can recover gracefully.
1109 buf = zalloc (bufsize);
1112 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1113 return JB_ERR_MEMORY;
1116 assert(bufsize >= skip_size);
1117 memcpy(buf, csp->iob->buf, skip_size);
1118 zstr.avail_out = bufsize - skip_size;
1119 zstr.next_out = (Bytef *)buf + skip_size;
1121 /* Try to decompress the whole stream in one shot. */
1122 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1124 /* We need to allocate more memory for the output buffer. */
1126 char *tmpbuf; /* used for realloc'ing the buffer */
1127 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1130 * If zlib wants more data then there's a problem, because
1131 * the complete compressed file should have been buffered.
1133 if (0 == zstr.avail_in)
1135 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1136 return JB_ERR_COMPRESS;
1140 * If we tried the limit and still didn't have enough
1141 * memory, just give up.
1143 if (bufsize == csp->config->buffer_limit)
1145 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1146 return JB_ERR_MEMORY;
1149 /* Try doubling the buffer size each time. */
1152 /* Don't exceed the buffer limit. */
1153 if (bufsize > csp->config->buffer_limit)
1155 bufsize = csp->config->buffer_limit;
1158 /* Try to allocate the new buffer. */
1159 tmpbuf = realloc(buf, bufsize);
1162 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1164 return JB_ERR_MEMORY;
1168 char *oldnext_out = (char *)zstr.next_out;
1171 * Update the fields for inflate() to use the new
1172 * buffer, which may be in a location different from
1175 zstr.avail_out += bufsize - oldbufsize;
1176 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1179 * Compare with an uglier method of calculating these values
1180 * that doesn't require the extra oldbufsize variable.
1182 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1183 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1184 assert(zstr.avail_out > 0);
1190 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1192 log_error(LOG_LEVEL_ERROR,
1193 "Inconsistent stream state after decompression: %s", zstr.msg);
1195 * XXX: Intentionally no return.
1197 * According to zlib.h, Z_STREAM_ERROR is returned
1198 * "if the stream state was inconsistent".
1200 * I assume in this case inflate()'s status
1201 * would also be something different than Z_STREAM_END
1202 * so this check should be redundant, but lets see.
1206 if (status != Z_STREAM_END)
1208 /* We failed to decompress the stream. */
1209 log_error(LOG_LEVEL_ERROR,
1210 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1211 return JB_ERR_COMPRESS;
1215 * Finally, we can actually update the iob, since the
1216 * decompression was successful. First, free the old
1219 freez(csp->iob->buf);
1221 /* Now, update the iob to use the new buffer. */
1222 csp->iob->buf = buf;
1223 csp->iob->cur = csp->iob->buf + skip_size;
1224 csp->iob->eod = (char *)zstr.next_out;
1225 csp->iob->size = bufsize;
1228 * Make sure the new uncompressed iob obeys some minimal
1229 * consistency conditions.
1231 if ((csp->iob->buf < csp->iob->cur)
1232 && (csp->iob->cur <= csp->iob->eod)
1233 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1235 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1238 log_error(LOG_LEVEL_RE_FILTER,
1239 "Decompression successful. Old size: %d, new size: %d.",
1240 old_size, new_size);
1244 /* zlib thinks this is OK, so lets do the same. */
1245 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1250 /* It seems that zlib did something weird. */
1251 log_error(LOG_LEVEL_ERROR,
1252 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1253 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1254 csp->iob->eod, csp->iob->buf + csp->iob->size);
1255 return JB_ERR_COMPRESS;
1261 #endif /* defined(FEATURE_ZLIB) */
1264 /*********************************************************************
1266 * Function : get_header
1268 * Description : This (odd) routine will parse the csp->iob
1271 * 1 : csp = Current client state (buffers, headers, etc...)
1273 * Returns : Any one of the following:
1275 * 1) a pointer to a dynamically allocated string that contains a header line
1276 * 2) NULL indicating that the end of the header was reached
1277 * 3) "" indicating that the end of the iob was reached before finding
1278 * a complete header line.
1280 *********************************************************************/
1281 char *get_header(struct client_state *csp)
1287 if ((iob->cur == NULL)
1288 || ((p = strchr(iob->cur, '\n')) == NULL))
1290 return(""); /* couldn't find a complete header */
1295 ret = strdup(iob->cur);
1298 /* FIXME No way to handle error properly */
1299 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1304 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1306 /* is this a blank line (i.e. the end of the header) ? */
1318 /*********************************************************************
1320 * Function : get_header_value
1322 * Description : Get the value of a given header from a chained list
1323 * of header lines or return NULL if no such header is
1324 * present in the list.
1327 * 1 : header_list = pointer to list
1328 * 2 : header_name = string with name of header to look for.
1329 * Trailing colon required, capitalization
1332 * Returns : NULL if not found, else value of header
1334 *********************************************************************/
1335 char *get_header_value(const struct list *header_list, const char *header_name)
1337 struct list_entry *cur_entry;
1341 assert(header_list);
1342 assert(header_name);
1343 length = strlen(header_name);
1345 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1349 if (!strncmpic(cur_entry->str, header_name, length))
1352 * Found: return pointer to start of value
1354 ret = (char *) (cur_entry->str + length);
1355 while (*ret && ijb_isspace(*ret)) ret++;
1368 /*********************************************************************
1372 * Description : add, delete or modify lines in the HTTP header streams.
1373 * On entry, it receives a linked list of headers space
1374 * that was allocated dynamically (both the list nodes
1375 * and the header contents).
1377 * As a side effect it frees the space used by the original
1381 * 1 : pats = list of patterns to match against headers
1382 * 2 : more_headers = list of functions to add more
1383 * headers (client or server)
1384 * 3 : csp = Current client state (buffers, headers, etc...)
1386 * Returns : Single pointer to a fully formed header, or NULL
1387 * on out-of-memory error.
1389 *********************************************************************/
1390 char *sed(const struct parsers pats[],
1391 const add_header_func_ptr more_headers[],
1392 struct client_state *csp)
1394 struct list_entry *p;
1395 const struct parsers *v;
1396 const add_header_func_ptr *f;
1397 jb_err err = JB_ERR_OK;
1401 * If filtering is enabled, sed is run twice,
1402 * but most of the work needs to be done only once.
1404 first_run = (more_headers != NULL ) ? 1 : 0;
1406 if (first_run) /* Parse and print */
1408 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1409 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1411 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1413 /* Header crunch()ed in previous run? -> ignore */
1414 if (p->str == NULL) continue;
1416 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1418 /* Does the current parser handle this header? */
1419 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1421 err = v->parser(csp, (char **)&(p->str));
1425 /* place any additional headers on the csp->headers list */
1426 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1431 else /* Parse only */
1434 * The second run is only needed if the body was modified
1435 * and the content-lenght has changed.
1437 if (strncmpic(csp->http->cmd, "HEAD", 4))
1439 /*XXX: Code duplication */
1440 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1442 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1444 /* Header crunch()ed in previous run? -> ignore */
1445 if (p->str == NULL) continue;
1447 /* Does the current parser handle this header? */
1448 if (strncmpic(p->str, v->str, v->len) == 0)
1450 err = v->parser(csp, (char **)&(p->str));
1457 if (err != JB_ERR_OK)
1462 return list_to_text(csp->headers);
1466 /* here begins the family of parser functions that reformat header lines */
1468 /*********************************************************************
1470 * Function : filter_header
1472 * Description : Executes all text substitutions from all applying
1473 * +(server|client)-header-filter actions on the header.
1474 * Most of the code was copied from pcrs_filter_response,
1475 * including the rather short variable names
1478 * 1 : csp = Current client state (buffers, headers, etc...)
1479 * 2 : header = On input, pointer to header to modify.
1480 * On output, pointer to the modified header, or NULL
1481 * to remove the header. This function frees the
1482 * original string if necessary.
1484 * Returns : JB_ERR_OK on success and always succeeds
1486 *********************************************************************/
1487 jb_err filter_header(struct client_state *csp, char **header)
1491 size_t size = strlen(*header);
1493 char *newheader = NULL;
1496 struct file_list *fl;
1497 struct re_filterfile_spec *b;
1498 struct list_entry *filtername;
1500 int i, found_filters = 0;
1501 int wanted_filter_type;
1502 int multi_action_index;
1504 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1506 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1507 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1511 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1512 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1516 * Need to check the set of re_filterfiles...
1518 for (i = 0; i < MAX_AF_FILES; i++)
1531 if (0 == found_filters)
1533 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1537 for (i = 0; i < MAX_AF_FILES; i++)
1540 if ((NULL == fl) || (NULL == fl->f))
1543 * Either there are no filter files
1544 * left, or this filter file just
1545 * contains no valid filters.
1547 * Continue to be sure we don't miss
1548 * valid filter files that are chained
1549 * after empty or invalid ones.
1554 * For all applying +filter actions, look if a filter by that
1555 * name exists and if yes, execute its pcrs_joblist on the
1558 for (b = fl->f; b; b = b->next)
1560 if (b->type != wanted_filter_type)
1562 /* Skip other filter types */
1566 for (filtername = csp->action->multi[multi_action_index]->first;
1567 filtername ; filtername = filtername->next)
1569 if (strcmp(b->name, filtername->str) == 0)
1571 int current_hits = 0;
1573 if ( NULL == b->joblist )
1575 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1579 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1580 *header, size, b->name);
1582 /* Apply all jobs from the joblist */
1583 for (job = b->joblist; NULL != job; job = job->next)
1585 matches = pcrs_execute(job, *header, size, &newheader, &size);
1588 current_hits += matches;
1589 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1591 *header = newheader;
1593 else if ( 0 == matches )
1595 /* Filter doesn't change header */
1601 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1602 *header, b->name, pcrs_strerror(matches));
1603 if( newheader != NULL)
1605 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1610 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1611 hits += current_hits;
1618 * Additionally checking for hits is important because if
1619 * the continue hack is triggered, server headers can
1620 * arrive empty to separate multiple heads from each other.
1622 if ((0 == size) && hits)
1624 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1632 /*********************************************************************
1634 * Function : connection
1636 * Description : Makes sure that the value of the Connection: header
1637 * is "close" and signals connection_close_adder
1641 * 1 : csp = Current client state (buffers, headers, etc...)
1642 * 2 : header = On input, pointer to header to modify.
1643 * On output, pointer to the modified header, or NULL
1644 * to remove the header. This function frees the
1645 * original string if necessary.
1647 * Returns : JB_ERR_OK on success, or
1648 * JB_ERR_MEMORY on out-of-memory error.
1650 *********************************************************************/
1651 jb_err connection(struct client_state *csp, char **header)
1653 char *old_header = *header;
1655 /* Do we have a 'Connection: close' header? */
1656 if (strcmpic(*header, "Connection: close"))
1658 /* No, create one */
1659 *header = strdup("Connection: close");
1662 return JB_ERR_MEMORY;
1664 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1668 /* Signal connection_close_adder() to return early. */
1669 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1671 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1675 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1682 /*********************************************************************
1684 * Function : crumble
1686 * Description : This is called if a header matches a pattern to "crunch"
1689 * 1 : csp = Current client state (buffers, headers, etc...)
1690 * 2 : header = On input, pointer to header to modify.
1691 * On output, pointer to the modified header, or NULL
1692 * to remove the header. This function frees the
1693 * original string if necessary.
1695 * Returns : JB_ERR_OK on success, or
1696 * JB_ERR_MEMORY on out-of-memory error.
1698 *********************************************************************/
1699 jb_err crumble(struct client_state *csp, char **header)
1701 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1706 /*********************************************************************
1708 * Function : crunch_server_header
1710 * Description : Crunch server header if it matches a string supplied by the
1711 * user. Called from `sed'.
1714 * 1 : csp = Current client state (buffers, headers, etc...)
1715 * 2 : header = On input, pointer to header to modify.
1716 * On output, pointer to the modified header, or NULL
1717 * to remove the header. This function frees the
1718 * original string if necessary.
1720 * Returns : JB_ERR_OK on success and always succeeds
1722 *********************************************************************/
1723 jb_err crunch_server_header(struct client_state *csp, char **header)
1725 const char *crunch_pattern;
1727 /* Do we feel like crunching? */
1728 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1730 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1732 /* Is the current header the lucky one? */
1733 if (strstr(*header, crunch_pattern))
1735 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1744 /*********************************************************************
1746 * Function : server_content_type
1748 * Description : Set the content-type for filterable types (text/.*,
1749 * .*xml.*, javascript and image/gif) unless filtering has been
1750 * forbidden (CT_TABOO) while parsing earlier headers.
1751 * NOTE: Since text/plain is commonly used by web servers
1752 * for files whose correct type is unknown, we don't
1753 * set CT_TEXT for it.
1756 * 1 : csp = Current client state (buffers, headers, etc...)
1757 * 2 : header = On input, pointer to header to modify.
1758 * On output, pointer to the modified header, or NULL
1759 * to remove the header. This function frees the
1760 * original string if necessary.
1762 * Returns : JB_ERR_OK on success, or
1763 * JB_ERR_MEMORY on out-of-memory error.
1765 *********************************************************************/
1766 jb_err server_content_type(struct client_state *csp, char **header)
1768 /* Remove header if it isn't the first Content-Type header */
1769 if(csp->content_type && (csp->content_type != CT_TABOO))
1772 * Another, slightly slower, way to see if
1773 * we already parsed another Content-Type header.
1775 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1777 log_error(LOG_LEVEL_ERROR,
1778 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1785 if (!(csp->content_type & CT_TABOO))
1787 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1788 || strstr(*header, "xml")
1789 || strstr(*header, "application/x-javascript"))
1791 csp->content_type |= CT_TEXT;
1793 else if (strstr(*header, " image/gif"))
1795 csp->content_type |= CT_GIF;
1797 else if (strstr(*header, " image/jpeg"))
1799 csp->content_type |= CT_JPEG;
1803 csp->content_type = 0;
1807 * Are we enabling text mode by force?
1809 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1812 * Do we really have to?
1814 if (csp->content_type & CT_TEXT)
1816 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1820 csp->content_type |= CT_TEXT;
1821 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1825 * Are we messing with the content type?
1827 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1830 * Make sure the user doesn't accidently
1831 * change the content type of binary documents.
1833 if (csp->content_type & CT_TEXT)
1836 *header = strdup("Content-Type: ");
1837 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1841 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1842 return JB_ERR_MEMORY;
1844 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1848 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1849 "Enable force-text-mode if you know what you're doing.", *header);
1856 /*********************************************************************
1858 * Function : server_transfer_coding
1860 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1861 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1862 * - Remove header if body was chunked but has been
1863 * de-chunked for filtering.
1866 * 1 : csp = Current client state (buffers, headers, etc...)
1867 * 2 : header = On input, pointer to header to modify.
1868 * On output, pointer to the modified header, or NULL
1869 * to remove the header. This function frees the
1870 * original string if necessary.
1872 * Returns : JB_ERR_OK on success, or
1873 * JB_ERR_MEMORY on out-of-memory error.
1875 *********************************************************************/
1876 jb_err server_transfer_coding(struct client_state *csp, char **header)
1879 * Turn off pcrs and gif filtering if body compressed
1881 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1885 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1887 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1888 csp->http->cmd, *header);
1889 #endif /* def FEATURE_ZLIB */
1890 csp->content_type = CT_TABOO;
1894 * Raise flag if body chunked
1896 if (strstr(*header, "chunked"))
1898 csp->flags |= CSP_FLAG_CHUNKED;
1901 * If the body was modified, it has been de-chunked first
1902 * and the header must be removed.
1904 * FIXME: If there is more than one transfer encoding,
1905 * only the "chunked" part should be removed here.
1907 if (csp->flags & CSP_FLAG_MODIFIED)
1909 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1918 /*********************************************************************
1920 * Function : server_content_encoding
1922 * Description : This function is run twice for each request,
1923 * unless FEATURE_ZLIB and filtering are disabled.
1925 * The first run is used to check if the content
1926 * is compressed, if FEATURE_ZLIB is disabled
1927 * filtering is then disabled as well, if FEATURE_ZLIB
1928 * is enabled the content is marked for decompression.
1930 * The second run is used to remove the Content-Encoding
1931 * header if the decompression was successful.
1934 * 1 : csp = Current client state (buffers, headers, etc...)
1935 * 2 : header = On input, pointer to header to modify.
1936 * On output, pointer to the modified header, or NULL
1937 * to remove the header. This function frees the
1938 * original string if necessary.
1940 * Returns : JB_ERR_OK on success, or
1941 * JB_ERR_MEMORY on out-of-memory error.
1943 *********************************************************************/
1944 jb_err server_content_encoding(struct client_state *csp, char **header)
1947 if ((csp->flags & CSP_FLAG_MODIFIED)
1948 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1951 * We successfully decompressed the content,
1952 * and have to clean the header now, so the
1953 * client no longer expects compressed data..
1955 * XXX: There is a difference between cleaning
1956 * and removing it completely.
1958 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1961 else if (strstr(*header, "gzip"))
1963 /* Mark for gzip decompression */
1964 csp->content_type |= CT_GZIP;
1966 else if (strstr(*header, "deflate"))
1968 /* Mark for zlib decompression */
1969 csp->content_type |= CT_DEFLATE;
1971 else if (strstr(*header, "compress"))
1974 * We can't decompress this; therefore we can't filter
1977 csp->content_type |= CT_TABOO;
1979 #else /* !defined(FEATURE_ZLIB) */
1980 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1983 * Body is compressed, turn off pcrs and gif filtering.
1985 csp->content_type |= CT_TABOO;
1988 * Log a warning if the user expects the content to be filtered.
1990 if ((csp->rlist != NULL) &&
1991 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
1993 log_error(LOG_LEVEL_INFO,
1994 "Compressed content detected, content filtering disabled. "
1995 "Consider recompiling Privoxy with zlib support or "
1996 "enable the prevent-compression action.");
1999 #endif /* defined(FEATURE_ZLIB) */
2006 /*********************************************************************
2008 * Function : server_content_length
2010 * Description : Adjust Content-Length header if we modified
2014 * 1 : csp = Current client state (buffers, headers, etc...)
2015 * 2 : header = On input, pointer to header to modify.
2016 * On output, pointer to the modified header, or NULL
2017 * to remove the header. This function frees the
2018 * original string if necessary.
2020 * Returns : JB_ERR_OK on success, or
2021 * JB_ERR_MEMORY on out-of-memory error.
2023 *********************************************************************/
2024 jb_err server_content_length(struct client_state *csp, char **header)
2026 const size_t max_header_length = 80;
2028 /* Regenerate header if the content was modified. */
2029 if (csp->flags & CSP_FLAG_MODIFIED)
2032 *header = (char *) zalloc(max_header_length);
2033 if (*header == NULL)
2035 return JB_ERR_MEMORY;
2038 snprintf(*header, max_header_length, "Content-Length: %d",
2039 (int)csp->content_length);
2040 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2041 (int)csp->content_length);
2048 /*********************************************************************
2050 * Function : server_content_md5
2052 * Description : Crumble any Content-MD5 headers if the document was
2053 * modified. FIXME: Should we re-compute instead?
2056 * 1 : csp = Current client state (buffers, headers, etc...)
2057 * 2 : header = On input, pointer to header to modify.
2058 * On output, pointer to the modified header, or NULL
2059 * to remove the header. This function frees the
2060 * original string if necessary.
2062 * Returns : JB_ERR_OK on success, or
2063 * JB_ERR_MEMORY on out-of-memory error.
2065 *********************************************************************/
2066 jb_err server_content_md5(struct client_state *csp, char **header)
2068 if (csp->flags & CSP_FLAG_MODIFIED)
2070 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2077 /*********************************************************************
2079 * Function : server_content_disposition
2081 * Description : If enabled, blocks or modifies the "content-disposition" header.
2082 * Called from `sed'.
2085 * 1 : csp = Current client state (buffers, headers, etc...)
2086 * 2 : header = On input, pointer to header to modify.
2087 * On output, pointer to the modified header, or NULL
2088 * to remove the header. This function frees the
2089 * original string if necessary.
2091 * Returns : JB_ERR_OK on success, or
2092 * JB_ERR_MEMORY on out-of-memory error.
2094 *********************************************************************/
2095 jb_err server_content_disposition(struct client_state *csp, char **header)
2100 * Are we messing with the content-disposition header?
2102 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2108 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2110 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2113 * Blocking content-disposition header
2115 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2122 * Replacing content-disposition header
2125 *header = strdup("content-disposition: ");
2126 string_append(header, newval);
2128 if (*header == NULL)
2130 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2134 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2137 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2140 /*********************************************************************
2142 * Function : server_last_modified
2144 * Description : Changes Last-Modified header to the actual date
2145 * to help hide-if-modified-since.
2146 * Called from `sed'.
2149 * 1 : csp = Current client state (buffers, headers, etc...)
2150 * 2 : header = On input, pointer to header to modify.
2151 * On output, pointer to the modified header, or NULL
2152 * to remove the header. This function frees the
2153 * original string if necessary.
2155 * Returns : JB_ERR_OK on success, or
2156 * JB_ERR_MEMORY on out-of-memory error.
2158 *********************************************************************/
2159 jb_err server_last_modified(struct client_state *csp, char **header)
2162 char buf[BUFFER_SIZE];
2165 #ifdef HAVE_GMTIME_R
2168 struct tm *timeptr = NULL;
2169 time_t now, last_modified;
2171 long int days, hours, minutes, seconds;
2174 * Are we messing with the Last-Modified header?
2176 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2182 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2184 if (0 == strcmpic(newval, "block") )
2187 * Blocking Last-Modified header. Useless but why not.
2189 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2193 else if (0 == strcmpic(newval, "reset-to-request-time"))
2196 * Setting Last-Modified Header to now.
2198 get_http_time(0, buf);
2200 *header = strdup("Last-Modified: ");
2201 string_append(header, buf);
2203 if (*header == NULL)
2205 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2209 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2212 else if (0 == strcmpic(newval, "randomize"))
2214 const char *header_time = *header + sizeof("Last-Modified:");
2216 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2218 #ifdef HAVE_GMTIME_R
2219 timeptr = gmtime_r(&now, &gmt);
2220 #elif FEATURE_PTHREAD
2221 pthread_mutex_lock(&gmtime_mutex);
2222 timeptr = gmtime(&now);
2223 pthread_mutex_unlock(&gmtime_mutex);
2225 timeptr = gmtime(&now);
2227 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2229 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2234 rtime = (long int)difftime(now, last_modified);
2237 rtime = pick_from_range(rtime);
2238 last_modified += rtime;
2239 #ifdef HAVE_GMTIME_R
2240 timeptr = gmtime_r(&last_modified, &gmt);
2241 #elif FEATURE_PTHREAD
2242 pthread_mutex_lock(&gmtime_mutex);
2243 timeptr = gmtime(&last_modified);
2244 pthread_mutex_unlock(&gmtime_mutex);
2246 timeptr = gmtime(&last_modified);
2248 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2250 *header = strdup("Last-Modified: ");
2251 string_append(header, newheader);
2253 if (*header == NULL)
2255 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2256 return JB_ERR_MEMORY;
2259 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2261 days = rtime / (3600 * 24);
2262 hours = rtime / 3600 % 24;
2263 minutes = rtime / 60 % 60;
2264 seconds = rtime % 60;
2266 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2267 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2268 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2273 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2282 /*********************************************************************
2284 * Function : client_accept_encoding
2286 * Description : Rewrite the client's Accept-Encoding header so that
2287 * if doesn't allow compression, if the action applies.
2288 * Note: For HTTP/1.0 the absence of the header is enough.
2291 * 1 : csp = Current client state (buffers, headers, etc...)
2292 * 2 : header = On input, pointer to header to modify.
2293 * On output, pointer to the modified header, or NULL
2294 * to remove the header. This function frees the
2295 * original string if necessary.
2297 * Returns : JB_ERR_OK on success, or
2298 * JB_ERR_MEMORY on out-of-memory error.
2300 *********************************************************************/
2301 jb_err client_accept_encoding(struct client_state *csp, char **header)
2303 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2305 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2309 /* Temporarily disable the correct behaviour to
2310 * work around a PHP bug.
2312 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2314 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2315 * if (*header == NULL)
2317 * return JB_ERR_MEMORY;
2328 /*********************************************************************
2330 * Function : client_te
2332 * Description : Rewrite the client's TE header so that
2333 * if doesn't allow compression, if the action applies.
2336 * 1 : csp = Current client state (buffers, headers, etc...)
2337 * 2 : header = On input, pointer to header to modify.
2338 * On output, pointer to the modified header, or NULL
2339 * to remove the header. This function frees the
2340 * original string if necessary.
2342 * Returns : JB_ERR_OK on success, or
2343 * JB_ERR_MEMORY on out-of-memory error.
2345 *********************************************************************/
2346 jb_err client_te(struct client_state *csp, char **header)
2348 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2351 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2357 /*********************************************************************
2359 * Function : client_referrer
2361 * Description : Handle the "referer" config setting properly.
2362 * Called from `sed'.
2365 * 1 : csp = Current client state (buffers, headers, etc...)
2366 * 2 : header = On input, pointer to header to modify.
2367 * On output, pointer to the modified header, or NULL
2368 * to remove the header. This function frees the
2369 * original string if necessary.
2371 * Returns : JB_ERR_OK on success, or
2372 * JB_ERR_MEMORY on out-of-memory error.
2374 *********************************************************************/
2375 jb_err client_referrer(struct client_state *csp, char **header)
2382 #ifdef FEATURE_FORCE_LOAD
2383 /* Since the referrer can include the prefix even
2384 * if the request itself is non-forced, we must
2385 * clean it unconditionally
2387 strclean(*header, FORCE_PREFIX);
2388 #endif /* def FEATURE_FORCE_LOAD */
2391 * Are we sending referer?
2393 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2398 newval = csp->action->string[ACTION_STRING_REFERER];
2400 if ((0 != strcmpic(newval, "conditional-block")))
2404 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2409 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2412 else if (0 == strcmpic(newval, "conditional-block"))
2415 * Block referer if host has changed.
2418 if (NULL == (host = strdup(csp->http->hostport)))
2421 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2422 return JB_ERR_MEMORY;
2424 if (NULL == (referer = strdup(*header)))
2428 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2429 return JB_ERR_MEMORY;
2431 hostlenght = strlen(host);
2432 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2434 /*Shorten referer to make sure the referer is blocked
2435 *if www.example.org/www.example.com-shall-see-the-referer/
2436 *links to www.example.com/
2438 referer[hostlenght+17] = '\0';
2440 if ( 0 == strstr(referer, host)) /*Host has changed*/
2442 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2447 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2453 else if (0 != strcmpic(newval, "forge"))
2456 * We have a specific (fixed) referer we want to send.
2458 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2460 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2462 *header = strdup("Referer: ");
2463 string_append(header, newval);
2464 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2466 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2471 * Forge a referer as http://[hostname:port of REQUEST]/
2472 * to fool stupid checks for in-site links
2475 *header = strdup("Referer: http://");
2476 string_append(header, csp->http->hostport);
2477 string_append(header, "/");
2478 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2480 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2484 /*********************************************************************
2486 * Function : client_accept_language
2488 * Description : Handle the "Accept-Language" config setting properly.
2489 * Called from `sed'.
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2493 * 2 : header = On input, pointer to header to modify.
2494 * On output, pointer to the modified header, or NULL
2495 * to remove the header. This function frees the
2496 * original string if necessary.
2498 * Returns : JB_ERR_OK on success, or
2499 * JB_ERR_MEMORY on out-of-memory error.
2501 *********************************************************************/
2502 jb_err client_accept_language(struct client_state *csp, char **header)
2507 * Are we messing with the Accept-Language?
2509 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2511 /*I don't think so*/
2515 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2517 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2520 * Blocking Accept-Language header
2522 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2529 * Replacing Accept-Language header
2532 *header = strdup("Accept-Language: ");
2533 string_append(header, newval);
2535 if (*header == NULL)
2537 log_error(LOG_LEVEL_ERROR,
2538 "Insufficent memory. Accept-Language header crunched without replacement.");
2542 log_error(LOG_LEVEL_HEADER,
2543 "Accept-Language header crunched and replaced with: %s", *header);
2546 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2549 /*********************************************************************
2551 * Function : crunch_client_header
2553 * Description : Crunch client header if it matches a string supplied by the
2554 * user. Called from `sed'.
2557 * 1 : csp = Current client state (buffers, headers, etc...)
2558 * 2 : header = On input, pointer to header to modify.
2559 * On output, pointer to the modified header, or NULL
2560 * to remove the header. This function frees the
2561 * original string if necessary.
2563 * Returns : JB_ERR_OK on success and always succeeds
2565 *********************************************************************/
2566 jb_err crunch_client_header(struct client_state *csp, char **header)
2568 const char *crunch_pattern;
2570 /* Do we feel like crunching? */
2571 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2573 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2575 /* Is the current header the lucky one? */
2576 if (strstr(*header, crunch_pattern))
2578 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2586 /*********************************************************************
2588 * Function : client_uagent
2590 * Description : Handle the "user-agent" config setting properly
2591 * and remember its original value to enable browser
2592 * bug workarounds. Called from `sed'.
2595 * 1 : csp = Current client state (buffers, headers, etc...)
2596 * 2 : header = On input, pointer to header to modify.
2597 * On output, pointer to the modified header, or NULL
2598 * to remove the header. This function frees the
2599 * original string if necessary.
2601 * Returns : JB_ERR_OK on success, or
2602 * JB_ERR_MEMORY on out-of-memory error.
2604 *********************************************************************/
2605 jb_err client_uagent(struct client_state *csp, char **header)
2609 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2614 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2621 *header = strdup("User-Agent: ");
2622 string_append(header, newval);
2624 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2626 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2629 /*********************************************************************
2631 * Function : client_ua
2633 * Description : Handle "ua-" headers properly. Called from `sed'.
2636 * 1 : csp = Current client state (buffers, headers, etc...)
2637 * 2 : header = On input, pointer to header to modify.
2638 * On output, pointer to the modified header, or NULL
2639 * to remove the header. This function frees the
2640 * original string if necessary.
2642 * Returns : JB_ERR_OK on success, or
2643 * JB_ERR_MEMORY on out-of-memory error.
2645 *********************************************************************/
2646 jb_err client_ua(struct client_state *csp, char **header)
2648 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2650 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2658 /*********************************************************************
2660 * Function : client_from
2662 * Description : Handle the "from" config setting properly.
2663 * Called from `sed'.
2666 * 1 : csp = Current client state (buffers, headers, etc...)
2667 * 2 : header = On input, pointer to header to modify.
2668 * On output, pointer to the modified header, or NULL
2669 * to remove the header. This function frees the
2670 * original string if necessary.
2672 * Returns : JB_ERR_OK on success, or
2673 * JB_ERR_MEMORY on out-of-memory error.
2675 *********************************************************************/
2676 jb_err client_from(struct client_state *csp, char **header)
2680 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2687 newval = csp->action->string[ACTION_STRING_FROM];
2690 * Are we blocking the e-mail address?
2692 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2694 log_error(LOG_LEVEL_HEADER, "crunched From!");
2698 log_error(LOG_LEVEL_HEADER, " modified");
2700 *header = strdup("From: ");
2701 string_append(header, newval);
2703 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2707 /*********************************************************************
2709 * Function : client_send_cookie
2711 * Description : Crunches the "cookie" header if necessary.
2712 * Called from `sed'.
2714 * XXX: Stupid name, doesn't send squat.
2717 * 1 : csp = Current client state (buffers, headers, etc...)
2718 * 2 : header = On input, pointer to header to modify.
2719 * On output, pointer to the modified header, or NULL
2720 * to remove the header. This function frees the
2721 * original string if necessary.
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 jb_err client_send_cookie(struct client_state *csp, char **header)
2729 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2731 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2739 /*********************************************************************
2741 * Function : client_x_forwarded
2743 * Description : Handle the "x-forwarded-for" config setting properly,
2744 * also used in the add_client_headers list. Called from `sed'.
2747 * 1 : csp = Current client state (buffers, headers, etc...)
2748 * 2 : header = On input, pointer to header to modify.
2749 * On output, pointer to the modified header, or NULL
2750 * to remove the header. This function frees the
2751 * original string if necessary.
2753 * Returns : JB_ERR_OK on success, or
2754 * JB_ERR_MEMORY on out-of-memory error.
2756 *********************************************************************/
2757 jb_err client_x_forwarded(struct client_state *csp, char **header)
2759 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2761 /* Save it so we can re-add it later */
2762 freez(csp->x_forwarded);
2763 csp->x_forwarded = *header;
2766 * Always set *header = NULL, since this information
2767 * will be sent at the end of the header.
2774 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2781 /*********************************************************************
2783 * Function : client_max_forwards
2785 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2786 * from the value of the Max-Forwards header field.
2789 * 1 : csp = Current client state (buffers, headers, etc...)
2790 * 2 : header = On input, pointer to header to modify.
2791 * On output, pointer to the modified header, or NULL
2792 * to remove the header. This function frees the
2793 * original string if necessary.
2795 * Returns : JB_ERR_OK on success, or
2796 * JB_ERR_MEMORY on out-of-memory error.
2798 *********************************************************************/
2799 jb_err client_max_forwards(struct client_state *csp, char **header)
2803 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2804 (0 == strcmpic(csp->http->gpc, "options")))
2806 assert(*(*header+12) == ':');
2807 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2809 if (max_forwards > 0)
2811 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2812 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2813 csp->http->gpc, max_forwards);
2815 else if (max_forwards < 0)
2817 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2823 * Not supposed to be reached. direct_response() which
2824 * was already called earlier in chat() should have
2825 * intercepted the request.
2827 log_error(LOG_LEVEL_ERROR,
2828 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2829 assert(max_forwards != 0);
2834 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2843 /*********************************************************************
2845 * Function : client_host
2847 * Description : If the request URI did not contain host and
2848 * port information, parse and evaluate the Host
2851 * Also, kill ill-formed HOST: headers as sent by
2852 * Apple's iTunes software when used with a proxy.
2855 * 1 : csp = Current client state (buffers, headers, etc...)
2856 * 2 : header = On input, pointer to header to modify.
2857 * On output, pointer to the modified header, or NULL
2858 * to remove the header. This function frees the
2859 * original string if necessary.
2861 * Returns : JB_ERR_OK on success, or
2862 * JB_ERR_MEMORY on out-of-memory error.
2864 *********************************************************************/
2865 jb_err client_host(struct client_state *csp, char **header)
2870 * If the header field name is all upper-case, chances are that it's
2871 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2872 * not a problem -- they are regenerated later.
2874 if ((*header)[1] == 'O')
2876 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2881 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2882 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2885 if (NULL == (p = strdup((*header)+6)))
2887 return JB_ERR_MEMORY;
2890 if (NULL == (q = strdup(p)))
2893 return JB_ERR_MEMORY;
2896 freez(csp->http->hostport);
2897 csp->http->hostport = p;
2898 freez(csp->http->host);
2899 csp->http->host = q;
2900 q = strchr(csp->http->host, ':');
2903 /* Terminate hostname and evaluate port string */
2905 csp->http->port = atoi(q);
2909 csp->http->port = csp->http->ssl ? 443 : 80;
2912 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2913 csp->http->hostport, csp->http->host, csp->http->port);
2916 /* Signal client_host_adder() to return right away */
2917 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2922 /*********************************************************************
2924 * Function : client_if_modified_since
2926 * Description : Remove or modify the If-Modified-Since header.
2929 * 1 : csp = Current client state (buffers, headers, etc...)
2930 * 2 : header = On input, pointer to header to modify.
2931 * On output, pointer to the modified header, or NULL
2932 * to remove the header. This function frees the
2933 * original string if necessary.
2935 * Returns : JB_ERR_OK on success, or
2936 * JB_ERR_MEMORY on out-of-memory error.
2938 *********************************************************************/
2939 jb_err client_if_modified_since(struct client_state *csp, char **header)
2942 #ifdef HAVE_GMTIME_R
2945 struct tm *timeptr = NULL;
2949 long int hours, minutes, seconds;
2953 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2956 * The client got an error message because of a temporary problem,
2957 * the problem is gone and the client now tries to revalidate our
2958 * error message on the real server. The revalidation would always
2959 * end with the transmission of the whole document and there is
2960 * no need to expose the bogus If-Modified-Since header.
2962 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2965 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2967 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2969 if ((0 == strcmpic(newval, "block")))
2971 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2974 else /* add random value */
2976 const char *header_time = *header + sizeof("If-Modified-Since:");
2978 if (JB_ERR_OK != parse_header_time(header_time, &tm))
2980 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2985 rtime = strtol(newval, &endptr, 0);
2988 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2989 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2996 rtime = pick_from_range(rtime);
3000 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3003 tm += rtime * (negative ? -1 : 1);
3004 #ifdef HAVE_GMTIME_R
3005 timeptr = gmtime_r(&tm, &gmt);
3006 #elif FEATURE_PTHREAD
3007 pthread_mutex_lock(&gmtime_mutex);
3008 timeptr = gmtime(&tm);
3009 pthread_mutex_unlock(&gmtime_mutex);
3011 timeptr = gmtime(&tm);
3013 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3016 *header = strdup("If-Modified-Since: ");
3017 string_append(header, newheader);
3019 if (*header == NULL)
3021 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3022 return JB_ERR_MEMORY;
3025 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3027 hours = rtime / 3600;
3028 minutes = rtime / 60 % 60;
3029 seconds = rtime % 60;
3031 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3032 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3033 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3042 /*********************************************************************
3044 * Function : client_if_none_match
3046 * Description : Remove the If-None-Match header.
3049 * 1 : csp = Current client state (buffers, headers, etc...)
3050 * 2 : header = On input, pointer to header to modify.
3051 * On output, pointer to the modified header, or NULL
3052 * to remove the header. This function frees the
3053 * original string if necessary.
3055 * Returns : JB_ERR_OK on success, or
3056 * JB_ERR_MEMORY on out-of-memory error.
3058 *********************************************************************/
3059 jb_err client_if_none_match(struct client_state *csp, char **header)
3061 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3063 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3070 /*********************************************************************
3072 * Function : client_x_filter
3074 * Description : Disables filtering if the client set "X-Filter: No".
3075 * Called from `sed'.
3078 * 1 : csp = Current client state (buffers, headers, etc...)
3079 * 2 : header = On input, pointer to header to modify.
3080 * On output, pointer to the modified header, or NULL
3081 * to remove the header. This function frees the
3082 * original string if necessary.
3084 * Returns : JB_ERR_OK on success
3086 *********************************************************************/
3087 jb_err client_x_filter(struct client_state *csp, char **header)
3089 if ( 0 == strcmpic(*header, "X-Filter: No"))
3091 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3093 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3097 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3099 log_error(LOG_LEVEL_HEADER,
3100 "force-text-mode overruled the client's request to fetch without filtering!");
3104 csp->content_type = CT_TABOO;
3105 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3106 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3107 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3109 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3116 /* the following functions add headers directly to the header list */
3118 /*********************************************************************
3120 * Function : client_host_adder
3122 * Description : Adds the Host: header field if it is missing.
3123 * Called from `sed'.
3126 * 1 : csp = Current client state (buffers, headers, etc...)
3128 * Returns : JB_ERR_OK on success, or
3129 * JB_ERR_MEMORY on out-of-memory error.
3131 *********************************************************************/
3132 jb_err client_host_adder(struct client_state *csp)
3137 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3139 /* Header already set by the client, nothing to do. */
3143 if ( !csp->http->hostport || !*(csp->http->hostport))
3145 /* XXX: When does this happen and why is it OK? */
3146 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3151 * remove 'user:pass@' from 'proto://user:pass@host'
3153 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3159 p = csp->http->hostport;
3162 /* XXX: Just add it, we already made sure that it will be unique */
3163 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3164 err = enlist_unique_header(csp->headers, "Host", p);
3170 /*********************************************************************
3172 * Function : client_cookie_adder
3174 * Description : Used in the add_client_headers list. Called from `sed'.
3176 * XXX: Remove csp->cookie_list which is no longer used.
3179 * 1 : csp = Current client state (buffers, headers, etc...)
3181 * Returns : JB_ERR_OK on success, or
3182 * JB_ERR_MEMORY on out-of-memory error.
3184 *********************************************************************/
3185 jb_err client_cookie_adder(struct client_state *csp)
3187 struct list_entry *lst;
3189 struct list_entry *list1 = csp->cookie_list->first;
3190 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3191 int first_cookie = 1;
3194 if ((list1 == NULL) && (list2 == NULL))
3200 tmp = strdup("Cookie: ");
3202 for (lst = list1; lst ; lst = lst->next)
3210 string_append(&tmp, "; ");
3212 string_append(&tmp, lst->str);
3215 for (lst = list2; lst ; lst = lst->next)
3223 string_append(&tmp, "; ");
3225 string_join(&tmp, cookie_encode(lst->str));
3230 return JB_ERR_MEMORY;
3233 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3234 err = enlist(csp->headers, tmp);
3240 /*********************************************************************
3242 * Function : client_accept_encoding_adder
3244 * Description : Add an Accept-Encoding header to the client's request
3245 * that disables compression if the action applies, and
3246 * the header is not already there. Called from `sed'.
3247 * Note: For HTTP/1.0, the absence of the header is enough.
3250 * 1 : csp = Current client state (buffers, headers, etc...)
3252 * Returns : JB_ERR_OK on success, or
3253 * JB_ERR_MEMORY on out-of-memory error.
3255 *********************************************************************/
3256 jb_err client_accept_encoding_adder(struct client_state *csp)
3258 assert(0); /* Not in use */
3260 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3261 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3263 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3270 /*********************************************************************
3272 * Function : client_xtra_adder
3274 * Description : Used in the add_client_headers list. Called from `sed'.
3277 * 1 : csp = Current client state (buffers, headers, etc...)
3279 * Returns : JB_ERR_OK on success, or
3280 * JB_ERR_MEMORY on out-of-memory error.
3282 *********************************************************************/
3283 jb_err client_xtra_adder(struct client_state *csp)
3285 struct list_entry *lst;
3288 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3289 lst ; lst = lst->next)
3291 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3292 err = enlist(csp->headers, lst->str);
3304 /*********************************************************************
3306 * Function : client_x_forwarded_adder
3308 * Description : Used in the add_client_headers list. Called from `sed'.
3311 * 1 : csp = Current client state (buffers, headers, etc...)
3313 * Returns : JB_ERR_OK on success, or
3314 * JB_ERR_MEMORY on out-of-memory error.
3316 *********************************************************************/
3317 jb_err client_x_forwarded_adder(struct client_state *csp)
3322 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3327 if (csp->x_forwarded)
3329 p = strdup(csp->x_forwarded);
3330 string_append(&p, ", ");
3334 p = strdup("X-Forwarded-For: ");
3336 string_append(&p, csp->ip_addr_str);
3340 return JB_ERR_MEMORY;
3343 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3344 err = enlist(csp->headers, p);
3351 /*********************************************************************
3353 * Function : connection_close_adder
3355 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3356 * support. Adds a "Connection: close" header to csp->headers
3357 * unless the header was already present. Called from `sed'.
3359 * FIXME: This whole function shouldn't be neccessary!
3362 * 1 : csp = Current client state (buffers, headers, etc...)
3364 * Returns : JB_ERR_OK on success, or
3365 * JB_ERR_MEMORY on out-of-memory error.
3367 *********************************************************************/
3368 jb_err connection_close_adder(struct client_state *csp)
3370 const unsigned int flags = csp->flags;
3373 * Return right away if
3375 * - we're parsing server headers and the server header
3376 * "Connection: close" is already set, or if
3378 * - we're parsing client headers and the client header
3379 * "Connection: close" is already set.
3381 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3382 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3383 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3384 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3389 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3391 return enlist(csp->headers, "Connection: close");
3395 /*********************************************************************
3397 * Function : server_http
3399 * Description : - Save the HTTP Status into csp->http->status
3400 * - Set CT_TABOO to prevent filtering if the answer
3401 * is a partial range (HTTP status 206)
3402 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3406 * 1 : csp = Current client state (buffers, headers, etc...)
3407 * 2 : header = On input, pointer to header to modify.
3408 * On output, pointer to the modified header, or NULL
3409 * to remove the header. This function frees the
3410 * original string if necessary.
3412 * Returns : JB_ERR_OK on success, or
3413 * JB_ERR_MEMORY on out-of-memory error.
3415 *********************************************************************/
3416 jb_err server_http(struct client_state *csp, char **header)
3418 /* Signal that were now parsing server headers. */
3419 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
3421 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3422 if (csp->http->status == 206)
3424 csp->content_type = CT_TABOO;
3427 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3430 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3437 /*********************************************************************
3439 * Function : server_set_cookie
3441 * Description : Handle the server "cookie" header properly.
3442 * Log cookie to the jar file. Then "crunch",
3443 * accept or rewrite it to a session cookie.
3444 * Called from `sed'.
3446 * TODO: Allow the user to specify a new expiration
3447 * time to cause the cookie to expire even before the
3448 * browser is closed.
3451 * 1 : csp = Current client state (buffers, headers, etc...)
3452 * 2 : header = On input, pointer to header to modify.
3453 * On output, pointer to the modified header, or NULL
3454 * to remove the header. This function frees the
3455 * original string if necessary.
3457 * Returns : JB_ERR_OK on success, or
3458 * JB_ERR_MEMORY on out-of-memory error.
3460 *********************************************************************/
3461 jb_err server_set_cookie(struct client_state *csp, char **header)
3468 #ifdef FEATURE_COOKIE_JAR
3469 if (csp->config->jar)
3472 * Write timestamp into outbuf.
3474 * Complex because not all OSs have tm_gmtoff or
3475 * the %z field in strftime()
3477 char tempbuf[ BUFFER_SIZE ];
3479 #ifdef HAVE_LOCALTIME_R
3480 tm_now = *localtime_r(&now, &tm_now);
3481 #elif FEATURE_PTHREAD
3482 pthread_mutex_lock(&localtime_mutex);
3483 tm_now = *localtime (&now);
3484 pthread_mutex_unlock(&localtime_mutex);
3486 tm_now = *localtime (&now);
3488 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3490 /* strlen("set-cookie: ") = 12 */
3491 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3493 #endif /* def FEATURE_COOKIE_JAR */
3495 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3497 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3500 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3502 /* Flag whether or not to log a message */
3505 /* A variable to store the tag we're working on */
3508 /* Skip "Set-Cookie:" (11 characters) in header */
3509 cur_tag = *header + 11;
3511 /* skip whitespace between "Set-Cookie:" and value */
3512 while (*cur_tag && ijb_isspace(*cur_tag))
3517 /* Loop through each tag in the cookie */
3521 char *next_tag = strchr(cur_tag, ';');
3522 if (next_tag != NULL)
3524 /* Skip the ';' character itself */
3527 /* skip whitespace ";" and start of tag */
3528 while (*next_tag && ijb_isspace(*next_tag))
3535 /* "Next tag" is the end of the string */
3536 next_tag = cur_tag + strlen(cur_tag);
3540 * Check the expiration date to see
3541 * if the cookie is still valid, if yes,
3542 * rewrite it to a session cookie.
3544 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3546 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3548 /* Did we detect the date properly? */
3549 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3552 * Nope, treat it as if it was still valid.
3554 * XXX: Should we remove the whole cookie instead?
3556 log_error(LOG_LEVEL_ERROR,
3557 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3558 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3564 * Yes. Check if the cookie is still valid.
3566 * If the cookie is already expired it's probably
3567 * a delete cookie and even if it isn't, the browser
3568 * will discard it anyway.
3572 * XXX: timegm() isn't available on some AmigaOS
3573 * versions and our replacement doesn't work.
3575 * Our options are to either:
3577 * - disable session-cookies-only completely if timegm
3580 * - to simply remove all expired tags, like it has
3581 * been done until Privoxy 3.0.6 and to live with
3582 * the consequence that it can cause login/logout
3583 * problems on servers that don't validate their
3584 * input properly, or
3586 * - to replace it with mktime in which
3587 * case there is a slight chance of valid cookies
3588 * passing as already expired.
3590 * This is the way it's currently done and it's not
3591 * as bad as it sounds. If the missing GMT offset is
3592 * enough to change the result of the expiration check
3593 * the cookie will be only valid for a few hours
3594 * anyway, which in many cases will be shorter
3595 * than a browser session.
3597 if (cookie_time - now < 0)
3599 log_error(LOG_LEVEL_HEADER,
3600 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3601 /* Just in case some clown sets more then one expiration date */
3607 * Still valid, delete expiration date by copying
3608 * the rest of the string over it.
3610 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3611 * since the behaviour of strcpy is undefined for overlapping
3614 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3616 /* That changed the header, need to issue a log message */
3620 * Note that the next tag has now been moved to *cur_tag,
3621 * so we do not need to update the cur_tag pointer.
3629 /* Move on to next cookie tag */
3636 assert(NULL != *header);
3637 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3646 #ifdef FEATURE_FORCE_LOAD
3647 /*********************************************************************
3649 * Function : strclean
3651 * Description : In-Situ-Eliminate all occurances of substring in
3655 * 1 : string = string to clean
3656 * 2 : substring = substring to eliminate
3658 * Returns : Number of eliminations
3660 *********************************************************************/
3661 int strclean(const char *string, const char *substring)
3667 len = strlen(substring);
3669 while((pos = strstr(string, substring)) != NULL)
3676 while (*p++ != '\0');
3683 #endif /* def FEATURE_FORCE_LOAD */
3685 /*********************************************************************
3687 * Function : parse_header_time
3689 * Description : Parses time formats used in HTTP header strings
3690 * to get the numerical respresentation.
3693 * 1 : header_time = HTTP header time as string.
3694 * 2 : result = storage for header_time in seconds
3696 * Returns : JB_ERR_OK if the time format was recognized, or
3697 * JB_ERR_PARSE otherwise.
3699 *********************************************************************/
3700 jb_err parse_header_time(const char *header_time, time_t *result)
3705 * Zero out gmt to prevent time zone offsets.
3707 * While this is only necessary on some platforms
3708 * (mingw32 for example), I don't know how to
3709 * detect these automatically and doing it everywhere
3712 memset(&gmt, 0, sizeof(gmt));
3714 /* Tue, 02 Jun 2037 20:00:00 */
3715 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3716 /* Tue, 02-Jun-2037 20:00:00 */
3717 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3718 /* Tue, 02-Jun-37 20:00:00 */
3719 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3720 /* Tuesday, 02-Jun-2037 20:00:00 */
3721 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3722 /* Tuesday Jun 02 20:00:00 2037 */
3723 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3725 return JB_ERR_PARSE;
3728 *result = timegm(&gmt);
3734 /*********************************************************************
3736 * Function : get_destination_from_headers
3738 * Description : Parse the "Host:" header to get the request's destination.
3739 * Only needed if the client's request was forcefully
3740 * redirected into Privoxy.
3742 * Code mainly copied from client_host() which is currently
3743 * run too late for this purpose.
3746 * 1 : headers = List of headers (one of them hopefully being
3747 * the "Host:" header)
3748 * 2 : http = storage for the result (host, port and hostport).
3750 * Returns : JB_ERR_MEMORY in case of memory problems,
3751 * JB_ERR_PARSE if the host header couldn't be found,
3752 * JB_ERR_OK otherwise.
3754 *********************************************************************/
3755 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3761 host = get_header_value(headers, "Host:");
3765 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3766 return JB_ERR_PARSE;
3769 if (NULL == (p = strdup((host))))
3771 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3772 return JB_ERR_MEMORY;
3775 if (NULL == (q = strdup(p)))
3778 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3779 return JB_ERR_MEMORY;
3782 freez(http->hostport);
3786 q = strchr(http->host, ':');
3789 /* Terminate hostname and evaluate port string */
3791 http->port = atoi(q);
3795 http->port = http->ssl ? 443 : 80;
3798 /* Rebuild request URL */
3800 http->url = strdup(http->ssl ? "https://" : "http://");
3801 string_append(&http->url, http->hostport);
3802 string_append(&http->url, http->path);
3803 if (http->url == NULL)
3805 return JB_ERR_MEMORY;
3808 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",