1 const char parsers_rcs[] = "$Id: parsers.c,v 1.67 2006/09/04 11:01:26 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.67 2006/09/04 11:01:26 fabiankeil
44 * After filtering de-chunked instances, remove
45 * "Transfer-Encoding" header entirely instead of changing
46 * it to "Transfer-Encoding: identity", which is invalid.
47 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
49 * Don't use localtime in parse_header_time. An empty time struct
50 * is good enough, it gets overwritten by strptime anyway.
52 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
53 * Use gmtime_r if available, fallback to gmtime with mutex
54 * protection for MacOSX and use vanilla gmtime for the rest.
56 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
57 * Changed client_referrer to use the right type (size_t) for
58 * hostlenght and to shorten the temporary referrer string with
59 * '\0' instead of adding a useless line break.
61 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
62 * - Back to timegm() using GnuPG's replacement if necessary.
63 * Using mktime() and localtime() could add a on hour offset if
64 * the randomize factor was big enough to lead to a summer/wintertime
67 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
69 * - Moved randomization code into pick_from_range().
71 * - Changed parse_header_time definition.
72 * time_t isn't guaranteed to be signed and
73 * if it isn't, -1 isn't available as error code.
74 * Changed some variable types in client_if_modified_since()
75 * because of the same reason.
77 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
78 * OS/2 compilation compatibility fixups
80 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
81 * Changed include from strptime.c to strptime.h
83 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
84 * Split filter-headers{} into filter-client-headers{}
85 * and filter-server-headers{}.
86 * Added parse_header_time() to share some code.
87 * Replaced timegm() with mktime().
89 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
90 * Windows service integration
92 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
93 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
95 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
96 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
97 * with what was really the latest development (the v_3_0_branch branch)
99 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
100 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
102 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
103 * Add the ability to check jpeg images for invalid
104 * lengths of comment blocks. Defensive strategy
105 * against the exploit:
106 * Microsoft Security Bulletin MS04-028
107 * Buffer Overrun in JPEG Processing (GDI+) Could
108 * Allow Code Execution (833987)
109 * Enabled with +inspect-jpegs in actions files.
111 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
112 * Excluded text/plain objects from filtering. This fixes a
113 * couple of client-crashing, download corruption and
114 * Privoxy performance issues, whose root cause lies in
115 * web servers labelling content of unknown type as text/plain.
117 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
118 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
120 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
121 * Completing the previous change
123 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
124 * Added temporary workaround for bug in PHP < 4.2.3
126 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
127 * 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.
129 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
130 * Fix typo: supressed -> suppressed
132 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
133 * Improved cookie logging
135 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
136 * Added basic support for OPTIONS and TRACE HTTP methods:
137 * - New parser function client_max_forwards which decrements
138 * the Max-Forwards HTTP header field of OPTIONS and TRACE
139 * requests by one before forwarding
140 * - New parser function client_host which extracts the host
141 * and port information from the HTTP header field if the
142 * request URI was not absolute
143 * - Don't crumble and re-add the Host: header, but only generate
144 * and append if missing
146 * Revision 1.56 2002/05/12 15:34:22 jongfoster
147 * Fixing typo in a comment
149 * Revision 1.55 2002/05/08 16:01:07 oes
150 * Optimized add_to_iob:
151 * - Use realloc instead of malloc(), memcpy(), free()
152 * - Expand to powers of two if possible, to get
153 * O(log n) reallocs instead of O(n).
154 * - Moved check for buffer limit here from chat
155 * - Report failure via returncode
157 * Revision 1.54 2002/04/02 15:03:16 oes
158 * Tiny code cosmetics
160 * Revision 1.53 2002/03/26 22:29:55 swa
161 * we have a new homepage!
163 * Revision 1.52 2002/03/24 13:25:43 swa
164 * name change related issues
166 * Revision 1.51 2002/03/13 00:27:05 jongfoster
169 * Revision 1.50 2002/03/12 01:45:35 oes
170 * More verbose logging
172 * Revision 1.49 2002/03/09 20:03:52 jongfoster
173 * - Making various functions return int rather than size_t.
174 * (Undoing a recent change). Since size_t is unsigned on
175 * Windows, functions like read_socket that return -1 on
176 * error cannot return a size_t.
178 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
179 * crashes, and also frequently caused JB to jump to 100%
180 * CPU and stay there. (Because it thought it had just
181 * read ((unsigned)-1) == 4Gb of data...)
183 * - The signature of write_socket has changed, it now simply
184 * returns success=0/failure=nonzero.
186 * - Trying to get rid of a few warnings --with-debug on
187 * Windows, I've introduced a new type "jb_socket". This is
188 * used for the socket file descriptors. On Windows, this
189 * is SOCKET (a typedef for unsigned). Everywhere else, it's
190 * an int. The error value can't be -1 any more, so it's
191 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
192 * Windows it maps to the #define INVALID_SOCKET.)
194 * - The signature of bind_port has changed.
196 * Revision 1.48 2002/03/07 03:46:53 oes
197 * Fixed compiler warnings etc
199 * Revision 1.47 2002/02/20 23:15:13 jongfoster
200 * Parsing functions now handle out-of-memory gracefully by returning
203 * Revision 1.46 2002/01/17 21:03:47 jongfoster
204 * Moving all our URL and URL pattern parsing code to urlmatch.c.
206 * Revision 1.45 2002/01/09 14:33:03 oes
207 * Added support for localtime_r.
209 * Revision 1.44 2001/12/14 01:22:54 steudten
210 * Remove 'user:pass@' from 'proto://user:pass@host' for the
211 * new added header 'Host: ..'. (See Req ID 491818)
213 * Revision 1.43 2001/11/23 00:26:38 jongfoster
214 * Fixing two really stupid errors in my previous commit
216 * Revision 1.42 2001/11/22 21:59:30 jongfoster
217 * Adding code to handle +no-cookies-keep
219 * Revision 1.41 2001/11/05 23:43:05 steudten
220 * Add time+date to log files.
222 * Revision 1.40 2001/10/26 20:13:09 jongfoster
223 * ctype.h is needed in Windows, too.
225 * Revision 1.39 2001/10/26 17:40:04 oes
226 * Introduced get_header_value()
227 * Removed http->user_agent, csp->referrer and csp->accept_types
228 * Removed client_accept()
230 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
231 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
232 * threads to call select() simultaneously. So, it's time to do a real, live,
233 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
234 * (native). Both versions will work, but using __OS2__ offers multi-threading.
236 * Revision 1.37 2001/10/23 21:36:02 jongfoster
237 * Documenting sed()'s error behaviou (doc change only)
239 * Revision 1.36 2001/10/13 12:51:51 joergs
240 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
241 * force-load), instead crumble Host: and add it (again) in client_host_adder
242 * (in case we get a HTTP/1.0 request without Host: header and forward it to
243 * a HTTP/1.1 server/proxy).
245 * Revision 1.35 2001/10/09 22:39:21 jongfoster
246 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
249 * Revision 1.34 2001/10/07 18:50:55 oes
250 * Added server_content_encoding, renamed server_transfer_encoding
252 * Revision 1.33 2001/10/07 18:04:49 oes
253 * Changed server_http11 to server_http and its pattern to "HTTP".
254 * Additional functionality: it now saves the HTTP status into
255 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
257 * Revision 1.32 2001/10/07 15:43:28 oes
258 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
259 * client_te and client_accept_encoding_adder, triggered by the new
260 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
261 * changed to allow only identity and chunked, and the TE header is
262 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
264 * parse_http_request no longer does anything than parsing. The rewriting
265 * of http->cmd and version mangling are gone. It now also recognizes
266 * the put and delete methods and saves the url in http->url. Removed
269 * renamed content_type and content_length to have the server_ prefix
271 * server_content_type now only works if csp->content_type != CT_TABOO
273 * added server_transfer_encoding, which
274 * - Sets CT_TABOO to prohibit filtering if encoding compresses
275 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
276 * - Change from "chunked" to "identity" if body was chunked
277 * but has been de-chunked for filtering.
279 * added server_content_md5 which crunches any Content-MD5 headers
280 * if the body was modified.
282 * made server_http11 conditional on +downgrade action
284 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
286 * Revision 1.31 2001/10/05 14:25:02 oes
287 * Crumble Keep-Alive from Server
289 * Revision 1.30 2001/09/29 12:56:03 joergs
290 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
292 * Revision 1.29 2001/09/24 21:09:24 jongfoster
293 * Fixing 2 memory leaks that Guy spotted, where the paramater to
294 * enlist() was not being free()d.
296 * Revision 1.28 2001/09/22 16:32:28 jongfoster
297 * Removing unused #includes.
299 * Revision 1.27 2001/09/20 15:45:25 steudten
301 * add casting from size_t to int for printf()
302 * remove local variable shadow s2
304 * Revision 1.26 2001/09/16 17:05:14 jongfoster
305 * Removing unused #include showarg.h
307 * Revision 1.25 2001/09/16 13:21:27 jongfoster
308 * Changes to use new list functions.
310 * Revision 1.24 2001/09/13 23:05:50 jongfoster
311 * Changing the string paramater to the header parsers a "const".
313 * Revision 1.23 2001/09/12 18:08:19 steudten
315 * In parse_http_request() header rewriting miss the host value, so
316 * from http://www.mydomain.com the result was just " / " not
317 * http://www.mydomain.com/ in case we forward.
319 * Revision 1.22 2001/09/10 10:58:53 oes
320 * Silenced compiler warnings
322 * Revision 1.21 2001/07/31 14:46:00 oes
323 * - Persistant connections now suppressed
324 * - sed() no longer appends empty header to csp->headers
326 * Revision 1.20 2001/07/30 22:08:36 jongfoster
327 * Tidying up #defines:
328 * - All feature #defines are now of the form FEATURE_xxx
329 * - Permanently turned off WIN_GUI_EDIT
330 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
332 * Revision 1.19 2001/07/25 17:21:54 oes
333 * client_uagent now saves copy of User-Agent: header value
335 * Revision 1.18 2001/07/13 14:02:46 oes
336 * - Included fix to repair broken HTTP requests that
337 * don't contain a path, not even '/'.
338 * - Removed all #ifdef PCRS
339 * - content_type now always inspected and classified as
340 * text, gif or other.
341 * - formatting / comments
343 * Revision 1.17 2001/06/29 21:45:41 oes
344 * Indentation, CRLF->LF, Tab-> Space
346 * Revision 1.16 2001/06/29 13:32:42 oes
348 * - Adapted free_http_request
349 * - Removed logentry from cancelled commit
351 * Revision 1.15 2001/06/03 19:12:38 oes
352 * deleted const struct interceptors
354 * Revision 1.14 2001/06/01 18:49:17 jongfoster
355 * Replaced "list_share" with "list" - the tiny memory gain was not
356 * worth the extra complexity.
358 * Revision 1.13 2001/05/31 21:30:33 jongfoster
359 * Removed list code - it's now in list.[ch]
360 * Renamed "permission" to "action", and changed many features
361 * to use the actions file rather than the global config.
363 * Revision 1.12 2001/05/31 17:33:13 oes
367 * Revision 1.11 2001/05/29 20:11:19 joergs
368 * '/ * inside comment' warning removed.
370 * Revision 1.10 2001/05/29 09:50:24 jongfoster
371 * Unified blocklist/imagelist/permissionslist.
372 * File format is still under discussion, but the internal changes
375 * Also modified interceptor behaviour:
376 * - We now intercept all URLs beginning with one of the following
377 * prefixes (and *only* these prefixes):
379 * * http://ijbswa.sf.net/config/
380 * * http://ijbswa.sourceforge.net/config/
381 * - New interceptors "home page" - go to http://i.j.b/ to see it.
382 * - Internal changes so that intercepted and fast redirect pages
383 * are not replaced with an image.
384 * - Interceptors now have the option to send a binary page direct
385 * to the client. (i.e. ijb-send-banner uses this)
386 * - Implemented show-url-info interceptor. (Which is why I needed
387 * the above interceptors changes - a typical URL is
388 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
389 * The previous mechanism would not have intercepted that, and
390 * if it had been intercepted then it then it would have replaced
393 * Revision 1.9 2001/05/28 17:26:33 jongfoster
394 * Fixing segfault if last header was crunched.
395 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
396 * can use the cross-platform sprintf() instead.)
398 * Revision 1.8 2001/05/27 22:17:04 oes
400 * - re_process_buffer no longer writes the modified buffer
401 * to the client, which was very ugly. It now returns the
402 * buffer, which it is then written by chat.
404 * - content_length now adjusts the Content-Length: header
405 * for modified documents rather than crunch()ing it.
406 * (Length info in csp->content_length, which is 0 for
407 * unmodified documents)
409 * - For this to work, sed() is called twice when filtering.
411 * Revision 1.7 2001/05/27 13:19:06 oes
412 * Patched Joergs solution for the content-length in.
414 * Revision 1.6 2001/05/26 13:39:32 jongfoster
415 * Only crunches Content-Length header if applying RE filtering.
416 * Without this fix, Microsoft Windows Update wouldn't work.
418 * Revision 1.5 2001/05/26 00:28:36 jongfoster
419 * Automatic reloading of config file.
420 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
421 * Most of the global variables have been moved to a new
422 * struct configuration_spec, accessed through csp->config->globalname
423 * Most of the globals remaining are used by the Win32 GUI.
425 * Revision 1.4 2001/05/22 18:46:04 oes
427 * - Enabled filtering banners by size rather than URL
428 * by adding patterns that replace all standard banner
429 * sizes with the "Junkbuster" gif to the re_filterfile
431 * - Enabled filtering WebBugs by providing a pattern
432 * which kills all 1x1 images
434 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
435 * which is selected by the (nonstandard and therefore
436 * capital) letter 'U' in the option string.
437 * It causes the quantifiers to be ungreedy by default.
438 * Appending a ? turns back to greedy (!).
440 * - Added a new interceptor ijb-send-banner, which
441 * sends back the "Junkbuster" gif. Without imagelist or
442 * MSIE detection support, or if tinygif = 1, or the
443 * URL isn't recognized as an imageurl, a lame HTML
444 * explanation is sent instead.
446 * - Added new feature, which permits blocking remote
447 * script redirects and firing back a local redirect
449 * The feature is conditionally compiled, i.e. it
450 * can be disabled with --disable-fast-redirects,
451 * plus it must be activated by a "fast-redirects"
452 * line in the config file, has its own log level
453 * and of course wants to be displayed by show-proxy-args
454 * Note: Boy, all the #ifdefs in 1001 locations and
455 * all the fumbling with configure.in and acconfig.h
456 * were *way* more work than the feature itself :-(
458 * - Because a generic redirect template was needed for
459 * this, tinygif = 3 now uses the same.
461 * - Moved GIFs, and other static HTTP response templates
466 * - Removed some >400 CRs again (Jon, you really worked
469 * Revision 1.3 2001/05/20 01:21:20 jongfoster
470 * Version 2.9.4 checkin.
471 * - Merged popupfile and cookiefile, and added control over PCRS
472 * filtering, in new "permissionsfile".
473 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
474 * file error you now get a message box (in the Win32 GUI) rather
475 * than the program exiting with no explanation.
476 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
478 * - Removed tabs from "config"
479 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
480 * - Bumped up version number.
482 * Revision 1.2 2001/05/17 23:02:36 oes
483 * - Made referrer option accept 'L' as a substitute for '§'
485 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
486 * Initial import of version 2.9.3 source tree
489 *********************************************************************/
496 #include <sys/types.h>
505 #if !defined(_WIN32) && !defined(__OS2__)
514 /* jcc.h is for mutex semapores only */
515 #endif /* def OSX_DARWIN */
521 #include "jbsockets.h"
522 #include "miscutil.h"
525 #ifndef HAVE_STRPTIME
526 #include "strptime.h"
529 const char parsers_h_rcs[] = PARSERS_H_VERSION;
531 /* Fix a problem with Solaris. There should be no effect on other
533 * Solaris's isspace() is a macro which uses it's argument directly
534 * as an array index. Therefore we need to make sure that high-bit
535 * characters generate +ve values, and ideally we also want to make
536 * the argument match the declared parameter type of "int".
538 * Why did they write a character function that can't take a simple
539 * "char" argument? Doh!
541 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
542 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
545 const struct parsers client_patterns[] = {
546 { "referer:", 8, client_referrer },
547 { "user-agent:", 11, client_uagent },
548 { "ua-", 3, client_ua },
549 { "from:", 5, client_from },
550 { "cookie:", 7, client_send_cookie },
551 { "x-forwarded-for:", 16, client_x_forwarded },
552 { "Accept-Encoding:", 16, client_accept_encoding },
553 { "TE:", 3, client_te },
554 { "Host:", 5, client_host },
555 { "if-modified-since:", 18, client_if_modified_since },
556 { "Keep-Alive:", 11, crumble },
557 { "connection:", 11, crumble },
558 { "proxy-connection:", 17, crumble },
559 { "max-forwards:", 13, client_max_forwards },
560 { "Accept-Language:", 16, client_accept_language },
561 { "if-none-match:", 14, client_if_none_match },
562 { "X-Filter:", 9, client_x_filter },
563 { "*", 0, crunch_client_header },
564 { "*", 0, filter_client_header },
568 const struct parsers server_patterns[] = {
569 { "HTTP", 4, server_http },
570 { "set-cookie:", 11, server_set_cookie },
571 { "connection:", 11, crumble },
572 { "Content-Type:", 13, server_content_type },
573 { "Content-Length:", 15, server_content_length },
574 { "Content-MD5:", 12, server_content_md5 },
575 { "Content-Encoding:", 17, server_content_encoding },
576 { "Transfer-Encoding:", 18, server_transfer_coding },
577 { "Keep-Alive:", 11, crumble },
578 { "content-disposition:", 20, server_content_disposition },
579 { "Last-Modified:", 14, server_last_modified },
580 { "*", 0, crunch_server_header },
581 { "*", 0, filter_server_header },
585 const struct parsers server_patterns_light[] = {
586 { "Content-Length:", 15, server_content_length },
587 { "Transfer-Encoding:", 18, server_transfer_coding },
591 const add_header_func_ptr add_client_headers[] = {
594 client_x_forwarded_adder,
596 /* Temporarily disabled: client_accept_encoding_adder, */
597 connection_close_adder,
602 const add_header_func_ptr add_server_headers[] = {
603 connection_close_adder,
607 /*********************************************************************
609 * Function : flush_socket
611 * Description : Write any pending "buffered" content.
614 * 1 : fd = file descriptor of the socket to read
615 * 2 : csp = Current client state (buffers, headers, etc...)
617 * Returns : On success, the number of bytes written are returned (zero
618 * indicates nothing was written). On error, -1 is returned,
619 * and errno is set appropriately. If count is zero and the
620 * file descriptor refers to a regular file, 0 will be
621 * returned without causing any other effect. For a special
622 * file, the results are not portable.
624 *********************************************************************/
625 int flush_socket(jb_socket fd, struct client_state *csp)
627 struct iob *iob = csp->iob;
628 int len = iob->eod - iob->cur;
635 if (write_socket(fd, iob->cur, (size_t)len))
639 iob->eod = iob->cur = iob->buf;
645 /*********************************************************************
647 * Function : add_to_iob
649 * Description : Add content to the buffered page, expanding the
650 * buffer if necessary.
653 * 1 : csp = Current client state (buffers, headers, etc...)
654 * 2 : buf = holds the content to be added to the page
655 * 3 : n = number of bytes to be added
657 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
658 * or buffer limit reached.
660 *********************************************************************/
661 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
663 struct iob *iob = csp->iob;
664 size_t used, offset, need, want;
667 if (n <= 0) return JB_ERR_OK;
669 used = iob->eod - iob->buf;
670 offset = iob->cur - iob->buf;
674 * If the buffer can't hold the new data, extend it first.
675 * Use the next power of two if possible, else use the actual need.
677 if (need > csp->config->buffer_limit)
679 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
680 return JB_ERR_MEMORY;
683 if (need > iob->size)
685 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
687 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
691 else if (NULL != (p = (char *)realloc(iob->buf, need)))
697 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
698 return JB_ERR_MEMORY;
701 /* Update the iob pointers */
702 iob->cur = p + offset;
707 /* copy the new data into the iob buffer */
708 memcpy(iob->eod, buf, (size_t)n);
710 /* point to the end of the data */
713 /* null terminate == cheap insurance */
721 /*********************************************************************
723 * Function : get_header
725 * Description : This (odd) routine will parse the csp->iob
728 * 1 : csp = Current client state (buffers, headers, etc...)
730 * Returns : Any one of the following:
732 * 1) a pointer to a dynamically allocated string that contains a header line
733 * 2) NULL indicating that the end of the header was reached
734 * 3) "" indicating that the end of the iob was reached before finding
735 * a complete header line.
737 *********************************************************************/
738 char *get_header(struct client_state *csp)
744 if ((iob->cur == NULL)
745 || ((p = strchr(iob->cur, '\n')) == NULL))
747 return(""); /* couldn't find a complete header */
752 ret = strdup(iob->cur);
755 /* FIXME No way to handle error properly */
756 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
761 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
763 /* is this a blank line (i.e. the end of the header) ? */
775 /*********************************************************************
777 * Function : get_header_value
779 * Description : Get the value of a given header from a chained list
780 * of header lines or return NULL if no such header is
781 * present in the list.
784 * 1 : header_list = pointer to list
785 * 2 : header_name = string with name of header to look for.
786 * Trailing colon required, capitalization
789 * Returns : NULL if not found, else value of header
791 *********************************************************************/
792 char *get_header_value(const struct list *header_list, const char *header_name)
794 struct list_entry *cur_entry;
800 length = strlen(header_name);
802 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
806 if (!strncmpic(cur_entry->str, header_name, length))
809 * Found: return pointer to start of value
811 ret = (char *) (cur_entry->str + length);
812 while (*ret && ijb_isspace(*ret)) ret++;
825 /*********************************************************************
829 * Description : add, delete or modify lines in the HTTP header streams.
830 * On entry, it receives a linked list of headers space
831 * that was allocated dynamically (both the list nodes
832 * and the header contents).
834 * As a side effect it frees the space used by the original
838 * 1 : pats = list of patterns to match against headers
839 * 2 : more_headers = list of functions to add more
840 * headers (client or server)
841 * 3 : csp = Current client state (buffers, headers, etc...)
843 * Returns : Single pointer to a fully formed header, or NULL
844 * on out-of-memory error.
846 *********************************************************************/
847 char *sed(const struct parsers pats[],
848 const add_header_func_ptr more_headers[],
849 struct client_state *csp)
851 struct list_entry *p;
852 const struct parsers *v;
853 const add_header_func_ptr *f;
854 jb_err err = JB_ERR_OK;
858 * If filtering is enabled, sed is run twice,
859 * but most of the work needs to be done only once.
861 first_run = (more_headers != NULL ) ? 1 : 0;
863 if (first_run) /* Parse and print */
865 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
867 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
869 /* Header crunch()ed in previous run? -> ignore */
870 if (p->str == NULL) continue;
872 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
874 /* Does the current parser handle this header? */
875 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
877 err = v->parser(csp, (char **)&(p->str));
881 /* place any additional headers on the csp->headers list */
882 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
887 else /* Parse only */
890 * The second run is only needed if the body was modified
891 * and the content-lenght has changed.
893 if (strncmpic(csp->http->cmd, "HEAD", 4))
895 /*XXX: Code duplication*/
896 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
898 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
900 /* Header crunch()ed in previous run? -> ignore */
901 if (p->str == NULL) continue;
903 /* Does the current parser handle this header? */
904 if (strncmpic(p->str, v->str, v->len) == 0)
906 err = v->parser(csp, (char **)&(p->str));
913 if (err != JB_ERR_OK)
918 return list_to_text(csp->headers);
922 /* here begins the family of parser functions that reformat header lines */
924 /*********************************************************************
926 * Function : filter_server_header
928 * Description : Checks if server header filtering is enabled.
929 * If it is, filter_header is called to do the work.
932 * 1 : csp = Current client state (buffers, headers, etc...)
933 * 2 : header = On input, pointer to header to modify.
934 * On output, pointer to the modified header, or NULL
935 * to remove the header. This function frees the
936 * original string if necessary.
938 * Returns : JB_ERR_OK on success and always succeeds
940 *********************************************************************/
941 jb_err filter_server_header(struct client_state *csp, char **header)
943 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
945 filter_header(csp, header);
950 /*********************************************************************
952 * Function : filter_client_header
954 * Description : Checks if client header filtering is enabled.
955 * If it is, filter_header is called to do the work.
958 * 1 : csp = Current client state (buffers, headers, etc...)
959 * 2 : header = On input, pointer to header to modify.
960 * On output, pointer to the modified header, or NULL
961 * to remove the header. This function frees the
962 * original string if necessary.
964 * Returns : JB_ERR_OK on success and always succeeds
966 *********************************************************************/
967 jb_err filter_client_header(struct client_state *csp, char **header)
969 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
971 filter_header(csp, header);
976 /*********************************************************************
978 * Function : filter_header
980 * Description : Executes all text substitutions from all applying
981 * +filter actions on the header.
982 * Most of the code was copied from pcrs_filter_response,
983 * including the rather short variable names
986 * 1 : csp = Current client state (buffers, headers, etc...)
987 * 2 : header = On input, pointer to header to modify.
988 * On output, pointer to the modified header, or NULL
989 * to remove the header. This function frees the
990 * original string if necessary.
992 * Returns : JB_ERR_OK on success and always succeeds
994 *********************************************************************/
995 jb_err filter_header(struct client_state *csp, char **header)
999 size_t size = strlen(*header);
1001 char *newheader = NULL;
1004 struct file_list *fl;
1005 struct re_filterfile_spec *b;
1006 struct list_entry *filtername;
1008 int i, found_filters = 0;
1010 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
1012 * Need to check the set of re_filterfiles...
1014 for (i = 0; i < MAX_AF_FILES; i++)
1027 if (0 == found_filters)
1029 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1033 for (i = 0; i < MAX_AF_FILES; i++)
1036 if ((NULL == fl) || (NULL == fl->f))
1039 * For all applying +filter actions, look if a filter by that
1040 * name exists and if yes, execute its pcrs_joblist on the
1043 for (b = fl->f; b; b = b->next)
1045 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1046 filtername ; filtername = filtername->next)
1048 if (strcmp(b->name, filtername->str) == 0)
1050 int current_hits = 0;
1052 if ( NULL == b->joblist )
1054 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1058 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1059 *header, size, b->name);
1061 /* Apply all jobs from the joblist */
1062 for (job = b->joblist; NULL != job; job = job->next)
1064 matches = pcrs_execute(job, *header, size, &newheader, &size);
1067 current_hits += matches;
1068 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1070 *header = newheader;
1072 else if ( 0 == matches )
1074 /* Filter doesn't change header */
1080 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1081 *header, b->name, pcrs_strerror(matches));
1082 if( newheader != NULL)
1084 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1089 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1090 hits += current_hits;
1098 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1101 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1107 /*********************************************************************
1109 * Function : crumble
1111 * Description : This is called if a header matches a pattern to "crunch"
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1115 * 2 : header = On input, pointer to header to modify.
1116 * On output, pointer to the modified header, or NULL
1117 * to remove the header. This function frees the
1118 * original string if necessary.
1120 * Returns : JB_ERR_OK on success, or
1121 * JB_ERR_MEMORY on out-of-memory error.
1123 *********************************************************************/
1124 jb_err crumble(struct client_state *csp, char **header)
1126 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1131 /*********************************************************************
1133 * Function : crunch_server_header
1135 * Description : Crunch server header if it matches a string supplied by the
1136 * user. Called from `sed'.
1139 * 1 : csp = Current client state (buffers, headers, etc...)
1140 * 2 : header = On input, pointer to header to modify.
1141 * On output, pointer to the modified header, or NULL
1142 * to remove the header. This function frees the
1143 * original string if necessary.
1145 * Returns : JB_ERR_OK on success and always succeeds
1147 *********************************************************************/
1148 jb_err crunch_server_header(struct client_state *csp, char **header)
1150 const char *crunch_pattern;
1151 /*Is there a header to crunch*/
1153 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1155 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1157 /*Is the current header the lucky one?*/
1158 if (strstr(*header, crunch_pattern))
1160 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1167 /*********************************************************************
1169 * Function : server_content_type
1171 * Description : Set the content-type for filterable types (text/.*,
1172 * javascript and image/gif) unless filtering has been
1173 * forbidden (CT_TABOO) while parsing earlier headers.
1174 * NOTE: Since text/plain is commonly used by web servers
1175 * for files whose correct type is unknown, we don't
1176 * set CT_TEXT for it.
1179 * 1 : csp = Current client state (buffers, headers, etc...)
1180 * 2 : header = On input, pointer to header to modify.
1181 * On output, pointer to the modified header, or NULL
1182 * to remove the header. This function frees the
1183 * original string if necessary.
1185 * Returns : JB_ERR_OK on success, or
1186 * JB_ERR_MEMORY on out-of-memory error.
1188 *********************************************************************/
1189 jb_err server_content_type(struct client_state *csp, char **header)
1193 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1195 if (csp->content_type != CT_TABOO)
1197 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1198 || strstr(*header, "xml")
1199 || strstr(*header, "application/x-javascript"))
1200 csp->content_type = CT_TEXT;
1201 else if (strstr(*header, " image/gif"))
1202 csp->content_type = CT_GIF;
1203 else if (strstr(*header, " image/jpeg"))
1204 csp->content_type = CT_JPEG;
1206 csp->content_type = 0;
1209 * Are we enabling text mode by force?
1211 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1214 * Do we really have to?
1216 if (csp->content_type == CT_TEXT)
1218 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1222 csp->content_type = CT_TEXT;
1223 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1227 * Are we messing with the content type?
1229 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1232 * Make sure the user doesn't accidently
1233 * change the content type of binary documents.
1235 if (csp->content_type == CT_TEXT)
1238 *header = strdup("Content-Type: ");
1239 string_append(header, newval);
1243 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1244 return JB_ERR_MEMORY;
1246 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1250 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1251 "Enable force-text-mode if you know what you're doing.", *header);
1258 /*********************************************************************
1260 * Function : server_transfer_coding
1262 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1263 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1264 * - Remove header if body was chunked but has been
1265 * de-chunked for filtering.
1268 * 1 : csp = Current client state (buffers, headers, etc...)
1269 * 2 : header = On input, pointer to header to modify.
1270 * On output, pointer to the modified header, or NULL
1271 * to remove the header. This function frees the
1272 * original string if necessary.
1274 * Returns : JB_ERR_OK on success, or
1275 * JB_ERR_MEMORY on out-of-memory error.
1277 *********************************************************************/
1278 jb_err server_transfer_coding(struct client_state *csp, char **header)
1281 * Turn off pcrs and gif filtering if body compressed
1283 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1285 csp->content_type = CT_TABOO;
1289 * Raise flag if body chunked
1291 if (strstr(*header, "chunked"))
1293 csp->flags |= CSP_FLAG_CHUNKED;
1296 * If the body was modified, it has been de-chunked first
1297 * and the header must be removed.
1299 if (csp->flags & CSP_FLAG_MODIFIED)
1301 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1310 /*********************************************************************
1312 * Function : server_content_encoding
1314 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1317 * 1 : csp = Current client state (buffers, headers, etc...)
1318 * 2 : header = On input, pointer to header to modify.
1319 * On output, pointer to the modified header, or NULL
1320 * to remove the header. This function frees the
1321 * original string if necessary.
1323 * Returns : JB_ERR_OK on success, or
1324 * JB_ERR_MEMORY on out-of-memory error.
1326 *********************************************************************/
1327 jb_err server_content_encoding(struct client_state *csp, char **header)
1330 * Turn off pcrs and gif filtering if body compressed
1332 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1334 csp->content_type = CT_TABOO;
1342 /*********************************************************************
1344 * Function : server_content_length
1346 * Description : Adjust Content-Length header if we modified
1350 * 1 : csp = Current client state (buffers, headers, etc...)
1351 * 2 : header = On input, pointer to header to modify.
1352 * On output, pointer to the modified header, or NULL
1353 * to remove the header. This function frees the
1354 * original string if necessary.
1356 * Returns : JB_ERR_OK on success, or
1357 * JB_ERR_MEMORY on out-of-memory error.
1359 *********************************************************************/
1360 jb_err server_content_length(struct client_state *csp, char **header)
1362 if (csp->content_length != 0) /* Content length could have been modified */
1365 * XXX: Shouldn't we check if csp->content_length
1366 * is different than the original value?
1369 *header = (char *) zalloc(100);
1370 if (*header == NULL)
1372 return JB_ERR_MEMORY;
1375 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1377 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1384 /*********************************************************************
1386 * Function : server_content_md5
1388 * Description : Crumble any Content-MD5 headers if the document was
1389 * modified. FIXME: Should we re-compute instead?
1392 * 1 : csp = Current client state (buffers, headers, etc...)
1393 * 2 : header = On input, pointer to header to modify.
1394 * On output, pointer to the modified header, or NULL
1395 * to remove the header. This function frees the
1396 * original string if necessary.
1398 * Returns : JB_ERR_OK on success, or
1399 * JB_ERR_MEMORY on out-of-memory error.
1401 *********************************************************************/
1402 jb_err server_content_md5(struct client_state *csp, char **header)
1404 if (csp->flags & CSP_FLAG_MODIFIED)
1406 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1413 /*********************************************************************
1415 * Function : server_content_disposition
1417 * Description : If enabled, blocks or modifies the "content-disposition" header.
1418 * Called from `sed'.
1421 * 1 : csp = Current client state (buffers, headers, etc...)
1422 * 2 : header = On input, pointer to header to modify.
1423 * On output, pointer to the modified header, or NULL
1424 * to remove the header. This function frees the
1425 * original string if necessary.
1427 * Returns : JB_ERR_OK on success, or
1428 * JB_ERR_MEMORY on out-of-memory error.
1430 *********************************************************************/
1431 jb_err server_content_disposition(struct client_state *csp, char **header)
1436 * Are we messing with the content-disposition header?
1438 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1444 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1446 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1449 * Blocking content-disposition header
1451 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1458 * Replacing content-disposition header
1461 *header = strdup("content-disposition: ");
1462 string_append(header, newval);
1464 if (*header == NULL)
1466 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1470 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1473 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1476 /*********************************************************************
1478 * Function : server_last_modified
1480 * Description : Changes Last-Modified header to the actual date
1481 * to help hide-if-modified-since.
1482 * Called from `sed'.
1485 * 1 : csp = Current client state (buffers, headers, etc...)
1486 * 2 : header = On input, pointer to header to modify.
1487 * On output, pointer to the modified header, or NULL
1488 * to remove the header. This function frees the
1489 * original string if necessary.
1491 * Returns : JB_ERR_OK on success, or
1492 * JB_ERR_MEMORY on out-of-memory error.
1494 *********************************************************************/
1495 jb_err server_last_modified(struct client_state *csp, char **header)
1498 char buf[BUFFER_SIZE];
1501 #ifdef HAVE_GMTIME_R
1504 struct tm *timeptr = NULL;
1505 time_t now, last_modified;
1507 long int days, hours, minutes, seconds;
1510 * Are we messing with the Last-Modified header?
1512 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1518 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1520 if (0 == strcmpic(newval, "block") )
1523 * Blocking Last-Modified header. Useless but why not.
1525 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1529 else if (0 == strcmpic(newval, "reset-to-request-time"))
1532 * Setting Last-Modified Header to now.
1534 get_http_time(0, buf);
1536 *header = strdup("Last-Modified: ");
1537 string_append(header, buf);
1539 if (*header == NULL)
1541 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1545 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1548 else if (0 == strcmpic(newval, "randomize"))
1550 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1552 #ifdef HAVE_GMTIME_R
1553 timeptr = gmtime_r(&now, &gmt);
1555 pthread_mutex_lock(&gmtime_mutex);
1556 timeptr = gmtime(&now);
1557 pthread_mutex_unlock(&gmtime_mutex);
1559 timeptr = gmtime(&now);
1561 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1563 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1568 rtime = difftime(now, last_modified);
1571 rtime = pick_from_range(rtime);
1572 last_modified += rtime;
1573 #ifdef HAVE_GMTIME_R
1574 timeptr = gmtime_r(&last_modified, &gmt);
1576 pthread_mutex_lock(&gmtime_mutex);
1577 timeptr = gmtime(&last_modified);
1578 pthread_mutex_unlock(&gmtime_mutex);
1580 timeptr = gmtime(&last_modified);
1582 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1584 *header = strdup("Last-Modified: ");
1585 string_append(header, newheader);
1587 if (*header == NULL)
1589 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1590 return JB_ERR_MEMORY;
1593 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1595 days = rtime / (3600 * 24);
1596 hours = rtime / 3600 % 24;
1597 minutes = rtime / 60 % 60;
1598 seconds = rtime % 60;
1600 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1601 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1602 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1607 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1615 /*********************************************************************
1617 * Function : client_accept_encoding
1619 * Description : Rewrite the client's Accept-Encoding header so that
1620 * if doesn't allow compression, if the action applies.
1621 * Note: For HTTP/1.0 the absence of the header is enough.
1624 * 1 : csp = Current client state (buffers, headers, etc...)
1625 * 2 : header = On input, pointer to header to modify.
1626 * On output, pointer to the modified header, or NULL
1627 * to remove the header. This function frees the
1628 * original string if necessary.
1630 * Returns : JB_ERR_OK on success, or
1631 * JB_ERR_MEMORY on out-of-memory error.
1633 *********************************************************************/
1634 jb_err client_accept_encoding(struct client_state *csp, char **header)
1636 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1638 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1642 /* Temporarily disable the correct behaviour to
1643 * work around a PHP bug.
1645 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1647 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1648 * if (*header == NULL)
1650 * return JB_ERR_MEMORY;
1661 /*********************************************************************
1663 * Function : client_te
1665 * Description : Rewrite the client's TE header so that
1666 * if doesn't allow compression, if the action applies.
1669 * 1 : csp = Current client state (buffers, headers, etc...)
1670 * 2 : header = On input, pointer to header to modify.
1671 * On output, pointer to the modified header, or NULL
1672 * to remove the header. This function frees the
1673 * original string if necessary.
1675 * Returns : JB_ERR_OK on success, or
1676 * JB_ERR_MEMORY on out-of-memory error.
1678 *********************************************************************/
1679 jb_err client_te(struct client_state *csp, char **header)
1681 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1684 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1690 /*********************************************************************
1692 * Function : client_referrer
1694 * Description : Handle the "referer" config setting properly.
1695 * Called from `sed'.
1698 * 1 : csp = Current client state (buffers, headers, etc...)
1699 * 2 : header = On input, pointer to header to modify.
1700 * On output, pointer to the modified header, or NULL
1701 * to remove the header. This function frees the
1702 * original string if necessary.
1704 * Returns : JB_ERR_OK on success, or
1705 * JB_ERR_MEMORY on out-of-memory error.
1707 *********************************************************************/
1708 jb_err client_referrer(struct client_state *csp, char **header)
1715 #ifdef FEATURE_FORCE_LOAD
1716 /* Since the referrer can include the prefix even
1717 * if the request itself is non-forced, we must
1718 * clean it unconditionally
1720 strclean(*header, FORCE_PREFIX);
1721 #endif /* def FEATURE_FORCE_LOAD */
1724 * Are we sending referer?
1726 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1731 newval = csp->action->string[ACTION_STRING_REFERER];
1733 if ((0 != strcmpic(newval, "conditional-block")))
1737 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1742 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1745 else if (0 == strcmpic(newval, "conditional-block"))
1748 * Block referer if host has changed.
1751 if (NULL == (host = strdup(csp->http->hostport)))
1754 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1755 return JB_ERR_MEMORY;
1757 if (NULL == (referer = strdup(*header)))
1761 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1762 return JB_ERR_MEMORY;
1764 hostlenght = strlen(host);
1765 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1767 /*Shorten referer to make sure the referer is blocked
1768 *if www.example.org/www.example.com-shall-see-the-referer/
1769 *links to www.example.com/
1771 referer[hostlenght+17] = '\0';
1773 if ( 0 == strstr(referer, host)) /*Host has changed*/
1775 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1780 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1786 else if (0 != strcmpic(newval, "forge"))
1789 * We have a specific (fixed) referer we want to send.
1791 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1793 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1795 *header = strdup("Referer: ");
1796 string_append(header, newval);
1797 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1799 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1804 * Forge a referer as http://[hostname:port of REQUEST]/
1805 * to fool stupid checks for in-site links
1808 *header = strdup("Referer: http://");
1809 string_append(header, csp->http->hostport);
1810 string_append(header, "/");
1811 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1813 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1817 /*********************************************************************
1819 * Function : client_accept_language
1821 * Description : Handle the "Accept-Language" config setting properly.
1822 * Called from `sed'.
1825 * 1 : csp = Current client state (buffers, headers, etc...)
1826 * 2 : header = On input, pointer to header to modify.
1827 * On output, pointer to the modified header, or NULL
1828 * to remove the header. This function frees the
1829 * original string if necessary.
1831 * Returns : JB_ERR_OK on success, or
1832 * JB_ERR_MEMORY on out-of-memory error.
1834 *********************************************************************/
1835 jb_err client_accept_language(struct client_state *csp, char **header)
1840 * Are we messing with the Accept-Language?
1842 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1844 /*I don't think so*/
1848 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1850 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1853 * Blocking Accept-Language header
1855 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1862 * Replacing Accept-Language header
1865 *header = strdup("Accept-Language: ");
1866 string_append(header, newval);
1868 if (*header == NULL)
1870 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1874 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1877 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1880 /*********************************************************************
1882 * Function : crunch_client_header
1884 * Description : Crunch client header if it matches a string supplied by the
1885 * user. Called from `sed'.
1888 * 1 : csp = Current client state (buffers, headers, etc...)
1889 * 2 : header = On input, pointer to header to modify.
1890 * On output, pointer to the modified header, or NULL
1891 * to remove the header. This function frees the
1892 * original string if necessary.
1894 * Returns : JB_ERR_OK on success and always succeeds
1896 *********************************************************************/
1897 jb_err crunch_client_header(struct client_state *csp, char **header)
1899 const char *crunch_pattern;
1900 /*Is there a header to crunch*/
1902 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1904 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1906 /*Is the current header the lucky one?*/
1907 if (strstr(*header, crunch_pattern))
1909 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1917 /*********************************************************************
1919 * Function : client_uagent
1921 * Description : Handle the "user-agent" config setting properly
1922 * and remember its original value to enable browser
1923 * bug workarounds. Called from `sed'.
1926 * 1 : csp = Current client state (buffers, headers, etc...)
1927 * 2 : header = On input, pointer to header to modify.
1928 * On output, pointer to the modified header, or NULL
1929 * to remove the header. This function frees the
1930 * original string if necessary.
1932 * Returns : JB_ERR_OK on success, or
1933 * JB_ERR_MEMORY on out-of-memory error.
1935 *********************************************************************/
1936 jb_err client_uagent(struct client_state *csp, char **header)
1940 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1945 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1952 *header = strdup("User-Agent: ");
1953 string_append(header, newval);
1955 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1957 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1960 /*********************************************************************
1962 * Function : client_ua
1964 * Description : Handle "ua-" headers properly. Called from `sed'.
1967 * 1 : csp = Current client state (buffers, headers, etc...)
1968 * 2 : header = On input, pointer to header to modify.
1969 * On output, pointer to the modified header, or NULL
1970 * to remove the header. This function frees the
1971 * original string if necessary.
1973 * Returns : JB_ERR_OK on success, or
1974 * JB_ERR_MEMORY on out-of-memory error.
1976 *********************************************************************/
1977 jb_err client_ua(struct client_state *csp, char **header)
1979 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1981 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1989 /*********************************************************************
1991 * Function : client_from
1993 * Description : Handle the "from" config setting properly.
1994 * Called from `sed'.
1997 * 1 : csp = Current client state (buffers, headers, etc...)
1998 * 2 : header = On input, pointer to header to modify.
1999 * On output, pointer to the modified header, or NULL
2000 * to remove the header. This function frees the
2001 * original string if necessary.
2003 * Returns : JB_ERR_OK on success, or
2004 * JB_ERR_MEMORY on out-of-memory error.
2006 *********************************************************************/
2007 jb_err client_from(struct client_state *csp, char **header)
2011 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2018 newval = csp->action->string[ACTION_STRING_FROM];
2021 * Are we blocking the e-mail address?
2023 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2025 log_error(LOG_LEVEL_HEADER, "crunched From!");
2029 log_error(LOG_LEVEL_HEADER, " modified");
2031 *header = strdup("From: ");
2032 string_append(header, newval);
2034 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2038 /*********************************************************************
2040 * Function : client_send_cookie
2042 * Description : Handle the "cookie" header properly. Called from `sed'.
2043 * If cookie is accepted, add it to the cookie_list,
2044 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2047 * 1 : csp = Current client state (buffers, headers, etc...)
2048 * 2 : header = On input, pointer to header to modify.
2049 * On output, pointer to the modified header, or NULL
2050 * to remove the header. This function frees the
2051 * original string if necessary.
2053 * Returns : JB_ERR_OK on success, or
2054 * JB_ERR_MEMORY on out-of-memory error.
2056 *********************************************************************/
2057 jb_err client_send_cookie(struct client_state *csp, char **header)
2059 jb_err result = JB_ERR_OK;
2061 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2063 /* strlen("cookie: ") == 8 */
2064 result = enlist(csp->cookie_list, *header + 8);
2068 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2072 * Always remove the cookie here. The cookie header
2073 * will be sent at the end of the header.
2081 /*********************************************************************
2083 * Function : client_x_forwarded
2085 * Description : Handle the "x-forwarded-for" config setting properly,
2086 * also used in the add_client_headers list. Called from `sed'.
2089 * 1 : csp = Current client state (buffers, headers, etc...)
2090 * 2 : header = On input, pointer to header to modify.
2091 * On output, pointer to the modified header, or NULL
2092 * to remove the header. This function frees the
2093 * original string if necessary.
2095 * Returns : JB_ERR_OK on success, or
2096 * JB_ERR_MEMORY on out-of-memory error.
2098 *********************************************************************/
2099 jb_err client_x_forwarded(struct client_state *csp, char **header)
2101 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2103 /* Save it so we can re-add it later */
2104 freez(csp->x_forwarded);
2105 csp->x_forwarded = *header;
2108 * Always set *header = NULL, since this information
2109 * will be sent at the end of the header.
2116 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2123 /*********************************************************************
2125 * Function : client_max_forwards
2127 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2128 * from the value of the Max-Forwards header field.
2131 * 1 : csp = Current client state (buffers, headers, etc...)
2132 * 2 : header = On input, pointer to header to modify.
2133 * On output, pointer to the modified header, or NULL
2134 * to remove the header. This function frees the
2135 * original string if necessary.
2137 * Returns : JB_ERR_OK on success, or
2138 * JB_ERR_MEMORY on out-of-memory error.
2140 *********************************************************************/
2141 jb_err client_max_forwards(struct client_state *csp, char **header)
2143 unsigned int max_forwards;
2145 if ((0 == strcmpic(csp->http->gpc, "trace"))
2146 || (0 == strcmpic(csp->http->gpc, "options")))
2148 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2150 if (max_forwards-- >= 1)
2152 sprintf(*header, "Max-Forwards: %u", max_forwards);
2153 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2157 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2166 /*********************************************************************
2168 * Function : client_host
2170 * Description : If the request URI did not contain host and
2171 * port information, parse and evaluate the Host
2174 * Also, kill ill-formed HOST: headers as sent by
2175 * Apple's iTunes software when used with a proxy.
2178 * 1 : csp = Current client state (buffers, headers, etc...)
2179 * 2 : header = On input, pointer to header to modify.
2180 * On output, pointer to the modified header, or NULL
2181 * to remove the header. This function frees the
2182 * original string if necessary.
2184 * Returns : JB_ERR_OK on success, or
2185 * JB_ERR_MEMORY on out-of-memory error.
2187 *********************************************************************/
2188 jb_err client_host(struct client_state *csp, char **header)
2193 * If the header field name is all upper-case, chances are that it's
2194 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2195 * not a problem -- they are regenerated later.
2197 if ((*header)[1] == 'O')
2199 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2204 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2205 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2208 if (NULL == (p = strdup((*header)+6)))
2210 return JB_ERR_MEMORY;
2213 if (NULL == (q = strdup(p)))
2216 return JB_ERR_MEMORY;
2219 freez(csp->http->hostport);
2220 csp->http->hostport = p;
2221 freez(csp->http->host);
2222 csp->http->host = q;
2223 q = strchr(csp->http->host, ':');
2226 /* Terminate hostname and evaluate port string */
2228 csp->http->port = atoi(q);
2232 csp->http->port = csp->http->ssl ? 443 : 80;
2235 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2236 csp->http->hostport, csp->http->host, csp->http->port);
2242 /*********************************************************************
2244 * Function : client_if_modified_since
2246 * Description : Remove or modify the If-Modified-Since header.
2249 * 1 : csp = Current client state (buffers, headers, etc...)
2250 * 2 : header = On input, pointer to header to modify.
2251 * On output, pointer to the modified header, or NULL
2252 * to remove the header. This function frees the
2253 * original string if necessary.
2255 * Returns : JB_ERR_OK on success, or
2256 * JB_ERR_MEMORY on out-of-memory error.
2258 *********************************************************************/
2259 jb_err client_if_modified_since(struct client_state *csp, char **header)
2262 #ifdef HAVE_GMTIME_R
2265 struct tm *timeptr = NULL;
2269 long int hours, minutes, seconds;
2273 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2276 * The client got an error message because of a temporary problem,
2277 * the problem is gone and the client now tries to revalidate our
2278 * error message on the real server. The revalidation would always
2279 * end with the transmission of the whole document and there is
2280 * no need to expose the bogus If-Modified-Since header.
2282 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2285 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2287 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2289 if ((0 == strcmpic(newval, "block")))
2291 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2294 else /* add random value */
2296 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2298 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2303 rtime = strtol(newval, &endptr, 0);
2311 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2312 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2314 rtime = pick_from_range(rtime);
2318 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2322 #ifdef HAVE_GMTIME_R
2323 timeptr = gmtime_r(&tm, &gmt);
2325 pthread_mutex_lock(&gmtime_mutex);
2326 timeptr = gmtime(&tm);
2327 pthread_mutex_unlock(&gmtime_mutex);
2329 timeptr = gmtime(&tm);
2331 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2334 *header = strdup("If-Modified-Since: ");
2335 string_append(header, newheader);
2337 if (*header == NULL)
2339 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2340 return JB_ERR_MEMORY;
2343 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2345 hours = rtime / 3600;
2346 minutes = rtime / 60 % 60;
2347 seconds = rtime % 60;
2349 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2350 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2351 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2360 /*********************************************************************
2362 * Function : client_if_none_match
2364 * Description : Remove the If-None-Match header.
2367 * 1 : csp = Current client state (buffers, headers, etc...)
2368 * 2 : header = On input, pointer to header to modify.
2369 * On output, pointer to the modified header, or NULL
2370 * to remove the header. This function frees the
2371 * original string if necessary.
2373 * Returns : JB_ERR_OK on success, or
2374 * JB_ERR_MEMORY on out-of-memory error.
2376 *********************************************************************/
2377 jb_err client_if_none_match(struct client_state *csp, char **header)
2379 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2381 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2388 /*********************************************************************
2390 * Function : client_x_filter
2392 * Description : Disables filtering if the client set "X-Filter: No".
2393 * Called from `sed'.
2396 * 1 : csp = Current client state (buffers, headers, etc...)
2397 * 2 : header = On input, pointer to header to modify.
2398 * On output, pointer to the modified header, or NULL
2399 * to remove the header. This function frees the
2400 * original string if necessary.
2402 * Returns : JB_ERR_OK on success
2404 *********************************************************************/
2405 jb_err client_x_filter(struct client_state *csp, char **header)
2407 if ( 0 == strcmpic(*header, "X-Filter: No"))
2409 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2411 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2415 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2417 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2421 csp->content_type = CT_TABOO;
2422 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2424 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2431 /* the following functions add headers directly to the header list */
2433 /*********************************************************************
2435 * Function : client_host_adder
2437 * Description : Adds the Host: header field if it is missing.
2438 * Called from `sed'.
2441 * 1 : csp = Current client state (buffers, headers, etc...)
2443 * Returns : JB_ERR_OK on success, or
2444 * JB_ERR_MEMORY on out-of-memory error.
2446 *********************************************************************/
2447 jb_err client_host_adder(struct client_state *csp)
2452 if ( !csp->http->hostport || !*(csp->http->hostport))
2458 * remove 'user:pass@' from 'proto://user:pass@host'
2460 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2466 p = csp->http->hostport;
2469 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2470 err = enlist_unique_header(csp->headers, "Host", p);
2476 /*********************************************************************
2478 * Function : client_cookie_adder
2480 * Description : Used in the add_client_headers list. Called from `sed'.
2483 * 1 : csp = Current client state (buffers, headers, etc...)
2485 * Returns : JB_ERR_OK on success, or
2486 * JB_ERR_MEMORY on out-of-memory error.
2488 *********************************************************************/
2489 jb_err client_cookie_adder(struct client_state *csp)
2491 struct list_entry *lst;
2493 struct list_entry *list1 = csp->cookie_list->first;
2494 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2495 int first_cookie = 1;
2498 if ((list1 == NULL) && (list2 == NULL))
2504 tmp = strdup("Cookie: ");
2506 for (lst = list1; lst ; lst = lst->next)
2514 string_append(&tmp, "; ");
2516 string_append(&tmp, lst->str);
2519 for (lst = list2; lst ; lst = lst->next)
2527 string_append(&tmp, "; ");
2529 string_join(&tmp, cookie_encode(lst->str));
2534 return JB_ERR_MEMORY;
2537 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2538 err = enlist(csp->headers, tmp);
2544 /*********************************************************************
2546 * Function : client_accept_encoding_adder
2548 * Description : Add an Accept-Encoding header to the client's request
2549 * that disables compression if the action applies, and
2550 * the header is not already there. Called from `sed'.
2551 * Note: For HTTP/1.0, the absence of the header is enough.
2554 * 1 : csp = Current client state (buffers, headers, etc...)
2556 * Returns : JB_ERR_OK on success, or
2557 * JB_ERR_MEMORY on out-of-memory error.
2559 *********************************************************************/
2560 jb_err client_accept_encoding_adder(struct client_state *csp)
2562 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2563 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2565 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2572 /*********************************************************************
2574 * Function : client_xtra_adder
2576 * Description : Used in the add_client_headers list. Called from `sed'.
2579 * 1 : csp = Current client state (buffers, headers, etc...)
2581 * Returns : JB_ERR_OK on success, or
2582 * JB_ERR_MEMORY on out-of-memory error.
2584 *********************************************************************/
2585 jb_err client_xtra_adder(struct client_state *csp)
2587 struct list_entry *lst;
2590 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2591 lst ; lst = lst->next)
2593 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2594 err = enlist(csp->headers, lst->str);
2606 /*********************************************************************
2608 * Function : client_x_forwarded_adder
2610 * Description : Used in the add_client_headers list. Called from `sed'.
2613 * 1 : csp = Current client state (buffers, headers, etc...)
2615 * Returns : JB_ERR_OK on success, or
2616 * JB_ERR_MEMORY on out-of-memory error.
2618 *********************************************************************/
2619 jb_err client_x_forwarded_adder(struct client_state *csp)
2624 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2629 if (csp->x_forwarded)
2631 p = strdup(csp->x_forwarded);
2632 string_append(&p, ", ");
2636 p = strdup("X-Forwarded-For: ");
2638 string_append(&p, csp->ip_addr_str);
2642 return JB_ERR_MEMORY;
2645 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2646 err = enlist(csp->headers, p);
2653 /*********************************************************************
2655 * Function : connection_close_adder
2657 * Description : Adds a "Connection: close" header to csp->headers
2658 * as a temporary fix for the needed but missing HTTP/1.1
2659 * support. Called from `sed'.
2660 * FIXME: This whole function shouldn't be neccessary!
2663 * 1 : csp = Current client state (buffers, headers, etc...)
2665 * Returns : JB_ERR_OK on success, or
2666 * JB_ERR_MEMORY on out-of-memory error.
2668 *********************************************************************/
2669 jb_err connection_close_adder(struct client_state *csp)
2671 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2672 return enlist(csp->headers, "Connection: close");
2676 /*********************************************************************
2678 * Function : server_http
2680 * Description : - Save the HTTP Status into csp->http->status
2681 * - Set CT_TABOO to prevent filtering if the answer
2682 * is a partial range (HTTP status 206)
2683 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2688 * 2 : header = On input, pointer to header to modify.
2689 * On output, pointer to the modified header, or NULL
2690 * to remove the header. This function frees the
2691 * original string if necessary.
2693 * Returns : JB_ERR_OK on success, or
2694 * JB_ERR_MEMORY on out-of-memory error.
2696 *********************************************************************/
2697 jb_err server_http(struct client_state *csp, char **header)
2699 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2700 if (csp->http->status == 206)
2702 csp->content_type = CT_TABOO;
2705 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2708 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2715 /*********************************************************************
2717 * Function : server_set_cookie
2719 * Description : Handle the server "cookie" header properly.
2720 * Log cookie to the jar file. Then "crunch" it,
2721 * or accept it. Called from `sed'.
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2725 * 2 : header = On input, pointer to header to modify.
2726 * On output, pointer to the modified header, or NULL
2727 * to remove the header. This function frees the
2728 * original string if necessary.
2730 * Returns : JB_ERR_OK on success, or
2731 * JB_ERR_MEMORY on out-of-memory error.
2733 *********************************************************************/
2734 jb_err server_set_cookie(struct client_state *csp, char **header)
2736 #ifdef FEATURE_COOKIE_JAR
2737 if (csp->config->jar)
2740 * Write timestamp into outbuf.
2742 * Complex because not all OSs have tm_gmtoff or
2743 * the %z field in strftime()
2745 char tempbuf[ BUFFER_SIZE ];
2749 #ifdef HAVE_LOCALTIME_R
2750 tm_now = *localtime_r(&now, &tm_now);
2752 pthread_mutex_lock(&localtime_mutex);
2753 tm_now = *localtime (&now);
2754 pthread_mutex_unlock(&localtime_mutex);
2756 tm_now = *localtime (&now);
2758 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2760 /* strlen("set-cookie: ") = 12 */
2761 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2763 #endif /* def FEATURE_COOKIE_JAR */
2765 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2767 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2768 return crumble(csp, header);
2770 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2772 /* Flag whether or not to log a message */
2775 /* A variable to store the tag we're working on */
2778 /* Skip "Set-Cookie:" (11 characters) in header */
2779 cur_tag = *header + 11;
2781 /* skip whitespace between "Set-Cookie:" and value */
2782 while (*cur_tag && ijb_isspace(*cur_tag))
2787 /* Loop through each tag in the cookie */
2791 char *next_tag = strchr(cur_tag, ';');
2792 if (next_tag != NULL)
2794 /* Skip the ';' character itself */
2797 /* skip whitespace ";" and start of tag */
2798 while (*next_tag && ijb_isspace(*next_tag))
2805 /* "Next tag" is the end of the string */
2806 next_tag = cur_tag + strlen(cur_tag);
2809 /* Is this the "Expires" tag? */
2810 if (strncmpic(cur_tag, "expires=", 8) == 0)
2812 /* Delete the tag by copying the rest of the string over it.
2813 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2814 * since the behaviour of strcpy is undefined for overlapping
2817 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2819 /* That changed the header, need to issue a log message */
2822 /* Note that the next tag has now been moved to *cur_tag,
2823 * so we do not need to update the cur_tag pointer.
2828 /* Move on to next cookie tag */
2835 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2843 #ifdef FEATURE_FORCE_LOAD
2844 /*********************************************************************
2846 * Function : strclean
2848 * Description : In-Situ-Eliminate all occurances of substring in
2852 * 1 : string = string to clean
2853 * 2 : substring = substring to eliminate
2855 * Returns : Number of eliminations
2857 *********************************************************************/
2858 int strclean(const char *string, const char *substring)
2860 int hits = 0, len = strlen(substring);
2863 while((pos = strstr(string, substring)) != NULL)
2870 while (*p++ != '\0');
2877 #endif /* def FEATURE_FORCE_LOAD */
2879 /*********************************************************************
2881 * Function : parse_header_time
2883 * Description : Transforms time inside a HTTP header into
2884 * the usual time format.
2887 * 1 : header = header to parse
2888 * 2 : tm = storage for the resulting time in seconds
2890 * Returns : Time struct containing the header time, or
2891 * NULL in case of a parsing problem.
2893 *********************************************************************/
2894 struct tm *parse_header_time(char *header, time_t *tm) {
2898 struct tm * timeptr;
2900 /* Skipping header name */
2901 timestring = strstr(header, ": ");
2902 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)