1 const char parsers_rcs[] = "$Id: parsers.c,v 1.68 2006/09/06 10:43:32 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed',
14 * and `server_set_cookie'.
16 * Copyright : Written by and Copyright (C) 2001 the SourceForge
17 * Privoxy team. http://www.privoxy.org/
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
23 * This program is free software; you can redistribute it
24 * and/or modify it under the terms of the GNU General
25 * Public License as published by the Free Software
26 * Foundation; either version 2 of the License, or (at
27 * your option) any later version.
29 * This program is distributed in the hope that it will
30 * be useful, but WITHOUT ANY WARRANTY; without even the
31 * implied warranty of MERCHANTABILITY or FITNESS FOR A
32 * PARTICULAR PURPOSE. See the GNU General Public
33 * License for more details.
35 * The GNU General Public License should be included with
36 * this file. If not, you can view it at
37 * http://www.gnu.org/copyleft/gpl.html
38 * or write to the Free Software Foundation, Inc., 59
39 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
43 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
44 * Added config option enable-remote-http-toggle
45 * to specify if Privoxy should recognize special
46 * headers (currently only X-Filter) to change its
47 * behaviour. Disabled by default.
49 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
50 * After filtering de-chunked instances, remove
51 * "Transfer-Encoding" header entirely instead of changing
52 * it to "Transfer-Encoding: identity", which is invalid.
53 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
55 * Don't use localtime in parse_header_time. An empty time struct
56 * is good enough, it gets overwritten by strptime anyway.
58 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
59 * Use gmtime_r if available, fallback to gmtime with mutex
60 * protection for MacOSX and use vanilla gmtime for the rest.
62 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
63 * Changed client_referrer to use the right type (size_t) for
64 * hostlenght and to shorten the temporary referrer string with
65 * '\0' instead of adding a useless line break.
67 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
68 * - Back to timegm() using GnuPG's replacement if necessary.
69 * Using mktime() and localtime() could add a on hour offset if
70 * the randomize factor was big enough to lead to a summer/wintertime
73 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
75 * - Moved randomization code into pick_from_range().
77 * - Changed parse_header_time definition.
78 * time_t isn't guaranteed to be signed and
79 * if it isn't, -1 isn't available as error code.
80 * Changed some variable types in client_if_modified_since()
81 * because of the same reason.
83 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
84 * OS/2 compilation compatibility fixups
86 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
87 * Changed include from strptime.c to strptime.h
89 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
90 * Split filter-headers{} into filter-client-headers{}
91 * and filter-server-headers{}.
92 * Added parse_header_time() to share some code.
93 * Replaced timegm() with mktime().
95 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
96 * Windows service integration
98 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
99 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
101 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
102 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
103 * with what was really the latest development (the v_3_0_branch branch)
105 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
106 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
108 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
109 * Add the ability to check jpeg images for invalid
110 * lengths of comment blocks. Defensive strategy
111 * against the exploit:
112 * Microsoft Security Bulletin MS04-028
113 * Buffer Overrun in JPEG Processing (GDI+) Could
114 * Allow Code Execution (833987)
115 * Enabled with +inspect-jpegs in actions files.
117 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
118 * Excluded text/plain objects from filtering. This fixes a
119 * couple of client-crashing, download corruption and
120 * Privoxy performance issues, whose root cause lies in
121 * web servers labelling content of unknown type as text/plain.
123 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
124 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
126 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
127 * Completing the previous change
129 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
130 * Added temporary workaround for bug in PHP < 4.2.3
132 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
133 * 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.
135 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
136 * Fix typo: supressed -> suppressed
138 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
139 * Improved cookie logging
141 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
142 * Added basic support for OPTIONS and TRACE HTTP methods:
143 * - New parser function client_max_forwards which decrements
144 * the Max-Forwards HTTP header field of OPTIONS and TRACE
145 * requests by one before forwarding
146 * - New parser function client_host which extracts the host
147 * and port information from the HTTP header field if the
148 * request URI was not absolute
149 * - Don't crumble and re-add the Host: header, but only generate
150 * and append if missing
152 * Revision 1.56 2002/05/12 15:34:22 jongfoster
153 * Fixing typo in a comment
155 * Revision 1.55 2002/05/08 16:01:07 oes
156 * Optimized add_to_iob:
157 * - Use realloc instead of malloc(), memcpy(), free()
158 * - Expand to powers of two if possible, to get
159 * O(log n) reallocs instead of O(n).
160 * - Moved check for buffer limit here from chat
161 * - Report failure via returncode
163 * Revision 1.54 2002/04/02 15:03:16 oes
164 * Tiny code cosmetics
166 * Revision 1.53 2002/03/26 22:29:55 swa
167 * we have a new homepage!
169 * Revision 1.52 2002/03/24 13:25:43 swa
170 * name change related issues
172 * Revision 1.51 2002/03/13 00:27:05 jongfoster
175 * Revision 1.50 2002/03/12 01:45:35 oes
176 * More verbose logging
178 * Revision 1.49 2002/03/09 20:03:52 jongfoster
179 * - Making various functions return int rather than size_t.
180 * (Undoing a recent change). Since size_t is unsigned on
181 * Windows, functions like read_socket that return -1 on
182 * error cannot return a size_t.
184 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
185 * crashes, and also frequently caused JB to jump to 100%
186 * CPU and stay there. (Because it thought it had just
187 * read ((unsigned)-1) == 4Gb of data...)
189 * - The signature of write_socket has changed, it now simply
190 * returns success=0/failure=nonzero.
192 * - Trying to get rid of a few warnings --with-debug on
193 * Windows, I've introduced a new type "jb_socket". This is
194 * used for the socket file descriptors. On Windows, this
195 * is SOCKET (a typedef for unsigned). Everywhere else, it's
196 * an int. The error value can't be -1 any more, so it's
197 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
198 * Windows it maps to the #define INVALID_SOCKET.)
200 * - The signature of bind_port has changed.
202 * Revision 1.48 2002/03/07 03:46:53 oes
203 * Fixed compiler warnings etc
205 * Revision 1.47 2002/02/20 23:15:13 jongfoster
206 * Parsing functions now handle out-of-memory gracefully by returning
209 * Revision 1.46 2002/01/17 21:03:47 jongfoster
210 * Moving all our URL and URL pattern parsing code to urlmatch.c.
212 * Revision 1.45 2002/01/09 14:33:03 oes
213 * Added support for localtime_r.
215 * Revision 1.44 2001/12/14 01:22:54 steudten
216 * Remove 'user:pass@' from 'proto://user:pass@host' for the
217 * new added header 'Host: ..'. (See Req ID 491818)
219 * Revision 1.43 2001/11/23 00:26:38 jongfoster
220 * Fixing two really stupid errors in my previous commit
222 * Revision 1.42 2001/11/22 21:59:30 jongfoster
223 * Adding code to handle +no-cookies-keep
225 * Revision 1.41 2001/11/05 23:43:05 steudten
226 * Add time+date to log files.
228 * Revision 1.40 2001/10/26 20:13:09 jongfoster
229 * ctype.h is needed in Windows, too.
231 * Revision 1.39 2001/10/26 17:40:04 oes
232 * Introduced get_header_value()
233 * Removed http->user_agent, csp->referrer and csp->accept_types
234 * Removed client_accept()
236 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
237 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
238 * threads to call select() simultaneously. So, it's time to do a real, live,
239 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
240 * (native). Both versions will work, but using __OS2__ offers multi-threading.
242 * Revision 1.37 2001/10/23 21:36:02 jongfoster
243 * Documenting sed()'s error behaviou (doc change only)
245 * Revision 1.36 2001/10/13 12:51:51 joergs
246 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
247 * force-load), instead crumble Host: and add it (again) in client_host_adder
248 * (in case we get a HTTP/1.0 request without Host: header and forward it to
249 * a HTTP/1.1 server/proxy).
251 * Revision 1.35 2001/10/09 22:39:21 jongfoster
252 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
255 * Revision 1.34 2001/10/07 18:50:55 oes
256 * Added server_content_encoding, renamed server_transfer_encoding
258 * Revision 1.33 2001/10/07 18:04:49 oes
259 * Changed server_http11 to server_http and its pattern to "HTTP".
260 * Additional functionality: it now saves the HTTP status into
261 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
263 * Revision 1.32 2001/10/07 15:43:28 oes
264 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
265 * client_te and client_accept_encoding_adder, triggered by the new
266 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
267 * changed to allow only identity and chunked, and the TE header is
268 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
270 * parse_http_request no longer does anything than parsing. The rewriting
271 * of http->cmd and version mangling are gone. It now also recognizes
272 * the put and delete methods and saves the url in http->url. Removed
275 * renamed content_type and content_length to have the server_ prefix
277 * server_content_type now only works if csp->content_type != CT_TABOO
279 * added server_transfer_encoding, which
280 * - Sets CT_TABOO to prohibit filtering if encoding compresses
281 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
282 * - Change from "chunked" to "identity" if body was chunked
283 * but has been de-chunked for filtering.
285 * added server_content_md5 which crunches any Content-MD5 headers
286 * if the body was modified.
288 * made server_http11 conditional on +downgrade action
290 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
292 * Revision 1.31 2001/10/05 14:25:02 oes
293 * Crumble Keep-Alive from Server
295 * Revision 1.30 2001/09/29 12:56:03 joergs
296 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
298 * Revision 1.29 2001/09/24 21:09:24 jongfoster
299 * Fixing 2 memory leaks that Guy spotted, where the paramater to
300 * enlist() was not being free()d.
302 * Revision 1.28 2001/09/22 16:32:28 jongfoster
303 * Removing unused #includes.
305 * Revision 1.27 2001/09/20 15:45:25 steudten
307 * add casting from size_t to int for printf()
308 * remove local variable shadow s2
310 * Revision 1.26 2001/09/16 17:05:14 jongfoster
311 * Removing unused #include showarg.h
313 * Revision 1.25 2001/09/16 13:21:27 jongfoster
314 * Changes to use new list functions.
316 * Revision 1.24 2001/09/13 23:05:50 jongfoster
317 * Changing the string paramater to the header parsers a "const".
319 * Revision 1.23 2001/09/12 18:08:19 steudten
321 * In parse_http_request() header rewriting miss the host value, so
322 * from http://www.mydomain.com the result was just " / " not
323 * http://www.mydomain.com/ in case we forward.
325 * Revision 1.22 2001/09/10 10:58:53 oes
326 * Silenced compiler warnings
328 * Revision 1.21 2001/07/31 14:46:00 oes
329 * - Persistant connections now suppressed
330 * - sed() no longer appends empty header to csp->headers
332 * Revision 1.20 2001/07/30 22:08:36 jongfoster
333 * Tidying up #defines:
334 * - All feature #defines are now of the form FEATURE_xxx
335 * - Permanently turned off WIN_GUI_EDIT
336 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
338 * Revision 1.19 2001/07/25 17:21:54 oes
339 * client_uagent now saves copy of User-Agent: header value
341 * Revision 1.18 2001/07/13 14:02:46 oes
342 * - Included fix to repair broken HTTP requests that
343 * don't contain a path, not even '/'.
344 * - Removed all #ifdef PCRS
345 * - content_type now always inspected and classified as
346 * text, gif or other.
347 * - formatting / comments
349 * Revision 1.17 2001/06/29 21:45:41 oes
350 * Indentation, CRLF->LF, Tab-> Space
352 * Revision 1.16 2001/06/29 13:32:42 oes
354 * - Adapted free_http_request
355 * - Removed logentry from cancelled commit
357 * Revision 1.15 2001/06/03 19:12:38 oes
358 * deleted const struct interceptors
360 * Revision 1.14 2001/06/01 18:49:17 jongfoster
361 * Replaced "list_share" with "list" - the tiny memory gain was not
362 * worth the extra complexity.
364 * Revision 1.13 2001/05/31 21:30:33 jongfoster
365 * Removed list code - it's now in list.[ch]
366 * Renamed "permission" to "action", and changed many features
367 * to use the actions file rather than the global config.
369 * Revision 1.12 2001/05/31 17:33:13 oes
373 * Revision 1.11 2001/05/29 20:11:19 joergs
374 * '/ * inside comment' warning removed.
376 * Revision 1.10 2001/05/29 09:50:24 jongfoster
377 * Unified blocklist/imagelist/permissionslist.
378 * File format is still under discussion, but the internal changes
381 * Also modified interceptor behaviour:
382 * - We now intercept all URLs beginning with one of the following
383 * prefixes (and *only* these prefixes):
385 * * http://ijbswa.sf.net/config/
386 * * http://ijbswa.sourceforge.net/config/
387 * - New interceptors "home page" - go to http://i.j.b/ to see it.
388 * - Internal changes so that intercepted and fast redirect pages
389 * are not replaced with an image.
390 * - Interceptors now have the option to send a binary page direct
391 * to the client. (i.e. ijb-send-banner uses this)
392 * - Implemented show-url-info interceptor. (Which is why I needed
393 * the above interceptors changes - a typical URL is
394 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
395 * The previous mechanism would not have intercepted that, and
396 * if it had been intercepted then it then it would have replaced
399 * Revision 1.9 2001/05/28 17:26:33 jongfoster
400 * Fixing segfault if last header was crunched.
401 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
402 * can use the cross-platform sprintf() instead.)
404 * Revision 1.8 2001/05/27 22:17:04 oes
406 * - re_process_buffer no longer writes the modified buffer
407 * to the client, which was very ugly. It now returns the
408 * buffer, which it is then written by chat.
410 * - content_length now adjusts the Content-Length: header
411 * for modified documents rather than crunch()ing it.
412 * (Length info in csp->content_length, which is 0 for
413 * unmodified documents)
415 * - For this to work, sed() is called twice when filtering.
417 * Revision 1.7 2001/05/27 13:19:06 oes
418 * Patched Joergs solution for the content-length in.
420 * Revision 1.6 2001/05/26 13:39:32 jongfoster
421 * Only crunches Content-Length header if applying RE filtering.
422 * Without this fix, Microsoft Windows Update wouldn't work.
424 * Revision 1.5 2001/05/26 00:28:36 jongfoster
425 * Automatic reloading of config file.
426 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
427 * Most of the global variables have been moved to a new
428 * struct configuration_spec, accessed through csp->config->globalname
429 * Most of the globals remaining are used by the Win32 GUI.
431 * Revision 1.4 2001/05/22 18:46:04 oes
433 * - Enabled filtering banners by size rather than URL
434 * by adding patterns that replace all standard banner
435 * sizes with the "Junkbuster" gif to the re_filterfile
437 * - Enabled filtering WebBugs by providing a pattern
438 * which kills all 1x1 images
440 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
441 * which is selected by the (nonstandard and therefore
442 * capital) letter 'U' in the option string.
443 * It causes the quantifiers to be ungreedy by default.
444 * Appending a ? turns back to greedy (!).
446 * - Added a new interceptor ijb-send-banner, which
447 * sends back the "Junkbuster" gif. Without imagelist or
448 * MSIE detection support, or if tinygif = 1, or the
449 * URL isn't recognized as an imageurl, a lame HTML
450 * explanation is sent instead.
452 * - Added new feature, which permits blocking remote
453 * script redirects and firing back a local redirect
455 * The feature is conditionally compiled, i.e. it
456 * can be disabled with --disable-fast-redirects,
457 * plus it must be activated by a "fast-redirects"
458 * line in the config file, has its own log level
459 * and of course wants to be displayed by show-proxy-args
460 * Note: Boy, all the #ifdefs in 1001 locations and
461 * all the fumbling with configure.in and acconfig.h
462 * were *way* more work than the feature itself :-(
464 * - Because a generic redirect template was needed for
465 * this, tinygif = 3 now uses the same.
467 * - Moved GIFs, and other static HTTP response templates
472 * - Removed some >400 CRs again (Jon, you really worked
475 * Revision 1.3 2001/05/20 01:21:20 jongfoster
476 * Version 2.9.4 checkin.
477 * - Merged popupfile and cookiefile, and added control over PCRS
478 * filtering, in new "permissionsfile".
479 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
480 * file error you now get a message box (in the Win32 GUI) rather
481 * than the program exiting with no explanation.
482 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
484 * - Removed tabs from "config"
485 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
486 * - Bumped up version number.
488 * Revision 1.2 2001/05/17 23:02:36 oes
489 * - Made referrer option accept 'L' as a substitute for '§'
491 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
492 * Initial import of version 2.9.3 source tree
495 *********************************************************************/
502 #include <sys/types.h>
511 #if !defined(_WIN32) && !defined(__OS2__)
520 /* jcc.h is for mutex semapores only */
521 #endif /* def OSX_DARWIN */
527 #include "jbsockets.h"
528 #include "miscutil.h"
531 #ifndef HAVE_STRPTIME
532 #include "strptime.h"
535 const char parsers_h_rcs[] = PARSERS_H_VERSION;
537 /* Fix a problem with Solaris. There should be no effect on other
539 * Solaris's isspace() is a macro which uses it's argument directly
540 * as an array index. Therefore we need to make sure that high-bit
541 * characters generate +ve values, and ideally we also want to make
542 * the argument match the declared parameter type of "int".
544 * Why did they write a character function that can't take a simple
545 * "char" argument? Doh!
547 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
548 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
551 const struct parsers client_patterns[] = {
552 { "referer:", 8, client_referrer },
553 { "user-agent:", 11, client_uagent },
554 { "ua-", 3, client_ua },
555 { "from:", 5, client_from },
556 { "cookie:", 7, client_send_cookie },
557 { "x-forwarded-for:", 16, client_x_forwarded },
558 { "Accept-Encoding:", 16, client_accept_encoding },
559 { "TE:", 3, client_te },
560 { "Host:", 5, client_host },
561 { "if-modified-since:", 18, client_if_modified_since },
562 { "Keep-Alive:", 11, crumble },
563 { "connection:", 11, crumble },
564 { "proxy-connection:", 17, crumble },
565 { "max-forwards:", 13, client_max_forwards },
566 { "Accept-Language:", 16, client_accept_language },
567 { "if-none-match:", 14, client_if_none_match },
568 { "X-Filter:", 9, client_x_filter },
569 { "*", 0, crunch_client_header },
570 { "*", 0, filter_client_header },
574 const struct parsers server_patterns[] = {
575 { "HTTP", 4, server_http },
576 { "set-cookie:", 11, server_set_cookie },
577 { "connection:", 11, crumble },
578 { "Content-Type:", 13, server_content_type },
579 { "Content-Length:", 15, server_content_length },
580 { "Content-MD5:", 12, server_content_md5 },
581 { "Content-Encoding:", 17, server_content_encoding },
582 { "Transfer-Encoding:", 18, server_transfer_coding },
583 { "Keep-Alive:", 11, crumble },
584 { "content-disposition:", 20, server_content_disposition },
585 { "Last-Modified:", 14, server_last_modified },
586 { "*", 0, crunch_server_header },
587 { "*", 0, filter_server_header },
591 const struct parsers server_patterns_light[] = {
592 { "Content-Length:", 15, server_content_length },
593 { "Transfer-Encoding:", 18, server_transfer_coding },
597 const add_header_func_ptr add_client_headers[] = {
600 client_x_forwarded_adder,
602 /* Temporarily disabled: client_accept_encoding_adder, */
603 connection_close_adder,
608 const add_header_func_ptr add_server_headers[] = {
609 connection_close_adder,
613 /*********************************************************************
615 * Function : flush_socket
617 * Description : Write any pending "buffered" content.
620 * 1 : fd = file descriptor of the socket to read
621 * 2 : csp = Current client state (buffers, headers, etc...)
623 * Returns : On success, the number of bytes written are returned (zero
624 * indicates nothing was written). On error, -1 is returned,
625 * and errno is set appropriately. If count is zero and the
626 * file descriptor refers to a regular file, 0 will be
627 * returned without causing any other effect. For a special
628 * file, the results are not portable.
630 *********************************************************************/
631 int flush_socket(jb_socket fd, struct client_state *csp)
633 struct iob *iob = csp->iob;
634 int len = iob->eod - iob->cur;
641 if (write_socket(fd, iob->cur, (size_t)len))
645 iob->eod = iob->cur = iob->buf;
651 /*********************************************************************
653 * Function : add_to_iob
655 * Description : Add content to the buffered page, expanding the
656 * buffer if necessary.
659 * 1 : csp = Current client state (buffers, headers, etc...)
660 * 2 : buf = holds the content to be added to the page
661 * 3 : n = number of bytes to be added
663 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
664 * or buffer limit reached.
666 *********************************************************************/
667 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
669 struct iob *iob = csp->iob;
670 size_t used, offset, need, want;
673 if (n <= 0) return JB_ERR_OK;
675 used = iob->eod - iob->buf;
676 offset = iob->cur - iob->buf;
680 * If the buffer can't hold the new data, extend it first.
681 * Use the next power of two if possible, else use the actual need.
683 if (need > csp->config->buffer_limit)
685 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
686 return JB_ERR_MEMORY;
689 if (need > iob->size)
691 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
693 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
697 else if (NULL != (p = (char *)realloc(iob->buf, need)))
703 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
704 return JB_ERR_MEMORY;
707 /* Update the iob pointers */
708 iob->cur = p + offset;
713 /* copy the new data into the iob buffer */
714 memcpy(iob->eod, buf, (size_t)n);
716 /* point to the end of the data */
719 /* null terminate == cheap insurance */
727 /*********************************************************************
729 * Function : get_header
731 * Description : This (odd) routine will parse the csp->iob
734 * 1 : csp = Current client state (buffers, headers, etc...)
736 * Returns : Any one of the following:
738 * 1) a pointer to a dynamically allocated string that contains a header line
739 * 2) NULL indicating that the end of the header was reached
740 * 3) "" indicating that the end of the iob was reached before finding
741 * a complete header line.
743 *********************************************************************/
744 char *get_header(struct client_state *csp)
750 if ((iob->cur == NULL)
751 || ((p = strchr(iob->cur, '\n')) == NULL))
753 return(""); /* couldn't find a complete header */
758 ret = strdup(iob->cur);
761 /* FIXME No way to handle error properly */
762 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
767 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
769 /* is this a blank line (i.e. the end of the header) ? */
781 /*********************************************************************
783 * Function : get_header_value
785 * Description : Get the value of a given header from a chained list
786 * of header lines or return NULL if no such header is
787 * present in the list.
790 * 1 : header_list = pointer to list
791 * 2 : header_name = string with name of header to look for.
792 * Trailing colon required, capitalization
795 * Returns : NULL if not found, else value of header
797 *********************************************************************/
798 char *get_header_value(const struct list *header_list, const char *header_name)
800 struct list_entry *cur_entry;
806 length = strlen(header_name);
808 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
812 if (!strncmpic(cur_entry->str, header_name, length))
815 * Found: return pointer to start of value
817 ret = (char *) (cur_entry->str + length);
818 while (*ret && ijb_isspace(*ret)) ret++;
831 /*********************************************************************
835 * Description : add, delete or modify lines in the HTTP header streams.
836 * On entry, it receives a linked list of headers space
837 * that was allocated dynamically (both the list nodes
838 * and the header contents).
840 * As a side effect it frees the space used by the original
844 * 1 : pats = list of patterns to match against headers
845 * 2 : more_headers = list of functions to add more
846 * headers (client or server)
847 * 3 : csp = Current client state (buffers, headers, etc...)
849 * Returns : Single pointer to a fully formed header, or NULL
850 * on out-of-memory error.
852 *********************************************************************/
853 char *sed(const struct parsers pats[],
854 const add_header_func_ptr more_headers[],
855 struct client_state *csp)
857 struct list_entry *p;
858 const struct parsers *v;
859 const add_header_func_ptr *f;
860 jb_err err = JB_ERR_OK;
864 * If filtering is enabled, sed is run twice,
865 * but most of the work needs to be done only once.
867 first_run = (more_headers != NULL ) ? 1 : 0;
869 if (first_run) /* Parse and print */
871 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
873 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
875 /* Header crunch()ed in previous run? -> ignore */
876 if (p->str == NULL) continue;
878 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
880 /* Does the current parser handle this header? */
881 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
883 err = v->parser(csp, (char **)&(p->str));
887 /* place any additional headers on the csp->headers list */
888 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
893 else /* Parse only */
896 * The second run is only needed if the body was modified
897 * and the content-lenght has changed.
899 if (strncmpic(csp->http->cmd, "HEAD", 4))
901 /*XXX: Code duplication*/
902 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
904 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
906 /* Header crunch()ed in previous run? -> ignore */
907 if (p->str == NULL) continue;
909 /* Does the current parser handle this header? */
910 if (strncmpic(p->str, v->str, v->len) == 0)
912 err = v->parser(csp, (char **)&(p->str));
919 if (err != JB_ERR_OK)
924 return list_to_text(csp->headers);
928 /* here begins the family of parser functions that reformat header lines */
930 /*********************************************************************
932 * Function : filter_server_header
934 * Description : Checks if server header filtering is enabled.
935 * If it is, filter_header is called to do the work.
938 * 1 : csp = Current client state (buffers, headers, etc...)
939 * 2 : header = On input, pointer to header to modify.
940 * On output, pointer to the modified header, or NULL
941 * to remove the header. This function frees the
942 * original string if necessary.
944 * Returns : JB_ERR_OK on success and always succeeds
946 *********************************************************************/
947 jb_err filter_server_header(struct client_state *csp, char **header)
949 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
951 filter_header(csp, header);
956 /*********************************************************************
958 * Function : filter_client_header
960 * Description : Checks if client header filtering is enabled.
961 * If it is, filter_header is called to do the work.
964 * 1 : csp = Current client state (buffers, headers, etc...)
965 * 2 : header = On input, pointer to header to modify.
966 * On output, pointer to the modified header, or NULL
967 * to remove the header. This function frees the
968 * original string if necessary.
970 * Returns : JB_ERR_OK on success and always succeeds
972 *********************************************************************/
973 jb_err filter_client_header(struct client_state *csp, char **header)
975 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
977 filter_header(csp, header);
982 /*********************************************************************
984 * Function : filter_header
986 * Description : Executes all text substitutions from all applying
987 * +filter actions on the header.
988 * Most of the code was copied from pcrs_filter_response,
989 * including the rather short variable names
992 * 1 : csp = Current client state (buffers, headers, etc...)
993 * 2 : header = On input, pointer to header to modify.
994 * On output, pointer to the modified header, or NULL
995 * to remove the header. This function frees the
996 * original string if necessary.
998 * Returns : JB_ERR_OK on success and always succeeds
1000 *********************************************************************/
1001 jb_err filter_header(struct client_state *csp, char **header)
1005 size_t size = strlen(*header);
1007 char *newheader = NULL;
1010 struct file_list *fl;
1011 struct re_filterfile_spec *b;
1012 struct list_entry *filtername;
1014 int i, found_filters = 0;
1016 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
1018 * Need to check the set of re_filterfiles...
1020 for (i = 0; i < MAX_AF_FILES; i++)
1033 if (0 == found_filters)
1035 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1039 for (i = 0; i < MAX_AF_FILES; i++)
1042 if ((NULL == fl) || (NULL == fl->f))
1045 * For all applying +filter actions, look if a filter by that
1046 * name exists and if yes, execute its pcrs_joblist on the
1049 for (b = fl->f; b; b = b->next)
1051 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1052 filtername ; filtername = filtername->next)
1054 if (strcmp(b->name, filtername->str) == 0)
1056 int current_hits = 0;
1058 if ( NULL == b->joblist )
1060 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1064 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1065 *header, size, b->name);
1067 /* Apply all jobs from the joblist */
1068 for (job = b->joblist; NULL != job; job = job->next)
1070 matches = pcrs_execute(job, *header, size, &newheader, &size);
1073 current_hits += matches;
1074 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1076 *header = newheader;
1078 else if ( 0 == matches )
1080 /* Filter doesn't change header */
1086 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1087 *header, b->name, pcrs_strerror(matches));
1088 if( newheader != NULL)
1090 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1095 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1096 hits += current_hits;
1104 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1107 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1113 /*********************************************************************
1115 * Function : crumble
1117 * Description : This is called if a header matches a pattern to "crunch"
1120 * 1 : csp = Current client state (buffers, headers, etc...)
1121 * 2 : header = On input, pointer to header to modify.
1122 * On output, pointer to the modified header, or NULL
1123 * to remove the header. This function frees the
1124 * original string if necessary.
1126 * Returns : JB_ERR_OK on success, or
1127 * JB_ERR_MEMORY on out-of-memory error.
1129 *********************************************************************/
1130 jb_err crumble(struct client_state *csp, char **header)
1132 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1137 /*********************************************************************
1139 * Function : crunch_server_header
1141 * Description : Crunch server header if it matches a string supplied by the
1142 * user. Called from `sed'.
1145 * 1 : csp = Current client state (buffers, headers, etc...)
1146 * 2 : header = On input, pointer to header to modify.
1147 * On output, pointer to the modified header, or NULL
1148 * to remove the header. This function frees the
1149 * original string if necessary.
1151 * Returns : JB_ERR_OK on success and always succeeds
1153 *********************************************************************/
1154 jb_err crunch_server_header(struct client_state *csp, char **header)
1156 const char *crunch_pattern;
1157 /*Is there a header to crunch*/
1159 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1161 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1163 /*Is the current header the lucky one?*/
1164 if (strstr(*header, crunch_pattern))
1166 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1173 /*********************************************************************
1175 * Function : server_content_type
1177 * Description : Set the content-type for filterable types (text/.*,
1178 * javascript and image/gif) unless filtering has been
1179 * forbidden (CT_TABOO) while parsing earlier headers.
1180 * NOTE: Since text/plain is commonly used by web servers
1181 * for files whose correct type is unknown, we don't
1182 * set CT_TEXT for it.
1185 * 1 : csp = Current client state (buffers, headers, etc...)
1186 * 2 : header = On input, pointer to header to modify.
1187 * On output, pointer to the modified header, or NULL
1188 * to remove the header. This function frees the
1189 * original string if necessary.
1191 * Returns : JB_ERR_OK on success, or
1192 * JB_ERR_MEMORY on out-of-memory error.
1194 *********************************************************************/
1195 jb_err server_content_type(struct client_state *csp, char **header)
1199 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1201 if (csp->content_type != CT_TABOO)
1203 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1204 || strstr(*header, "xml")
1205 || strstr(*header, "application/x-javascript"))
1206 csp->content_type = CT_TEXT;
1207 else if (strstr(*header, " image/gif"))
1208 csp->content_type = CT_GIF;
1209 else if (strstr(*header, " image/jpeg"))
1210 csp->content_type = CT_JPEG;
1212 csp->content_type = 0;
1215 * Are we enabling text mode by force?
1217 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1220 * Do we really have to?
1222 if (csp->content_type == CT_TEXT)
1224 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1228 csp->content_type = CT_TEXT;
1229 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1233 * Are we messing with the content type?
1235 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1238 * Make sure the user doesn't accidently
1239 * change the content type of binary documents.
1241 if (csp->content_type == CT_TEXT)
1244 *header = strdup("Content-Type: ");
1245 string_append(header, newval);
1249 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1250 return JB_ERR_MEMORY;
1252 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1256 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1257 "Enable force-text-mode if you know what you're doing.", *header);
1264 /*********************************************************************
1266 * Function : server_transfer_coding
1268 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1269 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1270 * - Remove header if body was chunked but has been
1271 * de-chunked for filtering.
1274 * 1 : csp = Current client state (buffers, headers, etc...)
1275 * 2 : header = On input, pointer to header to modify.
1276 * On output, pointer to the modified header, or NULL
1277 * to remove the header. This function frees the
1278 * original string if necessary.
1280 * Returns : JB_ERR_OK on success, or
1281 * JB_ERR_MEMORY on out-of-memory error.
1283 *********************************************************************/
1284 jb_err server_transfer_coding(struct client_state *csp, char **header)
1287 * Turn off pcrs and gif filtering if body compressed
1289 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1291 csp->content_type = CT_TABOO;
1295 * Raise flag if body chunked
1297 if (strstr(*header, "chunked"))
1299 csp->flags |= CSP_FLAG_CHUNKED;
1302 * If the body was modified, it has been de-chunked first
1303 * and the header must be removed.
1305 if (csp->flags & CSP_FLAG_MODIFIED)
1307 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1316 /*********************************************************************
1318 * Function : server_content_encoding
1320 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1323 * 1 : csp = Current client state (buffers, headers, etc...)
1324 * 2 : header = On input, pointer to header to modify.
1325 * On output, pointer to the modified header, or NULL
1326 * to remove the header. This function frees the
1327 * original string if necessary.
1329 * Returns : JB_ERR_OK on success, or
1330 * JB_ERR_MEMORY on out-of-memory error.
1332 *********************************************************************/
1333 jb_err server_content_encoding(struct client_state *csp, char **header)
1336 * Turn off pcrs and gif filtering if body compressed
1338 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1340 csp->content_type = CT_TABOO;
1348 /*********************************************************************
1350 * Function : server_content_length
1352 * Description : Adjust Content-Length header if we modified
1356 * 1 : csp = Current client state (buffers, headers, etc...)
1357 * 2 : header = On input, pointer to header to modify.
1358 * On output, pointer to the modified header, or NULL
1359 * to remove the header. This function frees the
1360 * original string if necessary.
1362 * Returns : JB_ERR_OK on success, or
1363 * JB_ERR_MEMORY on out-of-memory error.
1365 *********************************************************************/
1366 jb_err server_content_length(struct client_state *csp, char **header)
1368 if (csp->content_length != 0) /* Content length could have been modified */
1371 * XXX: Shouldn't we check if csp->content_length
1372 * is different than the original value?
1375 *header = (char *) zalloc(100);
1376 if (*header == NULL)
1378 return JB_ERR_MEMORY;
1381 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1383 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1390 /*********************************************************************
1392 * Function : server_content_md5
1394 * Description : Crumble any Content-MD5 headers if the document was
1395 * modified. FIXME: Should we re-compute instead?
1398 * 1 : csp = Current client state (buffers, headers, etc...)
1399 * 2 : header = On input, pointer to header to modify.
1400 * On output, pointer to the modified header, or NULL
1401 * to remove the header. This function frees the
1402 * original string if necessary.
1404 * Returns : JB_ERR_OK on success, or
1405 * JB_ERR_MEMORY on out-of-memory error.
1407 *********************************************************************/
1408 jb_err server_content_md5(struct client_state *csp, char **header)
1410 if (csp->flags & CSP_FLAG_MODIFIED)
1412 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1419 /*********************************************************************
1421 * Function : server_content_disposition
1423 * Description : If enabled, blocks or modifies the "content-disposition" header.
1424 * Called from `sed'.
1427 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * 2 : header = On input, pointer to header to modify.
1429 * On output, pointer to the modified header, or NULL
1430 * to remove the header. This function frees the
1431 * original string if necessary.
1433 * Returns : JB_ERR_OK on success, or
1434 * JB_ERR_MEMORY on out-of-memory error.
1436 *********************************************************************/
1437 jb_err server_content_disposition(struct client_state *csp, char **header)
1442 * Are we messing with the content-disposition header?
1444 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1450 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1452 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1455 * Blocking content-disposition header
1457 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1464 * Replacing content-disposition header
1467 *header = strdup("content-disposition: ");
1468 string_append(header, newval);
1470 if (*header == NULL)
1472 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1476 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1479 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1482 /*********************************************************************
1484 * Function : server_last_modified
1486 * Description : Changes Last-Modified header to the actual date
1487 * to help hide-if-modified-since.
1488 * Called from `sed'.
1491 * 1 : csp = Current client state (buffers, headers, etc...)
1492 * 2 : header = On input, pointer to header to modify.
1493 * On output, pointer to the modified header, or NULL
1494 * to remove the header. This function frees the
1495 * original string if necessary.
1497 * Returns : JB_ERR_OK on success, or
1498 * JB_ERR_MEMORY on out-of-memory error.
1500 *********************************************************************/
1501 jb_err server_last_modified(struct client_state *csp, char **header)
1504 char buf[BUFFER_SIZE];
1507 #ifdef HAVE_GMTIME_R
1510 struct tm *timeptr = NULL;
1511 time_t now, last_modified;
1513 long int days, hours, minutes, seconds;
1516 * Are we messing with the Last-Modified header?
1518 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1524 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1526 if (0 == strcmpic(newval, "block") )
1529 * Blocking Last-Modified header. Useless but why not.
1531 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1535 else if (0 == strcmpic(newval, "reset-to-request-time"))
1538 * Setting Last-Modified Header to now.
1540 get_http_time(0, buf);
1542 *header = strdup("Last-Modified: ");
1543 string_append(header, buf);
1545 if (*header == NULL)
1547 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1551 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1554 else if (0 == strcmpic(newval, "randomize"))
1556 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1558 #ifdef HAVE_GMTIME_R
1559 timeptr = gmtime_r(&now, &gmt);
1561 pthread_mutex_lock(&gmtime_mutex);
1562 timeptr = gmtime(&now);
1563 pthread_mutex_unlock(&gmtime_mutex);
1565 timeptr = gmtime(&now);
1567 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1569 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1574 rtime = difftime(now, last_modified);
1577 rtime = pick_from_range(rtime);
1578 last_modified += rtime;
1579 #ifdef HAVE_GMTIME_R
1580 timeptr = gmtime_r(&last_modified, &gmt);
1582 pthread_mutex_lock(&gmtime_mutex);
1583 timeptr = gmtime(&last_modified);
1584 pthread_mutex_unlock(&gmtime_mutex);
1586 timeptr = gmtime(&last_modified);
1588 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1590 *header = strdup("Last-Modified: ");
1591 string_append(header, newheader);
1593 if (*header == NULL)
1595 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1596 return JB_ERR_MEMORY;
1599 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1601 days = rtime / (3600 * 24);
1602 hours = rtime / 3600 % 24;
1603 minutes = rtime / 60 % 60;
1604 seconds = rtime % 60;
1606 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1607 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1608 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1613 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1621 /*********************************************************************
1623 * Function : client_accept_encoding
1625 * Description : Rewrite the client's Accept-Encoding header so that
1626 * if doesn't allow compression, if the action applies.
1627 * Note: For HTTP/1.0 the absence of the header is enough.
1630 * 1 : csp = Current client state (buffers, headers, etc...)
1631 * 2 : header = On input, pointer to header to modify.
1632 * On output, pointer to the modified header, or NULL
1633 * to remove the header. This function frees the
1634 * original string if necessary.
1636 * Returns : JB_ERR_OK on success, or
1637 * JB_ERR_MEMORY on out-of-memory error.
1639 *********************************************************************/
1640 jb_err client_accept_encoding(struct client_state *csp, char **header)
1642 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1644 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1648 /* Temporarily disable the correct behaviour to
1649 * work around a PHP bug.
1651 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1653 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1654 * if (*header == NULL)
1656 * return JB_ERR_MEMORY;
1667 /*********************************************************************
1669 * Function : client_te
1671 * Description : Rewrite the client's TE header so that
1672 * if doesn't allow compression, if the action applies.
1675 * 1 : csp = Current client state (buffers, headers, etc...)
1676 * 2 : header = On input, pointer to header to modify.
1677 * On output, pointer to the modified header, or NULL
1678 * to remove the header. This function frees the
1679 * original string if necessary.
1681 * Returns : JB_ERR_OK on success, or
1682 * JB_ERR_MEMORY on out-of-memory error.
1684 *********************************************************************/
1685 jb_err client_te(struct client_state *csp, char **header)
1687 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1690 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1696 /*********************************************************************
1698 * Function : client_referrer
1700 * Description : Handle the "referer" config setting properly.
1701 * Called from `sed'.
1704 * 1 : csp = Current client state (buffers, headers, etc...)
1705 * 2 : header = On input, pointer to header to modify.
1706 * On output, pointer to the modified header, or NULL
1707 * to remove the header. This function frees the
1708 * original string if necessary.
1710 * Returns : JB_ERR_OK on success, or
1711 * JB_ERR_MEMORY on out-of-memory error.
1713 *********************************************************************/
1714 jb_err client_referrer(struct client_state *csp, char **header)
1721 #ifdef FEATURE_FORCE_LOAD
1722 /* Since the referrer can include the prefix even
1723 * if the request itself is non-forced, we must
1724 * clean it unconditionally
1726 strclean(*header, FORCE_PREFIX);
1727 #endif /* def FEATURE_FORCE_LOAD */
1730 * Are we sending referer?
1732 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1737 newval = csp->action->string[ACTION_STRING_REFERER];
1739 if ((0 != strcmpic(newval, "conditional-block")))
1743 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1748 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1751 else if (0 == strcmpic(newval, "conditional-block"))
1754 * Block referer if host has changed.
1757 if (NULL == (host = strdup(csp->http->hostport)))
1760 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1761 return JB_ERR_MEMORY;
1763 if (NULL == (referer = strdup(*header)))
1767 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1768 return JB_ERR_MEMORY;
1770 hostlenght = strlen(host);
1771 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1773 /*Shorten referer to make sure the referer is blocked
1774 *if www.example.org/www.example.com-shall-see-the-referer/
1775 *links to www.example.com/
1777 referer[hostlenght+17] = '\0';
1779 if ( 0 == strstr(referer, host)) /*Host has changed*/
1781 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1786 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1792 else if (0 != strcmpic(newval, "forge"))
1795 * We have a specific (fixed) referer we want to send.
1797 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1799 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1801 *header = strdup("Referer: ");
1802 string_append(header, newval);
1803 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1805 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1810 * Forge a referer as http://[hostname:port of REQUEST]/
1811 * to fool stupid checks for in-site links
1814 *header = strdup("Referer: http://");
1815 string_append(header, csp->http->hostport);
1816 string_append(header, "/");
1817 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1819 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1823 /*********************************************************************
1825 * Function : client_accept_language
1827 * Description : Handle the "Accept-Language" config setting properly.
1828 * Called from `sed'.
1831 * 1 : csp = Current client state (buffers, headers, etc...)
1832 * 2 : header = On input, pointer to header to modify.
1833 * On output, pointer to the modified header, or NULL
1834 * to remove the header. This function frees the
1835 * original string if necessary.
1837 * Returns : JB_ERR_OK on success, or
1838 * JB_ERR_MEMORY on out-of-memory error.
1840 *********************************************************************/
1841 jb_err client_accept_language(struct client_state *csp, char **header)
1846 * Are we messing with the Accept-Language?
1848 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1850 /*I don't think so*/
1854 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1856 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1859 * Blocking Accept-Language header
1861 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1868 * Replacing Accept-Language header
1871 *header = strdup("Accept-Language: ");
1872 string_append(header, newval);
1874 if (*header == NULL)
1876 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1880 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1883 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1886 /*********************************************************************
1888 * Function : crunch_client_header
1890 * Description : Crunch client header if it matches a string supplied by the
1891 * user. Called from `sed'.
1894 * 1 : csp = Current client state (buffers, headers, etc...)
1895 * 2 : header = On input, pointer to header to modify.
1896 * On output, pointer to the modified header, or NULL
1897 * to remove the header. This function frees the
1898 * original string if necessary.
1900 * Returns : JB_ERR_OK on success and always succeeds
1902 *********************************************************************/
1903 jb_err crunch_client_header(struct client_state *csp, char **header)
1905 const char *crunch_pattern;
1906 /*Is there a header to crunch*/
1908 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1910 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1912 /*Is the current header the lucky one?*/
1913 if (strstr(*header, crunch_pattern))
1915 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1923 /*********************************************************************
1925 * Function : client_uagent
1927 * Description : Handle the "user-agent" config setting properly
1928 * and remember its original value to enable browser
1929 * bug workarounds. Called from `sed'.
1932 * 1 : csp = Current client state (buffers, headers, etc...)
1933 * 2 : header = On input, pointer to header to modify.
1934 * On output, pointer to the modified header, or NULL
1935 * to remove the header. This function frees the
1936 * original string if necessary.
1938 * Returns : JB_ERR_OK on success, or
1939 * JB_ERR_MEMORY on out-of-memory error.
1941 *********************************************************************/
1942 jb_err client_uagent(struct client_state *csp, char **header)
1946 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1951 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1958 *header = strdup("User-Agent: ");
1959 string_append(header, newval);
1961 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1963 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1966 /*********************************************************************
1968 * Function : client_ua
1970 * Description : Handle "ua-" headers properly. Called from `sed'.
1973 * 1 : csp = Current client state (buffers, headers, etc...)
1974 * 2 : header = On input, pointer to header to modify.
1975 * On output, pointer to the modified header, or NULL
1976 * to remove the header. This function frees the
1977 * original string if necessary.
1979 * Returns : JB_ERR_OK on success, or
1980 * JB_ERR_MEMORY on out-of-memory error.
1982 *********************************************************************/
1983 jb_err client_ua(struct client_state *csp, char **header)
1985 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1987 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1995 /*********************************************************************
1997 * Function : client_from
1999 * Description : Handle the "from" config setting properly.
2000 * Called from `sed'.
2003 * 1 : csp = Current client state (buffers, headers, etc...)
2004 * 2 : header = On input, pointer to header to modify.
2005 * On output, pointer to the modified header, or NULL
2006 * to remove the header. This function frees the
2007 * original string if necessary.
2009 * Returns : JB_ERR_OK on success, or
2010 * JB_ERR_MEMORY on out-of-memory error.
2012 *********************************************************************/
2013 jb_err client_from(struct client_state *csp, char **header)
2017 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2024 newval = csp->action->string[ACTION_STRING_FROM];
2027 * Are we blocking the e-mail address?
2029 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2031 log_error(LOG_LEVEL_HEADER, "crunched From!");
2035 log_error(LOG_LEVEL_HEADER, " modified");
2037 *header = strdup("From: ");
2038 string_append(header, newval);
2040 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2044 /*********************************************************************
2046 * Function : client_send_cookie
2048 * Description : Handle the "cookie" header properly. Called from `sed'.
2049 * If cookie is accepted, add it to the cookie_list,
2050 * else we crunch it. Mmmmmmmmmmm ... cookie ......
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_send_cookie(struct client_state *csp, char **header)
2065 jb_err result = JB_ERR_OK;
2067 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2069 /* strlen("cookie: ") == 8 */
2070 result = enlist(csp->cookie_list, *header + 8);
2074 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2078 * Always remove the cookie here. The cookie header
2079 * will be sent at the end of the header.
2087 /*********************************************************************
2089 * Function : client_x_forwarded
2091 * Description : Handle the "x-forwarded-for" config setting properly,
2092 * also used in the add_client_headers list. Called from `sed'.
2095 * 1 : csp = Current client state (buffers, headers, etc...)
2096 * 2 : header = On input, pointer to header to modify.
2097 * On output, pointer to the modified header, or NULL
2098 * to remove the header. This function frees the
2099 * original string if necessary.
2101 * Returns : JB_ERR_OK on success, or
2102 * JB_ERR_MEMORY on out-of-memory error.
2104 *********************************************************************/
2105 jb_err client_x_forwarded(struct client_state *csp, char **header)
2107 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2109 /* Save it so we can re-add it later */
2110 freez(csp->x_forwarded);
2111 csp->x_forwarded = *header;
2114 * Always set *header = NULL, since this information
2115 * will be sent at the end of the header.
2122 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2129 /*********************************************************************
2131 * Function : client_max_forwards
2133 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2134 * from the value of the Max-Forwards header field.
2137 * 1 : csp = Current client state (buffers, headers, etc...)
2138 * 2 : header = On input, pointer to header to modify.
2139 * On output, pointer to the modified header, or NULL
2140 * to remove the header. This function frees the
2141 * original string if necessary.
2143 * Returns : JB_ERR_OK on success, or
2144 * JB_ERR_MEMORY on out-of-memory error.
2146 *********************************************************************/
2147 jb_err client_max_forwards(struct client_state *csp, char **header)
2149 unsigned int max_forwards;
2151 if ((0 == strcmpic(csp->http->gpc, "trace"))
2152 || (0 == strcmpic(csp->http->gpc, "options")))
2154 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2156 if (max_forwards-- >= 1)
2158 sprintf(*header, "Max-Forwards: %u", max_forwards);
2159 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2163 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2172 /*********************************************************************
2174 * Function : client_host
2176 * Description : If the request URI did not contain host and
2177 * port information, parse and evaluate the Host
2180 * Also, kill ill-formed HOST: headers as sent by
2181 * Apple's iTunes software when used with a proxy.
2184 * 1 : csp = Current client state (buffers, headers, etc...)
2185 * 2 : header = On input, pointer to header to modify.
2186 * On output, pointer to the modified header, or NULL
2187 * to remove the header. This function frees the
2188 * original string if necessary.
2190 * Returns : JB_ERR_OK on success, or
2191 * JB_ERR_MEMORY on out-of-memory error.
2193 *********************************************************************/
2194 jb_err client_host(struct client_state *csp, char **header)
2199 * If the header field name is all upper-case, chances are that it's
2200 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2201 * not a problem -- they are regenerated later.
2203 if ((*header)[1] == 'O')
2205 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2210 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2211 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2214 if (NULL == (p = strdup((*header)+6)))
2216 return JB_ERR_MEMORY;
2219 if (NULL == (q = strdup(p)))
2222 return JB_ERR_MEMORY;
2225 freez(csp->http->hostport);
2226 csp->http->hostport = p;
2227 freez(csp->http->host);
2228 csp->http->host = q;
2229 q = strchr(csp->http->host, ':');
2232 /* Terminate hostname and evaluate port string */
2234 csp->http->port = atoi(q);
2238 csp->http->port = csp->http->ssl ? 443 : 80;
2241 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2242 csp->http->hostport, csp->http->host, csp->http->port);
2248 /*********************************************************************
2250 * Function : client_if_modified_since
2252 * Description : Remove or modify the If-Modified-Since header.
2255 * 1 : csp = Current client state (buffers, headers, etc...)
2256 * 2 : header = On input, pointer to header to modify.
2257 * On output, pointer to the modified header, or NULL
2258 * to remove the header. This function frees the
2259 * original string if necessary.
2261 * Returns : JB_ERR_OK on success, or
2262 * JB_ERR_MEMORY on out-of-memory error.
2264 *********************************************************************/
2265 jb_err client_if_modified_since(struct client_state *csp, char **header)
2268 #ifdef HAVE_GMTIME_R
2271 struct tm *timeptr = NULL;
2275 long int hours, minutes, seconds;
2279 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2282 * The client got an error message because of a temporary problem,
2283 * the problem is gone and the client now tries to revalidate our
2284 * error message on the real server. The revalidation would always
2285 * end with the transmission of the whole document and there is
2286 * no need to expose the bogus If-Modified-Since header.
2288 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2291 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2293 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2295 if ((0 == strcmpic(newval, "block")))
2297 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2300 else /* add random value */
2302 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2304 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2309 rtime = strtol(newval, &endptr, 0);
2317 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2318 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2320 rtime = pick_from_range(rtime);
2324 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2328 #ifdef HAVE_GMTIME_R
2329 timeptr = gmtime_r(&tm, &gmt);
2331 pthread_mutex_lock(&gmtime_mutex);
2332 timeptr = gmtime(&tm);
2333 pthread_mutex_unlock(&gmtime_mutex);
2335 timeptr = gmtime(&tm);
2337 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2340 *header = strdup("If-Modified-Since: ");
2341 string_append(header, newheader);
2343 if (*header == NULL)
2345 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2346 return JB_ERR_MEMORY;
2349 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2351 hours = rtime / 3600;
2352 minutes = rtime / 60 % 60;
2353 seconds = rtime % 60;
2355 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2356 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2357 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2366 /*********************************************************************
2368 * Function : client_if_none_match
2370 * Description : Remove the If-None-Match header.
2373 * 1 : csp = Current client state (buffers, headers, etc...)
2374 * 2 : header = On input, pointer to header to modify.
2375 * On output, pointer to the modified header, or NULL
2376 * to remove the header. This function frees the
2377 * original string if necessary.
2379 * Returns : JB_ERR_OK on success, or
2380 * JB_ERR_MEMORY on out-of-memory error.
2382 *********************************************************************/
2383 jb_err client_if_none_match(struct client_state *csp, char **header)
2385 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2387 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2394 /*********************************************************************
2396 * Function : client_x_filter
2398 * Description : Disables filtering if the client set "X-Filter: No".
2399 * Called from `sed'.
2402 * 1 : csp = Current client state (buffers, headers, etc...)
2403 * 2 : header = On input, pointer to header to modify.
2404 * On output, pointer to the modified header, or NULL
2405 * to remove the header. This function frees the
2406 * original string if necessary.
2408 * Returns : JB_ERR_OK on success
2410 *********************************************************************/
2411 jb_err client_x_filter(struct client_state *csp, char **header)
2413 if ( 0 == strcmpic(*header, "X-Filter: No"))
2415 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2417 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2421 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2423 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2427 csp->content_type = CT_TABOO;
2428 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2430 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2437 /* the following functions add headers directly to the header list */
2439 /*********************************************************************
2441 * Function : client_host_adder
2443 * Description : Adds the Host: header field if it is missing.
2444 * Called from `sed'.
2447 * 1 : csp = Current client state (buffers, headers, etc...)
2449 * Returns : JB_ERR_OK on success, or
2450 * JB_ERR_MEMORY on out-of-memory error.
2452 *********************************************************************/
2453 jb_err client_host_adder(struct client_state *csp)
2458 if ( !csp->http->hostport || !*(csp->http->hostport))
2464 * remove 'user:pass@' from 'proto://user:pass@host'
2466 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2472 p = csp->http->hostport;
2475 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2476 err = enlist_unique_header(csp->headers, "Host", p);
2482 /*********************************************************************
2484 * Function : client_cookie_adder
2486 * Description : Used in the add_client_headers list. Called from `sed'.
2489 * 1 : csp = Current client state (buffers, headers, etc...)
2491 * Returns : JB_ERR_OK on success, or
2492 * JB_ERR_MEMORY on out-of-memory error.
2494 *********************************************************************/
2495 jb_err client_cookie_adder(struct client_state *csp)
2497 struct list_entry *lst;
2499 struct list_entry *list1 = csp->cookie_list->first;
2500 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2501 int first_cookie = 1;
2504 if ((list1 == NULL) && (list2 == NULL))
2510 tmp = strdup("Cookie: ");
2512 for (lst = list1; lst ; lst = lst->next)
2520 string_append(&tmp, "; ");
2522 string_append(&tmp, lst->str);
2525 for (lst = list2; lst ; lst = lst->next)
2533 string_append(&tmp, "; ");
2535 string_join(&tmp, cookie_encode(lst->str));
2540 return JB_ERR_MEMORY;
2543 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2544 err = enlist(csp->headers, tmp);
2550 /*********************************************************************
2552 * Function : client_accept_encoding_adder
2554 * Description : Add an Accept-Encoding header to the client's request
2555 * that disables compression if the action applies, and
2556 * the header is not already there. Called from `sed'.
2557 * Note: For HTTP/1.0, the absence of the header is enough.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2562 * Returns : JB_ERR_OK on success, or
2563 * JB_ERR_MEMORY on out-of-memory error.
2565 *********************************************************************/
2566 jb_err client_accept_encoding_adder(struct client_state *csp)
2568 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2569 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2571 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2578 /*********************************************************************
2580 * Function : client_xtra_adder
2582 * Description : Used in the add_client_headers list. Called from `sed'.
2585 * 1 : csp = Current client state (buffers, headers, etc...)
2587 * Returns : JB_ERR_OK on success, or
2588 * JB_ERR_MEMORY on out-of-memory error.
2590 *********************************************************************/
2591 jb_err client_xtra_adder(struct client_state *csp)
2593 struct list_entry *lst;
2596 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2597 lst ; lst = lst->next)
2599 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2600 err = enlist(csp->headers, lst->str);
2612 /*********************************************************************
2614 * Function : client_x_forwarded_adder
2616 * Description : Used in the add_client_headers list. Called from `sed'.
2619 * 1 : csp = Current client state (buffers, headers, etc...)
2621 * Returns : JB_ERR_OK on success, or
2622 * JB_ERR_MEMORY on out-of-memory error.
2624 *********************************************************************/
2625 jb_err client_x_forwarded_adder(struct client_state *csp)
2630 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2635 if (csp->x_forwarded)
2637 p = strdup(csp->x_forwarded);
2638 string_append(&p, ", ");
2642 p = strdup("X-Forwarded-For: ");
2644 string_append(&p, csp->ip_addr_str);
2648 return JB_ERR_MEMORY;
2651 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2652 err = enlist(csp->headers, p);
2659 /*********************************************************************
2661 * Function : connection_close_adder
2663 * Description : Adds a "Connection: close" header to csp->headers
2664 * as a temporary fix for the needed but missing HTTP/1.1
2665 * support. Called from `sed'.
2666 * FIXME: This whole function shouldn't be neccessary!
2669 * 1 : csp = Current client state (buffers, headers, etc...)
2671 * Returns : JB_ERR_OK on success, or
2672 * JB_ERR_MEMORY on out-of-memory error.
2674 *********************************************************************/
2675 jb_err connection_close_adder(struct client_state *csp)
2677 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2678 return enlist(csp->headers, "Connection: close");
2682 /*********************************************************************
2684 * Function : server_http
2686 * Description : - Save the HTTP Status into csp->http->status
2687 * - Set CT_TABOO to prevent filtering if the answer
2688 * is a partial range (HTTP status 206)
2689 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2693 * 1 : csp = Current client state (buffers, headers, etc...)
2694 * 2 : header = On input, pointer to header to modify.
2695 * On output, pointer to the modified header, or NULL
2696 * to remove the header. This function frees the
2697 * original string if necessary.
2699 * Returns : JB_ERR_OK on success, or
2700 * JB_ERR_MEMORY on out-of-memory error.
2702 *********************************************************************/
2703 jb_err server_http(struct client_state *csp, char **header)
2705 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2706 if (csp->http->status == 206)
2708 csp->content_type = CT_TABOO;
2711 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2714 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2721 /*********************************************************************
2723 * Function : server_set_cookie
2725 * Description : Handle the server "cookie" header properly.
2726 * Log cookie to the jar file. Then "crunch" it,
2727 * or accept it. Called from `sed'.
2730 * 1 : csp = Current client state (buffers, headers, etc...)
2731 * 2 : header = On input, pointer to header to modify.
2732 * On output, pointer to the modified header, or NULL
2733 * to remove the header. This function frees the
2734 * original string if necessary.
2736 * Returns : JB_ERR_OK on success, or
2737 * JB_ERR_MEMORY on out-of-memory error.
2739 *********************************************************************/
2740 jb_err server_set_cookie(struct client_state *csp, char **header)
2742 #ifdef FEATURE_COOKIE_JAR
2743 if (csp->config->jar)
2746 * Write timestamp into outbuf.
2748 * Complex because not all OSs have tm_gmtoff or
2749 * the %z field in strftime()
2751 char tempbuf[ BUFFER_SIZE ];
2755 #ifdef HAVE_LOCALTIME_R
2756 tm_now = *localtime_r(&now, &tm_now);
2758 pthread_mutex_lock(&localtime_mutex);
2759 tm_now = *localtime (&now);
2760 pthread_mutex_unlock(&localtime_mutex);
2762 tm_now = *localtime (&now);
2764 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2766 /* strlen("set-cookie: ") = 12 */
2767 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2769 #endif /* def FEATURE_COOKIE_JAR */
2771 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2773 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2774 return crumble(csp, header);
2776 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2778 /* Flag whether or not to log a message */
2781 /* A variable to store the tag we're working on */
2784 /* Skip "Set-Cookie:" (11 characters) in header */
2785 cur_tag = *header + 11;
2787 /* skip whitespace between "Set-Cookie:" and value */
2788 while (*cur_tag && ijb_isspace(*cur_tag))
2793 /* Loop through each tag in the cookie */
2797 char *next_tag = strchr(cur_tag, ';');
2798 if (next_tag != NULL)
2800 /* Skip the ';' character itself */
2803 /* skip whitespace ";" and start of tag */
2804 while (*next_tag && ijb_isspace(*next_tag))
2811 /* "Next tag" is the end of the string */
2812 next_tag = cur_tag + strlen(cur_tag);
2815 /* Is this the "Expires" tag? */
2816 if (strncmpic(cur_tag, "expires=", 8) == 0)
2818 /* Delete the tag by copying the rest of the string over it.
2819 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2820 * since the behaviour of strcpy is undefined for overlapping
2823 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2825 /* That changed the header, need to issue a log message */
2828 /* Note that the next tag has now been moved to *cur_tag,
2829 * so we do not need to update the cur_tag pointer.
2834 /* Move on to next cookie tag */
2841 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2849 #ifdef FEATURE_FORCE_LOAD
2850 /*********************************************************************
2852 * Function : strclean
2854 * Description : In-Situ-Eliminate all occurances of substring in
2858 * 1 : string = string to clean
2859 * 2 : substring = substring to eliminate
2861 * Returns : Number of eliminations
2863 *********************************************************************/
2864 int strclean(const char *string, const char *substring)
2866 int hits = 0, len = strlen(substring);
2869 while((pos = strstr(string, substring)) != NULL)
2876 while (*p++ != '\0');
2883 #endif /* def FEATURE_FORCE_LOAD */
2885 /*********************************************************************
2887 * Function : parse_header_time
2889 * Description : Transforms time inside a HTTP header into
2890 * the usual time format.
2893 * 1 : header = header to parse
2894 * 2 : tm = storage for the resulting time in seconds
2896 * Returns : Time struct containing the header time, or
2897 * NULL in case of a parsing problem.
2899 *********************************************************************/
2900 struct tm *parse_header_time(char *header, time_t *tm) {
2904 struct tm * timeptr;
2906 /* Skipping header name */
2907 timestring = strstr(header, ": ");
2908 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)