1 const char parsers_rcs[] = "$Id: parsers.c,v 1.78 2006/12/26 17:19:20 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_server_header'
14 * `filter_client_header', `filter_header', `crunch_server_header',
15 * `server_content_encoding', `server_content_disposition',
16 * `server_last_modified', `client_accept_language',
17 * `crunch_client_header', `client_if_modified_since',
18 * `client_if_none_match', `get_destination_from_headers',
19 * `parse_header_time' and `server_set_cookie'.
21 * Copyright : Written by and Copyright (C) 2001-2006 the SourceForge
22 * Privoxy team. http://www.privoxy.org/
24 * Based on the Internet Junkbuster originally written
25 * by and Copyright (C) 1997 Anonymous Coders and
26 * Junkbusters Corporation. http://www.junkbusters.com
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
48 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
49 * Bringing back the "useless" localtime() call
50 * I removed in revision 1.67. On some platforms
51 * it's necessary to prevent time zone offsets.
53 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
54 * Rebuild request URL in get_destination_from_headers()
55 * to make sure redirect{pcrs command} works as expected
56 * for intercepted requests.
58 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
59 * Added get_destination_from_headers().
61 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
62 * Make pthread mutex locking more generic. Instead of
63 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
64 * and use mutex locking unless there is an _r function
65 * available. Better safe than sorry.
67 * Fixes "./configure --disable-pthread" and should result
68 * in less threading-related problems on pthread-using platforms,
69 * but it still doesn't fix BR#1122404.
71 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
72 * The special header "X-Filter: No" now disables
73 * header filtering as well.
75 * Revision 1.73 2006/09/23 13:26:38 roro
76 * Replace TABs by spaces in source code.
78 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
79 * Don't print a log message every time filter_headers is
80 * entered or left. It only creates noise without any real
83 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
84 * Fix +hide-if-modified-since{-n}.
86 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
87 * Have hide-if-modified-since interpret the random
88 * range value as minutes instead of hours. Allows
89 * more fine-grained configuration.
91 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
92 * Always have parse_header_time return a pointer
93 * that actual makes sense, even though we currently
94 * only need it to detect problems.
96 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
97 * Added config option enable-remote-http-toggle
98 * to specify if Privoxy should recognize special
99 * headers (currently only X-Filter) to change its
100 * behaviour. Disabled by default.
102 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
103 * After filtering de-chunked instances, remove
104 * "Transfer-Encoding" header entirely instead of changing
105 * it to "Transfer-Encoding: identity", which is invalid.
106 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
108 * Don't use localtime in parse_header_time. An empty time struct
109 * is good enough, it gets overwritten by strptime anyway.
111 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
112 * Use gmtime_r if available, fallback to gmtime with mutex
113 * protection for MacOSX and use vanilla gmtime for the rest.
115 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
116 * Changed client_referrer to use the right type (size_t) for
117 * hostlenght and to shorten the temporary referrer string with
118 * '\0' instead of adding a useless line break.
120 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
121 * - Back to timegm() using GnuPG's replacement if necessary.
122 * Using mktime() and localtime() could add a on hour offset if
123 * the randomize factor was big enough to lead to a summer/wintertime
126 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
128 * - Moved randomization code into pick_from_range().
130 * - Changed parse_header_time definition.
131 * time_t isn't guaranteed to be signed and
132 * if it isn't, -1 isn't available as error code.
133 * Changed some variable types in client_if_modified_since()
134 * because of the same reason.
136 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
137 * OS/2 compilation compatibility fixups
139 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
140 * Changed include from strptime.c to strptime.h
142 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
143 * Split filter-headers{} into filter-client-headers{}
144 * and filter-server-headers{}.
145 * Added parse_header_time() to share some code.
146 * Replaced timegm() with mktime().
148 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
149 * Windows service integration
151 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
152 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
154 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
155 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
156 * with what was really the latest development (the v_3_0_branch branch)
158 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
159 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
161 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
162 * Add the ability to check jpeg images for invalid
163 * lengths of comment blocks. Defensive strategy
164 * against the exploit:
165 * Microsoft Security Bulletin MS04-028
166 * Buffer Overrun in JPEG Processing (GDI+) Could
167 * Allow Code Execution (833987)
168 * Enabled with +inspect-jpegs in actions files.
170 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
171 * Excluded text/plain objects from filtering. This fixes a
172 * couple of client-crashing, download corruption and
173 * Privoxy performance issues, whose root cause lies in
174 * web servers labelling content of unknown type as text/plain.
176 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
177 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
179 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
180 * Completing the previous change
182 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
183 * Added temporary workaround for bug in PHP < 4.2.3
185 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
186 * 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.
188 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
189 * Fix typo: supressed -> suppressed
191 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
192 * Improved cookie logging
194 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
195 * Added basic support for OPTIONS and TRACE HTTP methods:
196 * - New parser function client_max_forwards which decrements
197 * the Max-Forwards HTTP header field of OPTIONS and TRACE
198 * requests by one before forwarding
199 * - New parser function client_host which extracts the host
200 * and port information from the HTTP header field if the
201 * request URI was not absolute
202 * - Don't crumble and re-add the Host: header, but only generate
203 * and append if missing
205 * Revision 1.56 2002/05/12 15:34:22 jongfoster
206 * Fixing typo in a comment
208 * Revision 1.55 2002/05/08 16:01:07 oes
209 * Optimized add_to_iob:
210 * - Use realloc instead of malloc(), memcpy(), free()
211 * - Expand to powers of two if possible, to get
212 * O(log n) reallocs instead of O(n).
213 * - Moved check for buffer limit here from chat
214 * - Report failure via returncode
216 * Revision 1.54 2002/04/02 15:03:16 oes
217 * Tiny code cosmetics
219 * Revision 1.53 2002/03/26 22:29:55 swa
220 * we have a new homepage!
222 * Revision 1.52 2002/03/24 13:25:43 swa
223 * name change related issues
225 * Revision 1.51 2002/03/13 00:27:05 jongfoster
228 * Revision 1.50 2002/03/12 01:45:35 oes
229 * More verbose logging
231 * Revision 1.49 2002/03/09 20:03:52 jongfoster
232 * - Making various functions return int rather than size_t.
233 * (Undoing a recent change). Since size_t is unsigned on
234 * Windows, functions like read_socket that return -1 on
235 * error cannot return a size_t.
237 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
238 * crashes, and also frequently caused JB to jump to 100%
239 * CPU and stay there. (Because it thought it had just
240 * read ((unsigned)-1) == 4Gb of data...)
242 * - The signature of write_socket has changed, it now simply
243 * returns success=0/failure=nonzero.
245 * - Trying to get rid of a few warnings --with-debug on
246 * Windows, I've introduced a new type "jb_socket". This is
247 * used for the socket file descriptors. On Windows, this
248 * is SOCKET (a typedef for unsigned). Everywhere else, it's
249 * an int. The error value can't be -1 any more, so it's
250 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
251 * Windows it maps to the #define INVALID_SOCKET.)
253 * - The signature of bind_port has changed.
255 * Revision 1.48 2002/03/07 03:46:53 oes
256 * Fixed compiler warnings etc
258 * Revision 1.47 2002/02/20 23:15:13 jongfoster
259 * Parsing functions now handle out-of-memory gracefully by returning
262 * Revision 1.46 2002/01/17 21:03:47 jongfoster
263 * Moving all our URL and URL pattern parsing code to urlmatch.c.
265 * Revision 1.45 2002/01/09 14:33:03 oes
266 * Added support for localtime_r.
268 * Revision 1.44 2001/12/14 01:22:54 steudten
269 * Remove 'user:pass@' from 'proto://user:pass@host' for the
270 * new added header 'Host: ..'. (See Req ID 491818)
272 * Revision 1.43 2001/11/23 00:26:38 jongfoster
273 * Fixing two really stupid errors in my previous commit
275 * Revision 1.42 2001/11/22 21:59:30 jongfoster
276 * Adding code to handle +no-cookies-keep
278 * Revision 1.41 2001/11/05 23:43:05 steudten
279 * Add time+date to log files.
281 * Revision 1.40 2001/10/26 20:13:09 jongfoster
282 * ctype.h is needed in Windows, too.
284 * Revision 1.39 2001/10/26 17:40:04 oes
285 * Introduced get_header_value()
286 * Removed http->user_agent, csp->referrer and csp->accept_types
287 * Removed client_accept()
289 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
290 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
291 * threads to call select() simultaneously. So, it's time to do a real, live,
292 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
293 * (native). Both versions will work, but using __OS2__ offers multi-threading.
295 * Revision 1.37 2001/10/23 21:36:02 jongfoster
296 * Documenting sed()'s error behaviou (doc change only)
298 * Revision 1.36 2001/10/13 12:51:51 joergs
299 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
300 * force-load), instead crumble Host: and add it (again) in client_host_adder
301 * (in case we get a HTTP/1.0 request without Host: header and forward it to
302 * a HTTP/1.1 server/proxy).
304 * Revision 1.35 2001/10/09 22:39:21 jongfoster
305 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
308 * Revision 1.34 2001/10/07 18:50:55 oes
309 * Added server_content_encoding, renamed server_transfer_encoding
311 * Revision 1.33 2001/10/07 18:04:49 oes
312 * Changed server_http11 to server_http and its pattern to "HTTP".
313 * Additional functionality: it now saves the HTTP status into
314 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
316 * Revision 1.32 2001/10/07 15:43:28 oes
317 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
318 * client_te and client_accept_encoding_adder, triggered by the new
319 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
320 * changed to allow only identity and chunked, and the TE header is
321 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
323 * parse_http_request no longer does anything than parsing. The rewriting
324 * of http->cmd and version mangling are gone. It now also recognizes
325 * the put and delete methods and saves the url in http->url. Removed
328 * renamed content_type and content_length to have the server_ prefix
330 * server_content_type now only works if csp->content_type != CT_TABOO
332 * added server_transfer_encoding, which
333 * - Sets CT_TABOO to prohibit filtering if encoding compresses
334 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
335 * - Change from "chunked" to "identity" if body was chunked
336 * but has been de-chunked for filtering.
338 * added server_content_md5 which crunches any Content-MD5 headers
339 * if the body was modified.
341 * made server_http11 conditional on +downgrade action
343 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
345 * Revision 1.31 2001/10/05 14:25:02 oes
346 * Crumble Keep-Alive from Server
348 * Revision 1.30 2001/09/29 12:56:03 joergs
349 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
351 * Revision 1.29 2001/09/24 21:09:24 jongfoster
352 * Fixing 2 memory leaks that Guy spotted, where the paramater to
353 * enlist() was not being free()d.
355 * Revision 1.28 2001/09/22 16:32:28 jongfoster
356 * Removing unused #includes.
358 * Revision 1.27 2001/09/20 15:45:25 steudten
360 * add casting from size_t to int for printf()
361 * remove local variable shadow s2
363 * Revision 1.26 2001/09/16 17:05:14 jongfoster
364 * Removing unused #include showarg.h
366 * Revision 1.25 2001/09/16 13:21:27 jongfoster
367 * Changes to use new list functions.
369 * Revision 1.24 2001/09/13 23:05:50 jongfoster
370 * Changing the string paramater to the header parsers a "const".
372 * Revision 1.23 2001/09/12 18:08:19 steudten
374 * In parse_http_request() header rewriting miss the host value, so
375 * from http://www.mydomain.com the result was just " / " not
376 * http://www.mydomain.com/ in case we forward.
378 * Revision 1.22 2001/09/10 10:58:53 oes
379 * Silenced compiler warnings
381 * Revision 1.21 2001/07/31 14:46:00 oes
382 * - Persistant connections now suppressed
383 * - sed() no longer appends empty header to csp->headers
385 * Revision 1.20 2001/07/30 22:08:36 jongfoster
386 * Tidying up #defines:
387 * - All feature #defines are now of the form FEATURE_xxx
388 * - Permanently turned off WIN_GUI_EDIT
389 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
391 * Revision 1.19 2001/07/25 17:21:54 oes
392 * client_uagent now saves copy of User-Agent: header value
394 * Revision 1.18 2001/07/13 14:02:46 oes
395 * - Included fix to repair broken HTTP requests that
396 * don't contain a path, not even '/'.
397 * - Removed all #ifdef PCRS
398 * - content_type now always inspected and classified as
399 * text, gif or other.
400 * - formatting / comments
402 * Revision 1.17 2001/06/29 21:45:41 oes
403 * Indentation, CRLF->LF, Tab-> Space
405 * Revision 1.16 2001/06/29 13:32:42 oes
407 * - Adapted free_http_request
408 * - Removed logentry from cancelled commit
410 * Revision 1.15 2001/06/03 19:12:38 oes
411 * deleted const struct interceptors
413 * Revision 1.14 2001/06/01 18:49:17 jongfoster
414 * Replaced "list_share" with "list" - the tiny memory gain was not
415 * worth the extra complexity.
417 * Revision 1.13 2001/05/31 21:30:33 jongfoster
418 * Removed list code - it's now in list.[ch]
419 * Renamed "permission" to "action", and changed many features
420 * to use the actions file rather than the global config.
422 * Revision 1.12 2001/05/31 17:33:13 oes
426 * Revision 1.11 2001/05/29 20:11:19 joergs
427 * '/ * inside comment' warning removed.
429 * Revision 1.10 2001/05/29 09:50:24 jongfoster
430 * Unified blocklist/imagelist/permissionslist.
431 * File format is still under discussion, but the internal changes
434 * Also modified interceptor behaviour:
435 * - We now intercept all URLs beginning with one of the following
436 * prefixes (and *only* these prefixes):
438 * * http://ijbswa.sf.net/config/
439 * * http://ijbswa.sourceforge.net/config/
440 * - New interceptors "home page" - go to http://i.j.b/ to see it.
441 * - Internal changes so that intercepted and fast redirect pages
442 * are not replaced with an image.
443 * - Interceptors now have the option to send a binary page direct
444 * to the client. (i.e. ijb-send-banner uses this)
445 * - Implemented show-url-info interceptor. (Which is why I needed
446 * the above interceptors changes - a typical URL is
447 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
448 * The previous mechanism would not have intercepted that, and
449 * if it had been intercepted then it then it would have replaced
452 * Revision 1.9 2001/05/28 17:26:33 jongfoster
453 * Fixing segfault if last header was crunched.
454 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
455 * can use the cross-platform sprintf() instead.)
457 * Revision 1.8 2001/05/27 22:17:04 oes
459 * - re_process_buffer no longer writes the modified buffer
460 * to the client, which was very ugly. It now returns the
461 * buffer, which it is then written by chat.
463 * - content_length now adjusts the Content-Length: header
464 * for modified documents rather than crunch()ing it.
465 * (Length info in csp->content_length, which is 0 for
466 * unmodified documents)
468 * - For this to work, sed() is called twice when filtering.
470 * Revision 1.7 2001/05/27 13:19:06 oes
471 * Patched Joergs solution for the content-length in.
473 * Revision 1.6 2001/05/26 13:39:32 jongfoster
474 * Only crunches Content-Length header if applying RE filtering.
475 * Without this fix, Microsoft Windows Update wouldn't work.
477 * Revision 1.5 2001/05/26 00:28:36 jongfoster
478 * Automatic reloading of config file.
479 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
480 * Most of the global variables have been moved to a new
481 * struct configuration_spec, accessed through csp->config->globalname
482 * Most of the globals remaining are used by the Win32 GUI.
484 * Revision 1.4 2001/05/22 18:46:04 oes
486 * - Enabled filtering banners by size rather than URL
487 * by adding patterns that replace all standard banner
488 * sizes with the "Junkbuster" gif to the re_filterfile
490 * - Enabled filtering WebBugs by providing a pattern
491 * which kills all 1x1 images
493 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
494 * which is selected by the (nonstandard and therefore
495 * capital) letter 'U' in the option string.
496 * It causes the quantifiers to be ungreedy by default.
497 * Appending a ? turns back to greedy (!).
499 * - Added a new interceptor ijb-send-banner, which
500 * sends back the "Junkbuster" gif. Without imagelist or
501 * MSIE detection support, or if tinygif = 1, or the
502 * URL isn't recognized as an imageurl, a lame HTML
503 * explanation is sent instead.
505 * - Added new feature, which permits blocking remote
506 * script redirects and firing back a local redirect
508 * The feature is conditionally compiled, i.e. it
509 * can be disabled with --disable-fast-redirects,
510 * plus it must be activated by a "fast-redirects"
511 * line in the config file, has its own log level
512 * and of course wants to be displayed by show-proxy-args
513 * Note: Boy, all the #ifdefs in 1001 locations and
514 * all the fumbling with configure.in and acconfig.h
515 * were *way* more work than the feature itself :-(
517 * - Because a generic redirect template was needed for
518 * this, tinygif = 3 now uses the same.
520 * - Moved GIFs, and other static HTTP response templates
525 * - Removed some >400 CRs again (Jon, you really worked
528 * Revision 1.3 2001/05/20 01:21:20 jongfoster
529 * Version 2.9.4 checkin.
530 * - Merged popupfile and cookiefile, and added control over PCRS
531 * filtering, in new "permissionsfile".
532 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
533 * file error you now get a message box (in the Win32 GUI) rather
534 * than the program exiting with no explanation.
535 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
537 * - Removed tabs from "config"
538 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
539 * - Bumped up version number.
541 * Revision 1.2 2001/05/17 23:02:36 oes
542 * - Made referrer option accept 'L' as a substitute for '§'
544 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
545 * Initial import of version 2.9.3 source tree
548 *********************************************************************/
555 #include <sys/types.h>
564 #if !defined(_WIN32) && !defined(__OS2__)
570 #ifdef FEATURE_PTHREAD
572 /* jcc.h is for mutex semapores only */
573 #endif /* def FEATURE_PTHREAD */
579 #include "jbsockets.h"
580 #include "miscutil.h"
583 #ifndef HAVE_STRPTIME
584 #include "strptime.h"
587 const char parsers_h_rcs[] = PARSERS_H_VERSION;
589 /* Fix a problem with Solaris. There should be no effect on other
591 * Solaris's isspace() is a macro which uses it's argument directly
592 * as an array index. Therefore we need to make sure that high-bit
593 * characters generate +ve values, and ideally we also want to make
594 * the argument match the declared parameter type of "int".
596 * Why did they write a character function that can't take a simple
597 * "char" argument? Doh!
599 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
600 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
603 const struct parsers client_patterns[] = {
604 { "referer:", 8, client_referrer },
605 { "user-agent:", 11, client_uagent },
606 { "ua-", 3, client_ua },
607 { "from:", 5, client_from },
608 { "cookie:", 7, client_send_cookie },
609 { "x-forwarded-for:", 16, client_x_forwarded },
610 { "Accept-Encoding:", 16, client_accept_encoding },
611 { "TE:", 3, client_te },
612 { "Host:", 5, client_host },
613 { "if-modified-since:", 18, client_if_modified_since },
614 { "Keep-Alive:", 11, crumble },
615 { "connection:", 11, crumble },
616 { "proxy-connection:", 17, crumble },
617 { "max-forwards:", 13, client_max_forwards },
618 { "Accept-Language:", 16, client_accept_language },
619 { "if-none-match:", 14, client_if_none_match },
620 { "X-Filter:", 9, client_x_filter },
621 { "*", 0, crunch_client_header },
622 { "*", 0, filter_client_header },
626 const struct parsers server_patterns[] = {
627 { "HTTP", 4, server_http },
628 { "set-cookie:", 11, server_set_cookie },
629 { "connection:", 11, crumble },
630 { "Content-Type:", 13, server_content_type },
631 { "Content-Length:", 15, server_content_length },
632 { "Content-MD5:", 12, server_content_md5 },
633 { "Content-Encoding:", 17, server_content_encoding },
634 { "Transfer-Encoding:", 18, server_transfer_coding },
635 { "Keep-Alive:", 11, crumble },
636 { "content-disposition:", 20, server_content_disposition },
637 { "Last-Modified:", 14, server_last_modified },
638 { "*", 0, crunch_server_header },
639 { "*", 0, filter_server_header },
643 const struct parsers server_patterns_light[] = {
644 { "Content-Length:", 15, server_content_length },
645 { "Transfer-Encoding:", 18, server_transfer_coding },
649 const add_header_func_ptr add_client_headers[] = {
652 client_x_forwarded_adder,
654 /* Temporarily disabled: client_accept_encoding_adder, */
655 connection_close_adder,
660 const add_header_func_ptr add_server_headers[] = {
661 connection_close_adder,
665 /*********************************************************************
667 * Function : flush_socket
669 * Description : Write any pending "buffered" content.
672 * 1 : fd = file descriptor of the socket to read
673 * 2 : csp = Current client state (buffers, headers, etc...)
675 * Returns : On success, the number of bytes written are returned (zero
676 * indicates nothing was written). On error, -1 is returned,
677 * and errno is set appropriately. If count is zero and the
678 * file descriptor refers to a regular file, 0 will be
679 * returned without causing any other effect. For a special
680 * file, the results are not portable.
682 *********************************************************************/
683 int flush_socket(jb_socket fd, struct client_state *csp)
685 struct iob *iob = csp->iob;
686 int len = iob->eod - iob->cur;
693 if (write_socket(fd, iob->cur, (size_t)len))
697 iob->eod = iob->cur = iob->buf;
703 /*********************************************************************
705 * Function : add_to_iob
707 * Description : Add content to the buffered page, expanding the
708 * buffer if necessary.
711 * 1 : csp = Current client state (buffers, headers, etc...)
712 * 2 : buf = holds the content to be added to the page
713 * 3 : n = number of bytes to be added
715 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
716 * or buffer limit reached.
718 *********************************************************************/
719 jb_err add_to_iob(struct client_state *csp, char *buf, size_t n)
721 struct iob *iob = csp->iob;
722 size_t used, offset, need, want;
725 if (n <= 0) return JB_ERR_OK;
727 used = (size_t)(iob->eod - iob->buf);
728 offset = (size_t)(iob->cur - iob->buf);
732 * If the buffer can't hold the new data, extend it first.
733 * Use the next power of two if possible, else use the actual need.
735 if (need > csp->config->buffer_limit)
737 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
738 return JB_ERR_MEMORY;
741 if (need > iob->size)
743 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
745 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
749 else if (NULL != (p = (char *)realloc(iob->buf, need)))
755 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
756 return JB_ERR_MEMORY;
759 /* Update the iob pointers */
760 iob->cur = p + offset;
765 /* copy the new data into the iob buffer */
766 memcpy(iob->eod, buf, (size_t)n);
768 /* point to the end of the data */
771 /* null terminate == cheap insurance */
779 /*********************************************************************
781 * Function : get_header
783 * Description : This (odd) routine will parse the csp->iob
786 * 1 : csp = Current client state (buffers, headers, etc...)
788 * Returns : Any one of the following:
790 * 1) a pointer to a dynamically allocated string that contains a header line
791 * 2) NULL indicating that the end of the header was reached
792 * 3) "" indicating that the end of the iob was reached before finding
793 * a complete header line.
795 *********************************************************************/
796 char *get_header(struct client_state *csp)
802 if ((iob->cur == NULL)
803 || ((p = strchr(iob->cur, '\n')) == NULL))
805 return(""); /* couldn't find a complete header */
810 ret = strdup(iob->cur);
813 /* FIXME No way to handle error properly */
814 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
819 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
821 /* is this a blank line (i.e. the end of the header) ? */
833 /*********************************************************************
835 * Function : get_header_value
837 * Description : Get the value of a given header from a chained list
838 * of header lines or return NULL if no such header is
839 * present in the list.
842 * 1 : header_list = pointer to list
843 * 2 : header_name = string with name of header to look for.
844 * Trailing colon required, capitalization
847 * Returns : NULL if not found, else value of header
849 *********************************************************************/
850 char *get_header_value(const struct list *header_list, const char *header_name)
852 struct list_entry *cur_entry;
858 length = strlen(header_name);
860 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
864 if (!strncmpic(cur_entry->str, header_name, length))
867 * Found: return pointer to start of value
869 ret = (char *) (cur_entry->str + length);
870 while (*ret && ijb_isspace(*ret)) ret++;
883 /*********************************************************************
887 * Description : add, delete or modify lines in the HTTP header streams.
888 * On entry, it receives a linked list of headers space
889 * that was allocated dynamically (both the list nodes
890 * and the header contents).
892 * As a side effect it frees the space used by the original
896 * 1 : pats = list of patterns to match against headers
897 * 2 : more_headers = list of functions to add more
898 * headers (client or server)
899 * 3 : csp = Current client state (buffers, headers, etc...)
901 * Returns : Single pointer to a fully formed header, or NULL
902 * on out-of-memory error.
904 *********************************************************************/
905 char *sed(const struct parsers pats[],
906 const add_header_func_ptr more_headers[],
907 struct client_state *csp)
909 struct list_entry *p;
910 const struct parsers *v;
911 const add_header_func_ptr *f;
912 jb_err err = JB_ERR_OK;
916 * If filtering is enabled, sed is run twice,
917 * but most of the work needs to be done only once.
919 first_run = (more_headers != NULL ) ? 1 : 0;
921 if (first_run) /* Parse and print */
923 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
925 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
927 /* Header crunch()ed in previous run? -> ignore */
928 if (p->str == NULL) continue;
930 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
932 /* Does the current parser handle this header? */
933 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
935 err = v->parser(csp, (char **)&(p->str));
939 /* place any additional headers on the csp->headers list */
940 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
945 else /* Parse only */
948 * The second run is only needed if the body was modified
949 * and the content-lenght has changed.
951 if (strncmpic(csp->http->cmd, "HEAD", 4))
953 /*XXX: Code duplication*/
954 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
956 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
958 /* Header crunch()ed in previous run? -> ignore */
959 if (p->str == NULL) continue;
961 /* Does the current parser handle this header? */
962 if (strncmpic(p->str, v->str, v->len) == 0)
964 err = v->parser(csp, (char **)&(p->str));
971 if (err != JB_ERR_OK)
976 return list_to_text(csp->headers);
980 /* here begins the family of parser functions that reformat header lines */
982 /*********************************************************************
984 * Function : filter_server_header
986 * Description : Checks if server header filtering is enabled.
987 * If it is, filter_header is called to do the work.
990 * 1 : csp = Current client state (buffers, headers, etc...)
991 * 2 : header = On input, pointer to header to modify.
992 * On output, pointer to the modified header, or NULL
993 * to remove the header. This function frees the
994 * original string if necessary.
996 * Returns : JB_ERR_OK on success and always succeeds
998 *********************************************************************/
999 jb_err filter_server_header(struct client_state *csp, char **header)
1001 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1003 filter_header(csp, header);
1008 /*********************************************************************
1010 * Function : filter_client_header
1012 * Description : Checks if client header filtering is enabled.
1013 * If it is, filter_header is called to do the work.
1016 * 1 : csp = Current client state (buffers, headers, etc...)
1017 * 2 : header = On input, pointer to header to modify.
1018 * On output, pointer to the modified header, or NULL
1019 * to remove the header. This function frees the
1020 * original string if necessary.
1022 * Returns : JB_ERR_OK on success and always succeeds
1024 *********************************************************************/
1025 jb_err filter_client_header(struct client_state *csp, char **header)
1027 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1029 filter_header(csp, header);
1034 /*********************************************************************
1036 * Function : filter_header
1038 * Description : Executes all text substitutions from all applying
1039 * +filter actions on the header.
1040 * Most of the code was copied from pcrs_filter_response,
1041 * including the rather short variable names
1044 * 1 : csp = Current client state (buffers, headers, etc...)
1045 * 2 : header = On input, pointer to header to modify.
1046 * On output, pointer to the modified header, or NULL
1047 * to remove the header. This function frees the
1048 * original string if necessary.
1050 * Returns : JB_ERR_OK on success and always succeeds
1052 *********************************************************************/
1053 jb_err filter_header(struct client_state *csp, char **header)
1057 size_t size = strlen(*header);
1059 char *newheader = NULL;
1062 struct file_list *fl;
1063 struct re_filterfile_spec *b;
1064 struct list_entry *filtername;
1066 int i, found_filters = 0;
1069 * Need to check the set of re_filterfiles...
1071 for (i = 0; i < MAX_AF_FILES; i++)
1084 if (0 == found_filters)
1086 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1090 for (i = 0; i < MAX_AF_FILES; i++)
1093 if ((NULL == fl) || (NULL == fl->f))
1096 * For all applying +filter actions, look if a filter by that
1097 * name exists and if yes, execute its pcrs_joblist on the
1100 for (b = fl->f; b; b = b->next)
1102 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1103 filtername ; filtername = filtername->next)
1105 if (strcmp(b->name, filtername->str) == 0)
1107 int current_hits = 0;
1109 if ( NULL == b->joblist )
1111 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1115 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1116 *header, size, b->name);
1118 /* Apply all jobs from the joblist */
1119 for (job = b->joblist; NULL != job; job = job->next)
1121 matches = pcrs_execute(job, *header, size, &newheader, &size);
1124 current_hits += matches;
1125 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1127 *header = newheader;
1129 else if ( 0 == matches )
1131 /* Filter doesn't change header */
1137 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1138 *header, b->name, pcrs_strerror(matches));
1139 if( newheader != NULL)
1141 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1146 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1147 hits += current_hits;
1155 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1163 /*********************************************************************
1165 * Function : crumble
1167 * Description : This is called if a header matches a pattern to "crunch"
1170 * 1 : csp = Current client state (buffers, headers, etc...)
1171 * 2 : header = On input, pointer to header to modify.
1172 * On output, pointer to the modified header, or NULL
1173 * to remove the header. This function frees the
1174 * original string if necessary.
1176 * Returns : JB_ERR_OK on success, or
1177 * JB_ERR_MEMORY on out-of-memory error.
1179 *********************************************************************/
1180 jb_err crumble(struct client_state *csp, char **header)
1182 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1187 /*********************************************************************
1189 * Function : crunch_server_header
1191 * Description : Crunch server header if it matches a string supplied by the
1192 * user. Called from `sed'.
1195 * 1 : csp = Current client state (buffers, headers, etc...)
1196 * 2 : header = On input, pointer to header to modify.
1197 * On output, pointer to the modified header, or NULL
1198 * to remove the header. This function frees the
1199 * original string if necessary.
1201 * Returns : JB_ERR_OK on success and always succeeds
1203 *********************************************************************/
1204 jb_err crunch_server_header(struct client_state *csp, char **header)
1206 const char *crunch_pattern;
1207 /*Is there a header to crunch*/
1209 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1211 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1213 /*Is the current header the lucky one?*/
1214 if (strstr(*header, crunch_pattern))
1216 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1223 /*********************************************************************
1225 * Function : server_content_type
1227 * Description : Set the content-type for filterable types (text/.*,
1228 * javascript and image/gif) unless filtering has been
1229 * forbidden (CT_TABOO) while parsing earlier headers.
1230 * NOTE: Since text/plain is commonly used by web servers
1231 * for files whose correct type is unknown, we don't
1232 * set CT_TEXT for it.
1235 * 1 : csp = Current client state (buffers, headers, etc...)
1236 * 2 : header = On input, pointer to header to modify.
1237 * On output, pointer to the modified header, or NULL
1238 * to remove the header. This function frees the
1239 * original string if necessary.
1241 * Returns : JB_ERR_OK on success, or
1242 * JB_ERR_MEMORY on out-of-memory error.
1244 *********************************************************************/
1245 jb_err server_content_type(struct client_state *csp, char **header)
1249 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1251 if (csp->content_type != CT_TABOO)
1253 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1254 || strstr(*header, "xml")
1255 || strstr(*header, "application/x-javascript"))
1256 csp->content_type = CT_TEXT;
1257 else if (strstr(*header, " image/gif"))
1258 csp->content_type = CT_GIF;
1259 else if (strstr(*header, " image/jpeg"))
1260 csp->content_type = CT_JPEG;
1262 csp->content_type = 0;
1265 * Are we enabling text mode by force?
1267 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1270 * Do we really have to?
1272 if (csp->content_type == CT_TEXT)
1274 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1278 csp->content_type = CT_TEXT;
1279 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1283 * Are we messing with the content type?
1285 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1288 * Make sure the user doesn't accidently
1289 * change the content type of binary documents.
1291 if (csp->content_type == CT_TEXT)
1294 *header = strdup("Content-Type: ");
1295 string_append(header, newval);
1299 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1300 return JB_ERR_MEMORY;
1302 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1306 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1307 "Enable force-text-mode if you know what you're doing.", *header);
1314 /*********************************************************************
1316 * Function : server_transfer_coding
1318 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1319 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1320 * - Remove header if body was chunked but has been
1321 * de-chunked for filtering.
1324 * 1 : csp = Current client state (buffers, headers, etc...)
1325 * 2 : header = On input, pointer to header to modify.
1326 * On output, pointer to the modified header, or NULL
1327 * to remove the header. This function frees the
1328 * original string if necessary.
1330 * Returns : JB_ERR_OK on success, or
1331 * JB_ERR_MEMORY on out-of-memory error.
1333 *********************************************************************/
1334 jb_err server_transfer_coding(struct client_state *csp, char **header)
1337 * Turn off pcrs and gif filtering if body compressed
1339 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1341 csp->content_type = CT_TABOO;
1345 * Raise flag if body chunked
1347 if (strstr(*header, "chunked"))
1349 csp->flags |= CSP_FLAG_CHUNKED;
1352 * If the body was modified, it has been de-chunked first
1353 * and the header must be removed.
1355 if (csp->flags & CSP_FLAG_MODIFIED)
1357 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1366 /*********************************************************************
1368 * Function : server_content_encoding
1370 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1373 * 1 : csp = Current client state (buffers, headers, etc...)
1374 * 2 : header = On input, pointer to header to modify.
1375 * On output, pointer to the modified header, or NULL
1376 * to remove the header. This function frees the
1377 * original string if necessary.
1379 * Returns : JB_ERR_OK on success, or
1380 * JB_ERR_MEMORY on out-of-memory error.
1382 *********************************************************************/
1383 jb_err server_content_encoding(struct client_state *csp, char **header)
1386 * Turn off pcrs and gif filtering if body compressed
1388 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1390 csp->content_type = CT_TABOO;
1398 /*********************************************************************
1400 * Function : server_content_length
1402 * Description : Adjust Content-Length header if we modified
1406 * 1 : csp = Current client state (buffers, headers, etc...)
1407 * 2 : header = On input, pointer to header to modify.
1408 * On output, pointer to the modified header, or NULL
1409 * to remove the header. This function frees the
1410 * original string if necessary.
1412 * Returns : JB_ERR_OK on success, or
1413 * JB_ERR_MEMORY on out-of-memory error.
1415 *********************************************************************/
1416 jb_err server_content_length(struct client_state *csp, char **header)
1418 if (csp->content_length != 0) /* Content length could have been modified */
1421 * XXX: Shouldn't we check if csp->content_length
1422 * is different than the original value?
1425 *header = (char *) zalloc(100);
1426 if (*header == NULL)
1428 return JB_ERR_MEMORY;
1431 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1433 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1440 /*********************************************************************
1442 * Function : server_content_md5
1444 * Description : Crumble any Content-MD5 headers if the document was
1445 * modified. FIXME: Should we re-compute instead?
1448 * 1 : csp = Current client state (buffers, headers, etc...)
1449 * 2 : header = On input, pointer to header to modify.
1450 * On output, pointer to the modified header, or NULL
1451 * to remove the header. This function frees the
1452 * original string if necessary.
1454 * Returns : JB_ERR_OK on success, or
1455 * JB_ERR_MEMORY on out-of-memory error.
1457 *********************************************************************/
1458 jb_err server_content_md5(struct client_state *csp, char **header)
1460 if (csp->flags & CSP_FLAG_MODIFIED)
1462 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1469 /*********************************************************************
1471 * Function : server_content_disposition
1473 * Description : If enabled, blocks or modifies the "content-disposition" header.
1474 * Called from `sed'.
1477 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * 2 : header = On input, pointer to header to modify.
1479 * On output, pointer to the modified header, or NULL
1480 * to remove the header. This function frees the
1481 * original string if necessary.
1483 * Returns : JB_ERR_OK on success, or
1484 * JB_ERR_MEMORY on out-of-memory error.
1486 *********************************************************************/
1487 jb_err server_content_disposition(struct client_state *csp, char **header)
1492 * Are we messing with the content-disposition header?
1494 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1500 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1502 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1505 * Blocking content-disposition header
1507 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1514 * Replacing content-disposition header
1517 *header = strdup("content-disposition: ");
1518 string_append(header, newval);
1520 if (*header == NULL)
1522 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1526 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1529 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1532 /*********************************************************************
1534 * Function : server_last_modified
1536 * Description : Changes Last-Modified header to the actual date
1537 * to help hide-if-modified-since.
1538 * Called from `sed'.
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1542 * 2 : header = On input, pointer to header to modify.
1543 * On output, pointer to the modified header, or NULL
1544 * to remove the header. This function frees the
1545 * original string if necessary.
1547 * Returns : JB_ERR_OK on success, or
1548 * JB_ERR_MEMORY on out-of-memory error.
1550 *********************************************************************/
1551 jb_err server_last_modified(struct client_state *csp, char **header)
1554 char buf[BUFFER_SIZE];
1557 #ifdef HAVE_GMTIME_R
1560 struct tm *timeptr = NULL;
1561 time_t now, last_modified;
1563 long int days, hours, minutes, seconds;
1566 * Are we messing with the Last-Modified header?
1568 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1574 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1576 if (0 == strcmpic(newval, "block") )
1579 * Blocking Last-Modified header. Useless but why not.
1581 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1585 else if (0 == strcmpic(newval, "reset-to-request-time"))
1588 * Setting Last-Modified Header to now.
1590 get_http_time(0, buf);
1592 *header = strdup("Last-Modified: ");
1593 string_append(header, buf);
1595 if (*header == NULL)
1597 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1601 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1604 else if (0 == strcmpic(newval, "randomize"))
1606 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1608 #ifdef HAVE_GMTIME_R
1609 timeptr = gmtime_r(&now, &gmt);
1610 #elif FEATURE_PTHREAD
1611 pthread_mutex_lock(&gmtime_mutex);
1612 timeptr = gmtime(&now);
1613 pthread_mutex_unlock(&gmtime_mutex);
1615 timeptr = gmtime(&now);
1617 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1619 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1624 rtime = (long int)difftime(now, last_modified);
1627 rtime = pick_from_range(rtime);
1628 last_modified += rtime;
1629 #ifdef HAVE_GMTIME_R
1630 timeptr = gmtime_r(&last_modified, &gmt);
1631 #elif FEATURE_PTHREAD
1632 pthread_mutex_lock(&gmtime_mutex);
1633 timeptr = gmtime(&last_modified);
1634 pthread_mutex_unlock(&gmtime_mutex);
1636 timeptr = gmtime(&last_modified);
1638 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1640 *header = strdup("Last-Modified: ");
1641 string_append(header, newheader);
1643 if (*header == NULL)
1645 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1646 return JB_ERR_MEMORY;
1649 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1651 days = rtime / (3600 * 24);
1652 hours = rtime / 3600 % 24;
1653 minutes = rtime / 60 % 60;
1654 seconds = rtime % 60;
1656 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1657 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1658 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1663 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1671 /*********************************************************************
1673 * Function : client_accept_encoding
1675 * Description : Rewrite the client's Accept-Encoding header so that
1676 * if doesn't allow compression, if the action applies.
1677 * Note: For HTTP/1.0 the absence of the header is enough.
1680 * 1 : csp = Current client state (buffers, headers, etc...)
1681 * 2 : header = On input, pointer to header to modify.
1682 * On output, pointer to the modified header, or NULL
1683 * to remove the header. This function frees the
1684 * original string if necessary.
1686 * Returns : JB_ERR_OK on success, or
1687 * JB_ERR_MEMORY on out-of-memory error.
1689 *********************************************************************/
1690 jb_err client_accept_encoding(struct client_state *csp, char **header)
1692 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1694 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1698 /* Temporarily disable the correct behaviour to
1699 * work around a PHP bug.
1701 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1703 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1704 * if (*header == NULL)
1706 * return JB_ERR_MEMORY;
1717 /*********************************************************************
1719 * Function : client_te
1721 * Description : Rewrite the client's TE header so that
1722 * if doesn't allow compression, if the action applies.
1725 * 1 : csp = Current client state (buffers, headers, etc...)
1726 * 2 : header = On input, pointer to header to modify.
1727 * On output, pointer to the modified header, or NULL
1728 * to remove the header. This function frees the
1729 * original string if necessary.
1731 * Returns : JB_ERR_OK on success, or
1732 * JB_ERR_MEMORY on out-of-memory error.
1734 *********************************************************************/
1735 jb_err client_te(struct client_state *csp, char **header)
1737 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1740 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1746 /*********************************************************************
1748 * Function : client_referrer
1750 * Description : Handle the "referer" config setting properly.
1751 * Called from `sed'.
1754 * 1 : csp = Current client state (buffers, headers, etc...)
1755 * 2 : header = On input, pointer to header to modify.
1756 * On output, pointer to the modified header, or NULL
1757 * to remove the header. This function frees the
1758 * original string if necessary.
1760 * Returns : JB_ERR_OK on success, or
1761 * JB_ERR_MEMORY on out-of-memory error.
1763 *********************************************************************/
1764 jb_err client_referrer(struct client_state *csp, char **header)
1771 #ifdef FEATURE_FORCE_LOAD
1772 /* Since the referrer can include the prefix even
1773 * if the request itself is non-forced, we must
1774 * clean it unconditionally
1776 strclean(*header, FORCE_PREFIX);
1777 #endif /* def FEATURE_FORCE_LOAD */
1780 * Are we sending referer?
1782 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1787 newval = csp->action->string[ACTION_STRING_REFERER];
1789 if ((0 != strcmpic(newval, "conditional-block")))
1793 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1798 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1801 else if (0 == strcmpic(newval, "conditional-block"))
1804 * Block referer if host has changed.
1807 if (NULL == (host = strdup(csp->http->hostport)))
1810 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1811 return JB_ERR_MEMORY;
1813 if (NULL == (referer = strdup(*header)))
1817 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1818 return JB_ERR_MEMORY;
1820 hostlenght = strlen(host);
1821 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1823 /*Shorten referer to make sure the referer is blocked
1824 *if www.example.org/www.example.com-shall-see-the-referer/
1825 *links to www.example.com/
1827 referer[hostlenght+17] = '\0';
1829 if ( 0 == strstr(referer, host)) /*Host has changed*/
1831 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1836 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1842 else if (0 != strcmpic(newval, "forge"))
1845 * We have a specific (fixed) referer we want to send.
1847 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1849 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1851 *header = strdup("Referer: ");
1852 string_append(header, newval);
1853 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1855 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1860 * Forge a referer as http://[hostname:port of REQUEST]/
1861 * to fool stupid checks for in-site links
1864 *header = strdup("Referer: http://");
1865 string_append(header, csp->http->hostport);
1866 string_append(header, "/");
1867 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1869 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1873 /*********************************************************************
1875 * Function : client_accept_language
1877 * Description : Handle the "Accept-Language" config setting properly.
1878 * Called from `sed'.
1881 * 1 : csp = Current client state (buffers, headers, etc...)
1882 * 2 : header = On input, pointer to header to modify.
1883 * On output, pointer to the modified header, or NULL
1884 * to remove the header. This function frees the
1885 * original string if necessary.
1887 * Returns : JB_ERR_OK on success, or
1888 * JB_ERR_MEMORY on out-of-memory error.
1890 *********************************************************************/
1891 jb_err client_accept_language(struct client_state *csp, char **header)
1896 * Are we messing with the Accept-Language?
1898 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1900 /*I don't think so*/
1904 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1906 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1909 * Blocking Accept-Language header
1911 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1918 * Replacing Accept-Language header
1921 *header = strdup("Accept-Language: ");
1922 string_append(header, newval);
1924 if (*header == NULL)
1926 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1930 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1933 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1936 /*********************************************************************
1938 * Function : crunch_client_header
1940 * Description : Crunch client header if it matches a string supplied by the
1941 * user. Called from `sed'.
1944 * 1 : csp = Current client state (buffers, headers, etc...)
1945 * 2 : header = On input, pointer to header to modify.
1946 * On output, pointer to the modified header, or NULL
1947 * to remove the header. This function frees the
1948 * original string if necessary.
1950 * Returns : JB_ERR_OK on success and always succeeds
1952 *********************************************************************/
1953 jb_err crunch_client_header(struct client_state *csp, char **header)
1955 const char *crunch_pattern;
1956 /*Is there a header to crunch*/
1958 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1960 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1962 /*Is the current header the lucky one?*/
1963 if (strstr(*header, crunch_pattern))
1965 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1973 /*********************************************************************
1975 * Function : client_uagent
1977 * Description : Handle the "user-agent" config setting properly
1978 * and remember its original value to enable browser
1979 * bug workarounds. Called from `sed'.
1982 * 1 : csp = Current client state (buffers, headers, etc...)
1983 * 2 : header = On input, pointer to header to modify.
1984 * On output, pointer to the modified header, or NULL
1985 * to remove the header. This function frees the
1986 * original string if necessary.
1988 * Returns : JB_ERR_OK on success, or
1989 * JB_ERR_MEMORY on out-of-memory error.
1991 *********************************************************************/
1992 jb_err client_uagent(struct client_state *csp, char **header)
1996 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2001 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2008 *header = strdup("User-Agent: ");
2009 string_append(header, newval);
2011 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2013 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2016 /*********************************************************************
2018 * Function : client_ua
2020 * Description : Handle "ua-" headers properly. Called from `sed'.
2023 * 1 : csp = Current client state (buffers, headers, etc...)
2024 * 2 : header = On input, pointer to header to modify.
2025 * On output, pointer to the modified header, or NULL
2026 * to remove the header. This function frees the
2027 * original string if necessary.
2029 * Returns : JB_ERR_OK on success, or
2030 * JB_ERR_MEMORY on out-of-memory error.
2032 *********************************************************************/
2033 jb_err client_ua(struct client_state *csp, char **header)
2035 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2037 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2045 /*********************************************************************
2047 * Function : client_from
2049 * Description : Handle the "from" config setting properly.
2050 * Called from `sed'.
2053 * 1 : csp = Current client state (buffers, headers, etc...)
2054 * 2 : header = On input, pointer to header to modify.
2055 * On output, pointer to the modified header, or NULL
2056 * to remove the header. This function frees the
2057 * original string if necessary.
2059 * Returns : JB_ERR_OK on success, or
2060 * JB_ERR_MEMORY on out-of-memory error.
2062 *********************************************************************/
2063 jb_err client_from(struct client_state *csp, char **header)
2067 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2074 newval = csp->action->string[ACTION_STRING_FROM];
2077 * Are we blocking the e-mail address?
2079 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2081 log_error(LOG_LEVEL_HEADER, "crunched From!");
2085 log_error(LOG_LEVEL_HEADER, " modified");
2087 *header = strdup("From: ");
2088 string_append(header, newval);
2090 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2094 /*********************************************************************
2096 * Function : client_send_cookie
2098 * Description : Handle the "cookie" header properly. Called from `sed'.
2099 * If cookie is accepted, add it to the cookie_list,
2100 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2103 * 1 : csp = Current client state (buffers, headers, etc...)
2104 * 2 : header = On input, pointer to header to modify.
2105 * On output, pointer to the modified header, or NULL
2106 * to remove the header. This function frees the
2107 * original string if necessary.
2109 * Returns : JB_ERR_OK on success, or
2110 * JB_ERR_MEMORY on out-of-memory error.
2112 *********************************************************************/
2113 jb_err client_send_cookie(struct client_state *csp, char **header)
2115 jb_err result = JB_ERR_OK;
2117 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2119 /* strlen("cookie: ") == 8 */
2120 result = enlist(csp->cookie_list, *header + 8);
2124 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2128 * Always remove the cookie here. The cookie header
2129 * will be sent at the end of the header.
2137 /*********************************************************************
2139 * Function : client_x_forwarded
2141 * Description : Handle the "x-forwarded-for" config setting properly,
2142 * also used in the add_client_headers list. Called from `sed'.
2145 * 1 : csp = Current client state (buffers, headers, etc...)
2146 * 2 : header = On input, pointer to header to modify.
2147 * On output, pointer to the modified header, or NULL
2148 * to remove the header. This function frees the
2149 * original string if necessary.
2151 * Returns : JB_ERR_OK on success, or
2152 * JB_ERR_MEMORY on out-of-memory error.
2154 *********************************************************************/
2155 jb_err client_x_forwarded(struct client_state *csp, char **header)
2157 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2159 /* Save it so we can re-add it later */
2160 freez(csp->x_forwarded);
2161 csp->x_forwarded = *header;
2164 * Always set *header = NULL, since this information
2165 * will be sent at the end of the header.
2172 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2179 /*********************************************************************
2181 * Function : client_max_forwards
2183 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2184 * from the value of the Max-Forwards header field.
2187 * 1 : csp = Current client state (buffers, headers, etc...)
2188 * 2 : header = On input, pointer to header to modify.
2189 * On output, pointer to the modified header, or NULL
2190 * to remove the header. This function frees the
2191 * original string if necessary.
2193 * Returns : JB_ERR_OK on success, or
2194 * JB_ERR_MEMORY on out-of-memory error.
2196 *********************************************************************/
2197 jb_err client_max_forwards(struct client_state *csp, char **header)
2199 unsigned int max_forwards;
2201 if ((0 == strcmpic(csp->http->gpc, "trace"))
2202 || (0 == strcmpic(csp->http->gpc, "options")))
2204 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2206 if (max_forwards-- >= 1)
2208 sprintf(*header, "Max-Forwards: %u", max_forwards);
2209 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2213 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2222 /*********************************************************************
2224 * Function : client_host
2226 * Description : If the request URI did not contain host and
2227 * port information, parse and evaluate the Host
2230 * Also, kill ill-formed HOST: headers as sent by
2231 * Apple's iTunes software when used with a proxy.
2234 * 1 : csp = Current client state (buffers, headers, etc...)
2235 * 2 : header = On input, pointer to header to modify.
2236 * On output, pointer to the modified header, or NULL
2237 * to remove the header. This function frees the
2238 * original string if necessary.
2240 * Returns : JB_ERR_OK on success, or
2241 * JB_ERR_MEMORY on out-of-memory error.
2243 *********************************************************************/
2244 jb_err client_host(struct client_state *csp, char **header)
2249 * If the header field name is all upper-case, chances are that it's
2250 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2251 * not a problem -- they are regenerated later.
2253 if ((*header)[1] == 'O')
2255 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2260 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2261 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2264 if (NULL == (p = strdup((*header)+6)))
2266 return JB_ERR_MEMORY;
2269 if (NULL == (q = strdup(p)))
2272 return JB_ERR_MEMORY;
2275 freez(csp->http->hostport);
2276 csp->http->hostport = p;
2277 freez(csp->http->host);
2278 csp->http->host = q;
2279 q = strchr(csp->http->host, ':');
2282 /* Terminate hostname and evaluate port string */
2284 csp->http->port = atoi(q);
2288 csp->http->port = csp->http->ssl ? 443 : 80;
2291 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2292 csp->http->hostport, csp->http->host, csp->http->port);
2298 /*********************************************************************
2300 * Function : client_if_modified_since
2302 * Description : Remove or modify the If-Modified-Since header.
2305 * 1 : csp = Current client state (buffers, headers, etc...)
2306 * 2 : header = On input, pointer to header to modify.
2307 * On output, pointer to the modified header, or NULL
2308 * to remove the header. This function frees the
2309 * original string if necessary.
2311 * Returns : JB_ERR_OK on success, or
2312 * JB_ERR_MEMORY on out-of-memory error.
2314 *********************************************************************/
2315 jb_err client_if_modified_since(struct client_state *csp, char **header)
2318 #ifdef HAVE_GMTIME_R
2321 struct tm *timeptr = NULL;
2325 long int hours, minutes, seconds;
2329 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2332 * The client got an error message because of a temporary problem,
2333 * the problem is gone and the client now tries to revalidate our
2334 * error message on the real server. The revalidation would always
2335 * end with the transmission of the whole document and there is
2336 * no need to expose the bogus If-Modified-Since header.
2338 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2341 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2343 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2345 if ((0 == strcmpic(newval, "block")))
2347 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2350 else /* add random value */
2352 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2354 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2359 rtime = strtol(newval, &endptr, 0);
2362 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2363 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2370 rtime = pick_from_range(rtime);
2374 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2377 tm += rtime * (negative ? -1 : 1);
2378 #ifdef HAVE_GMTIME_R
2379 timeptr = gmtime_r(&tm, &gmt);
2380 #elif FEATURE_PTHREAD
2381 pthread_mutex_lock(&gmtime_mutex);
2382 timeptr = gmtime(&tm);
2383 pthread_mutex_unlock(&gmtime_mutex);
2385 timeptr = gmtime(&tm);
2387 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2390 *header = strdup("If-Modified-Since: ");
2391 string_append(header, newheader);
2393 if (*header == NULL)
2395 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2396 return JB_ERR_MEMORY;
2399 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2401 hours = rtime / 3600;
2402 minutes = rtime / 60 % 60;
2403 seconds = rtime % 60;
2405 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2406 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2407 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2416 /*********************************************************************
2418 * Function : client_if_none_match
2420 * Description : Remove the If-None-Match header.
2423 * 1 : csp = Current client state (buffers, headers, etc...)
2424 * 2 : header = On input, pointer to header to modify.
2425 * On output, pointer to the modified header, or NULL
2426 * to remove the header. This function frees the
2427 * original string if necessary.
2429 * Returns : JB_ERR_OK on success, or
2430 * JB_ERR_MEMORY on out-of-memory error.
2432 *********************************************************************/
2433 jb_err client_if_none_match(struct client_state *csp, char **header)
2435 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2437 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2444 /*********************************************************************
2446 * Function : client_x_filter
2448 * Description : Disables filtering if the client set "X-Filter: No".
2449 * Called from `sed'.
2452 * 1 : csp = Current client state (buffers, headers, etc...)
2453 * 2 : header = On input, pointer to header to modify.
2454 * On output, pointer to the modified header, or NULL
2455 * to remove the header. This function frees the
2456 * original string if necessary.
2458 * Returns : JB_ERR_OK on success
2460 *********************************************************************/
2461 jb_err client_x_filter(struct client_state *csp, char **header)
2463 if ( 0 == strcmpic(*header, "X-Filter: No"))
2465 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2467 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2471 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2473 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2477 csp->content_type = CT_TABOO;
2478 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2479 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2480 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2482 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2489 /* the following functions add headers directly to the header list */
2491 /*********************************************************************
2493 * Function : client_host_adder
2495 * Description : Adds the Host: header field if it is missing.
2496 * Called from `sed'.
2499 * 1 : csp = Current client state (buffers, headers, etc...)
2501 * Returns : JB_ERR_OK on success, or
2502 * JB_ERR_MEMORY on out-of-memory error.
2504 *********************************************************************/
2505 jb_err client_host_adder(struct client_state *csp)
2510 if ( !csp->http->hostport || !*(csp->http->hostport))
2516 * remove 'user:pass@' from 'proto://user:pass@host'
2518 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2524 p = csp->http->hostport;
2527 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2528 err = enlist_unique_header(csp->headers, "Host", p);
2534 /*********************************************************************
2536 * Function : client_cookie_adder
2538 * Description : Used in the add_client_headers list. Called from `sed'.
2541 * 1 : csp = Current client state (buffers, headers, etc...)
2543 * Returns : JB_ERR_OK on success, or
2544 * JB_ERR_MEMORY on out-of-memory error.
2546 *********************************************************************/
2547 jb_err client_cookie_adder(struct client_state *csp)
2549 struct list_entry *lst;
2551 struct list_entry *list1 = csp->cookie_list->first;
2552 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2553 int first_cookie = 1;
2556 if ((list1 == NULL) && (list2 == NULL))
2562 tmp = strdup("Cookie: ");
2564 for (lst = list1; lst ; lst = lst->next)
2572 string_append(&tmp, "; ");
2574 string_append(&tmp, lst->str);
2577 for (lst = list2; lst ; lst = lst->next)
2585 string_append(&tmp, "; ");
2587 string_join(&tmp, cookie_encode(lst->str));
2592 return JB_ERR_MEMORY;
2595 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2596 err = enlist(csp->headers, tmp);
2602 /*********************************************************************
2604 * Function : client_accept_encoding_adder
2606 * Description : Add an Accept-Encoding header to the client's request
2607 * that disables compression if the action applies, and
2608 * the header is not already there. Called from `sed'.
2609 * Note: For HTTP/1.0, the absence of the header is enough.
2612 * 1 : csp = Current client state (buffers, headers, etc...)
2614 * Returns : JB_ERR_OK on success, or
2615 * JB_ERR_MEMORY on out-of-memory error.
2617 *********************************************************************/
2618 jb_err client_accept_encoding_adder(struct client_state *csp)
2620 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2621 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2623 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2630 /*********************************************************************
2632 * Function : client_xtra_adder
2634 * Description : Used in the add_client_headers list. Called from `sed'.
2637 * 1 : csp = Current client state (buffers, headers, etc...)
2639 * Returns : JB_ERR_OK on success, or
2640 * JB_ERR_MEMORY on out-of-memory error.
2642 *********************************************************************/
2643 jb_err client_xtra_adder(struct client_state *csp)
2645 struct list_entry *lst;
2648 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2649 lst ; lst = lst->next)
2651 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2652 err = enlist(csp->headers, lst->str);
2664 /*********************************************************************
2666 * Function : client_x_forwarded_adder
2668 * Description : Used in the add_client_headers list. Called from `sed'.
2671 * 1 : csp = Current client state (buffers, headers, etc...)
2673 * Returns : JB_ERR_OK on success, or
2674 * JB_ERR_MEMORY on out-of-memory error.
2676 *********************************************************************/
2677 jb_err client_x_forwarded_adder(struct client_state *csp)
2682 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2687 if (csp->x_forwarded)
2689 p = strdup(csp->x_forwarded);
2690 string_append(&p, ", ");
2694 p = strdup("X-Forwarded-For: ");
2696 string_append(&p, csp->ip_addr_str);
2700 return JB_ERR_MEMORY;
2703 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2704 err = enlist(csp->headers, p);
2711 /*********************************************************************
2713 * Function : connection_close_adder
2715 * Description : Adds a "Connection: close" header to csp->headers
2716 * as a temporary fix for the needed but missing HTTP/1.1
2717 * support. Called from `sed'.
2718 * FIXME: This whole function shouldn't be neccessary!
2721 * 1 : csp = Current client state (buffers, headers, etc...)
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 jb_err connection_close_adder(struct client_state *csp)
2729 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2730 return enlist(csp->headers, "Connection: close");
2734 /*********************************************************************
2736 * Function : server_http
2738 * Description : - Save the HTTP Status into csp->http->status
2739 * - Set CT_TABOO to prevent filtering if the answer
2740 * is a partial range (HTTP status 206)
2741 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2745 * 1 : csp = Current client state (buffers, headers, etc...)
2746 * 2 : header = On input, pointer to header to modify.
2747 * On output, pointer to the modified header, or NULL
2748 * to remove the header. This function frees the
2749 * original string if necessary.
2751 * Returns : JB_ERR_OK on success, or
2752 * JB_ERR_MEMORY on out-of-memory error.
2754 *********************************************************************/
2755 jb_err server_http(struct client_state *csp, char **header)
2757 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2758 if (csp->http->status == 206)
2760 csp->content_type = CT_TABOO;
2763 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2766 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2773 /*********************************************************************
2775 * Function : server_set_cookie
2777 * Description : Handle the server "cookie" header properly.
2778 * Log cookie to the jar file. Then "crunch" it,
2779 * or accept it. Called from `sed'.
2782 * 1 : csp = Current client state (buffers, headers, etc...)
2783 * 2 : header = On input, pointer to header to modify.
2784 * On output, pointer to the modified header, or NULL
2785 * to remove the header. This function frees the
2786 * original string if necessary.
2788 * Returns : JB_ERR_OK on success, or
2789 * JB_ERR_MEMORY on out-of-memory error.
2791 *********************************************************************/
2792 jb_err server_set_cookie(struct client_state *csp, char **header)
2794 #ifdef FEATURE_COOKIE_JAR
2795 if (csp->config->jar)
2798 * Write timestamp into outbuf.
2800 * Complex because not all OSs have tm_gmtoff or
2801 * the %z field in strftime()
2803 char tempbuf[ BUFFER_SIZE ];
2807 #ifdef HAVE_LOCALTIME_R
2808 tm_now = *localtime_r(&now, &tm_now);
2809 #elif FEATURE_PTHREAD
2810 pthread_mutex_lock(&localtime_mutex);
2811 tm_now = *localtime (&now);
2812 pthread_mutex_unlock(&localtime_mutex);
2814 tm_now = *localtime (&now);
2816 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2818 /* strlen("set-cookie: ") = 12 */
2819 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2821 #endif /* def FEATURE_COOKIE_JAR */
2823 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2825 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2826 return crumble(csp, header);
2828 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2830 /* Flag whether or not to log a message */
2833 /* A variable to store the tag we're working on */
2836 /* Skip "Set-Cookie:" (11 characters) in header */
2837 cur_tag = *header + 11;
2839 /* skip whitespace between "Set-Cookie:" and value */
2840 while (*cur_tag && ijb_isspace(*cur_tag))
2845 /* Loop through each tag in the cookie */
2849 char *next_tag = strchr(cur_tag, ';');
2850 if (next_tag != NULL)
2852 /* Skip the ';' character itself */
2855 /* skip whitespace ";" and start of tag */
2856 while (*next_tag && ijb_isspace(*next_tag))
2863 /* "Next tag" is the end of the string */
2864 next_tag = cur_tag + strlen(cur_tag);
2867 /* Is this the "Expires" tag? */
2868 if (strncmpic(cur_tag, "expires=", 8) == 0)
2870 /* Delete the tag by copying the rest of the string over it.
2871 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2872 * since the behaviour of strcpy is undefined for overlapping
2875 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2877 /* That changed the header, need to issue a log message */
2880 /* Note that the next tag has now been moved to *cur_tag,
2881 * so we do not need to update the cur_tag pointer.
2886 /* Move on to next cookie tag */
2893 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2901 #ifdef FEATURE_FORCE_LOAD
2902 /*********************************************************************
2904 * Function : strclean
2906 * Description : In-Situ-Eliminate all occurances of substring in
2910 * 1 : string = string to clean
2911 * 2 : substring = substring to eliminate
2913 * Returns : Number of eliminations
2915 *********************************************************************/
2916 int strclean(const char *string, const char *substring)
2922 len = strlen(substring);
2924 while((pos = strstr(string, substring)) != NULL)
2931 while (*p++ != '\0');
2938 #endif /* def FEATURE_FORCE_LOAD */
2940 /*********************************************************************
2942 * Function : parse_header_time
2944 * Description : Transforms time inside a HTTP header into
2945 * the usual time format.
2948 * 1 : header = header to parse
2949 * 2 : tm = storage for the resulting time in seconds
2951 * Returns : Time struct containing the header time, or
2952 * NULL in case of a parsing problems.
2954 *********************************************************************/
2955 struct tm *parse_header_time(char *header, time_t *tm) {
2959 struct tm * timeptr;
2962 * Initializing gmt to prevent time zone offsets.
2964 * While this is only necessary on some platforms
2965 * (mingw32 for example), I don't know how to
2966 * detect these automatically and doing it everywhere
2970 #ifdef HAVE_LOCALTIME_R
2971 gmt = *localtime_r(tm, &gmt);
2972 #elif FEATURE_PTHREAD
2973 pthread_mutex_lock(&localtime_mutex);
2974 gmt = *localtime(tm);
2975 pthread_mutex_unlock(&localtime_mutex);
2977 gmt = *localtime(tm);
2980 /* Skipping header name */
2981 timestring = strstr(header, ": ");
2982 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
2995 /*********************************************************************
2997 * Function : get_destination_from_headers
2999 * Description : Parse the "Host:" header to get the request's destination.
3000 * Only needed if the client's request was forcefully
3001 * redirected into Privoxy.
3003 * Code mainly copied from client_host() which is currently
3004 * run too late for this purpose.
3007 * 1 : headers = List of headers (one of them hopefully being
3008 * the "Host:" header)
3009 * 2 : http = storage for the result (host, port and hostport).
3011 * Returns : JB_ERR_MEMORY in case of memory problems,
3012 * JB_ERR_PARSE if the host header couldn't be found,
3013 * JB_ERR_OK otherwise.
3015 *********************************************************************/
3016 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3022 host = get_header_value(headers, "Host:");
3026 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3027 return JB_ERR_PARSE;
3030 if (NULL == (p = strdup((host))))
3032 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3033 return JB_ERR_MEMORY;
3036 if (NULL == (q = strdup(p)))
3039 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3040 return JB_ERR_MEMORY;
3043 freez(http->hostport);
3047 q = strchr(http->host, ':');
3050 /* Terminate hostname and evaluate port string */
3052 http->port = atoi(q);
3056 http->port = http->ssl ? 443 : 80;
3059 /* Rebuild request URL */
3061 http->url = strdup(http->ssl ? "https://" : "http://");
3062 string_append(&http->url, http->hostport);
3063 string_append(&http->url, http->path);
3064 if (http->url == NULL)
3066 return JB_ERR_MEMORY;
3069 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",