1 const char parsers_rcs[] = "$Id: parsers.c,v 1.73 2006/09/23 13:26:38 roro 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.73 2006/09/23 13:26:38 roro
44 * Replace TABs by spaces in source code.
46 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
47 * Don't print a log message every time filter_headers is
48 * entered or left. It only creates noise without any real
51 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
52 * Fix +hide-if-modified-since{-n}.
54 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
55 * Have hide-if-modified-since interpret the random
56 * range value as minutes instead of hours. Allows
57 * more fine-grained configuration.
59 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
60 * Always have parse_header_time return a pointer
61 * that actual makes sense, even though we currently
62 * only need it to detect problems.
64 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
65 * Added config option enable-remote-http-toggle
66 * to specify if Privoxy should recognize special
67 * headers (currently only X-Filter) to change its
68 * behaviour. Disabled by default.
70 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
71 * After filtering de-chunked instances, remove
72 * "Transfer-Encoding" header entirely instead of changing
73 * it to "Transfer-Encoding: identity", which is invalid.
74 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
76 * Don't use localtime in parse_header_time. An empty time struct
77 * is good enough, it gets overwritten by strptime anyway.
79 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
80 * Use gmtime_r if available, fallback to gmtime with mutex
81 * protection for MacOSX and use vanilla gmtime for the rest.
83 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
84 * Changed client_referrer to use the right type (size_t) for
85 * hostlenght and to shorten the temporary referrer string with
86 * '\0' instead of adding a useless line break.
88 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
89 * - Back to timegm() using GnuPG's replacement if necessary.
90 * Using mktime() and localtime() could add a on hour offset if
91 * the randomize factor was big enough to lead to a summer/wintertime
94 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
96 * - Moved randomization code into pick_from_range().
98 * - Changed parse_header_time definition.
99 * time_t isn't guaranteed to be signed and
100 * if it isn't, -1 isn't available as error code.
101 * Changed some variable types in client_if_modified_since()
102 * because of the same reason.
104 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
105 * OS/2 compilation compatibility fixups
107 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
108 * Changed include from strptime.c to strptime.h
110 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
111 * Split filter-headers{} into filter-client-headers{}
112 * and filter-server-headers{}.
113 * Added parse_header_time() to share some code.
114 * Replaced timegm() with mktime().
116 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
117 * Windows service integration
119 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
120 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
122 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
123 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
124 * with what was really the latest development (the v_3_0_branch branch)
126 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
127 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
129 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
130 * Add the ability to check jpeg images for invalid
131 * lengths of comment blocks. Defensive strategy
132 * against the exploit:
133 * Microsoft Security Bulletin MS04-028
134 * Buffer Overrun in JPEG Processing (GDI+) Could
135 * Allow Code Execution (833987)
136 * Enabled with +inspect-jpegs in actions files.
138 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
139 * Excluded text/plain objects from filtering. This fixes a
140 * couple of client-crashing, download corruption and
141 * Privoxy performance issues, whose root cause lies in
142 * web servers labelling content of unknown type as text/plain.
144 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
145 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
147 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
148 * Completing the previous change
150 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
151 * Added temporary workaround for bug in PHP < 4.2.3
153 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
154 * 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.
156 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
157 * Fix typo: supressed -> suppressed
159 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
160 * Improved cookie logging
162 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
163 * Added basic support for OPTIONS and TRACE HTTP methods:
164 * - New parser function client_max_forwards which decrements
165 * the Max-Forwards HTTP header field of OPTIONS and TRACE
166 * requests by one before forwarding
167 * - New parser function client_host which extracts the host
168 * and port information from the HTTP header field if the
169 * request URI was not absolute
170 * - Don't crumble and re-add the Host: header, but only generate
171 * and append if missing
173 * Revision 1.56 2002/05/12 15:34:22 jongfoster
174 * Fixing typo in a comment
176 * Revision 1.55 2002/05/08 16:01:07 oes
177 * Optimized add_to_iob:
178 * - Use realloc instead of malloc(), memcpy(), free()
179 * - Expand to powers of two if possible, to get
180 * O(log n) reallocs instead of O(n).
181 * - Moved check for buffer limit here from chat
182 * - Report failure via returncode
184 * Revision 1.54 2002/04/02 15:03:16 oes
185 * Tiny code cosmetics
187 * Revision 1.53 2002/03/26 22:29:55 swa
188 * we have a new homepage!
190 * Revision 1.52 2002/03/24 13:25:43 swa
191 * name change related issues
193 * Revision 1.51 2002/03/13 00:27:05 jongfoster
196 * Revision 1.50 2002/03/12 01:45:35 oes
197 * More verbose logging
199 * Revision 1.49 2002/03/09 20:03:52 jongfoster
200 * - Making various functions return int rather than size_t.
201 * (Undoing a recent change). Since size_t is unsigned on
202 * Windows, functions like read_socket that return -1 on
203 * error cannot return a size_t.
205 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
206 * crashes, and also frequently caused JB to jump to 100%
207 * CPU and stay there. (Because it thought it had just
208 * read ((unsigned)-1) == 4Gb of data...)
210 * - The signature of write_socket has changed, it now simply
211 * returns success=0/failure=nonzero.
213 * - Trying to get rid of a few warnings --with-debug on
214 * Windows, I've introduced a new type "jb_socket". This is
215 * used for the socket file descriptors. On Windows, this
216 * is SOCKET (a typedef for unsigned). Everywhere else, it's
217 * an int. The error value can't be -1 any more, so it's
218 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
219 * Windows it maps to the #define INVALID_SOCKET.)
221 * - The signature of bind_port has changed.
223 * Revision 1.48 2002/03/07 03:46:53 oes
224 * Fixed compiler warnings etc
226 * Revision 1.47 2002/02/20 23:15:13 jongfoster
227 * Parsing functions now handle out-of-memory gracefully by returning
230 * Revision 1.46 2002/01/17 21:03:47 jongfoster
231 * Moving all our URL and URL pattern parsing code to urlmatch.c.
233 * Revision 1.45 2002/01/09 14:33:03 oes
234 * Added support for localtime_r.
236 * Revision 1.44 2001/12/14 01:22:54 steudten
237 * Remove 'user:pass@' from 'proto://user:pass@host' for the
238 * new added header 'Host: ..'. (See Req ID 491818)
240 * Revision 1.43 2001/11/23 00:26:38 jongfoster
241 * Fixing two really stupid errors in my previous commit
243 * Revision 1.42 2001/11/22 21:59:30 jongfoster
244 * Adding code to handle +no-cookies-keep
246 * Revision 1.41 2001/11/05 23:43:05 steudten
247 * Add time+date to log files.
249 * Revision 1.40 2001/10/26 20:13:09 jongfoster
250 * ctype.h is needed in Windows, too.
252 * Revision 1.39 2001/10/26 17:40:04 oes
253 * Introduced get_header_value()
254 * Removed http->user_agent, csp->referrer and csp->accept_types
255 * Removed client_accept()
257 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
258 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
259 * threads to call select() simultaneously. So, it's time to do a real, live,
260 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
261 * (native). Both versions will work, but using __OS2__ offers multi-threading.
263 * Revision 1.37 2001/10/23 21:36:02 jongfoster
264 * Documenting sed()'s error behaviou (doc change only)
266 * Revision 1.36 2001/10/13 12:51:51 joergs
267 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
268 * force-load), instead crumble Host: and add it (again) in client_host_adder
269 * (in case we get a HTTP/1.0 request without Host: header and forward it to
270 * a HTTP/1.1 server/proxy).
272 * Revision 1.35 2001/10/09 22:39:21 jongfoster
273 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
276 * Revision 1.34 2001/10/07 18:50:55 oes
277 * Added server_content_encoding, renamed server_transfer_encoding
279 * Revision 1.33 2001/10/07 18:04:49 oes
280 * Changed server_http11 to server_http and its pattern to "HTTP".
281 * Additional functionality: it now saves the HTTP status into
282 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
284 * Revision 1.32 2001/10/07 15:43:28 oes
285 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
286 * client_te and client_accept_encoding_adder, triggered by the new
287 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
288 * changed to allow only identity and chunked, and the TE header is
289 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
291 * parse_http_request no longer does anything than parsing. The rewriting
292 * of http->cmd and version mangling are gone. It now also recognizes
293 * the put and delete methods and saves the url in http->url. Removed
296 * renamed content_type and content_length to have the server_ prefix
298 * server_content_type now only works if csp->content_type != CT_TABOO
300 * added server_transfer_encoding, which
301 * - Sets CT_TABOO to prohibit filtering if encoding compresses
302 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
303 * - Change from "chunked" to "identity" if body was chunked
304 * but has been de-chunked for filtering.
306 * added server_content_md5 which crunches any Content-MD5 headers
307 * if the body was modified.
309 * made server_http11 conditional on +downgrade action
311 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
313 * Revision 1.31 2001/10/05 14:25:02 oes
314 * Crumble Keep-Alive from Server
316 * Revision 1.30 2001/09/29 12:56:03 joergs
317 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
319 * Revision 1.29 2001/09/24 21:09:24 jongfoster
320 * Fixing 2 memory leaks that Guy spotted, where the paramater to
321 * enlist() was not being free()d.
323 * Revision 1.28 2001/09/22 16:32:28 jongfoster
324 * Removing unused #includes.
326 * Revision 1.27 2001/09/20 15:45:25 steudten
328 * add casting from size_t to int for printf()
329 * remove local variable shadow s2
331 * Revision 1.26 2001/09/16 17:05:14 jongfoster
332 * Removing unused #include showarg.h
334 * Revision 1.25 2001/09/16 13:21:27 jongfoster
335 * Changes to use new list functions.
337 * Revision 1.24 2001/09/13 23:05:50 jongfoster
338 * Changing the string paramater to the header parsers a "const".
340 * Revision 1.23 2001/09/12 18:08:19 steudten
342 * In parse_http_request() header rewriting miss the host value, so
343 * from http://www.mydomain.com the result was just " / " not
344 * http://www.mydomain.com/ in case we forward.
346 * Revision 1.22 2001/09/10 10:58:53 oes
347 * Silenced compiler warnings
349 * Revision 1.21 2001/07/31 14:46:00 oes
350 * - Persistant connections now suppressed
351 * - sed() no longer appends empty header to csp->headers
353 * Revision 1.20 2001/07/30 22:08:36 jongfoster
354 * Tidying up #defines:
355 * - All feature #defines are now of the form FEATURE_xxx
356 * - Permanently turned off WIN_GUI_EDIT
357 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
359 * Revision 1.19 2001/07/25 17:21:54 oes
360 * client_uagent now saves copy of User-Agent: header value
362 * Revision 1.18 2001/07/13 14:02:46 oes
363 * - Included fix to repair broken HTTP requests that
364 * don't contain a path, not even '/'.
365 * - Removed all #ifdef PCRS
366 * - content_type now always inspected and classified as
367 * text, gif or other.
368 * - formatting / comments
370 * Revision 1.17 2001/06/29 21:45:41 oes
371 * Indentation, CRLF->LF, Tab-> Space
373 * Revision 1.16 2001/06/29 13:32:42 oes
375 * - Adapted free_http_request
376 * - Removed logentry from cancelled commit
378 * Revision 1.15 2001/06/03 19:12:38 oes
379 * deleted const struct interceptors
381 * Revision 1.14 2001/06/01 18:49:17 jongfoster
382 * Replaced "list_share" with "list" - the tiny memory gain was not
383 * worth the extra complexity.
385 * Revision 1.13 2001/05/31 21:30:33 jongfoster
386 * Removed list code - it's now in list.[ch]
387 * Renamed "permission" to "action", and changed many features
388 * to use the actions file rather than the global config.
390 * Revision 1.12 2001/05/31 17:33:13 oes
394 * Revision 1.11 2001/05/29 20:11:19 joergs
395 * '/ * inside comment' warning removed.
397 * Revision 1.10 2001/05/29 09:50:24 jongfoster
398 * Unified blocklist/imagelist/permissionslist.
399 * File format is still under discussion, but the internal changes
402 * Also modified interceptor behaviour:
403 * - We now intercept all URLs beginning with one of the following
404 * prefixes (and *only* these prefixes):
406 * * http://ijbswa.sf.net/config/
407 * * http://ijbswa.sourceforge.net/config/
408 * - New interceptors "home page" - go to http://i.j.b/ to see it.
409 * - Internal changes so that intercepted and fast redirect pages
410 * are not replaced with an image.
411 * - Interceptors now have the option to send a binary page direct
412 * to the client. (i.e. ijb-send-banner uses this)
413 * - Implemented show-url-info interceptor. (Which is why I needed
414 * the above interceptors changes - a typical URL is
415 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
416 * The previous mechanism would not have intercepted that, and
417 * if it had been intercepted then it then it would have replaced
420 * Revision 1.9 2001/05/28 17:26:33 jongfoster
421 * Fixing segfault if last header was crunched.
422 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
423 * can use the cross-platform sprintf() instead.)
425 * Revision 1.8 2001/05/27 22:17:04 oes
427 * - re_process_buffer no longer writes the modified buffer
428 * to the client, which was very ugly. It now returns the
429 * buffer, which it is then written by chat.
431 * - content_length now adjusts the Content-Length: header
432 * for modified documents rather than crunch()ing it.
433 * (Length info in csp->content_length, which is 0 for
434 * unmodified documents)
436 * - For this to work, sed() is called twice when filtering.
438 * Revision 1.7 2001/05/27 13:19:06 oes
439 * Patched Joergs solution for the content-length in.
441 * Revision 1.6 2001/05/26 13:39:32 jongfoster
442 * Only crunches Content-Length header if applying RE filtering.
443 * Without this fix, Microsoft Windows Update wouldn't work.
445 * Revision 1.5 2001/05/26 00:28:36 jongfoster
446 * Automatic reloading of config file.
447 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
448 * Most of the global variables have been moved to a new
449 * struct configuration_spec, accessed through csp->config->globalname
450 * Most of the globals remaining are used by the Win32 GUI.
452 * Revision 1.4 2001/05/22 18:46:04 oes
454 * - Enabled filtering banners by size rather than URL
455 * by adding patterns that replace all standard banner
456 * sizes with the "Junkbuster" gif to the re_filterfile
458 * - Enabled filtering WebBugs by providing a pattern
459 * which kills all 1x1 images
461 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
462 * which is selected by the (nonstandard and therefore
463 * capital) letter 'U' in the option string.
464 * It causes the quantifiers to be ungreedy by default.
465 * Appending a ? turns back to greedy (!).
467 * - Added a new interceptor ijb-send-banner, which
468 * sends back the "Junkbuster" gif. Without imagelist or
469 * MSIE detection support, or if tinygif = 1, or the
470 * URL isn't recognized as an imageurl, a lame HTML
471 * explanation is sent instead.
473 * - Added new feature, which permits blocking remote
474 * script redirects and firing back a local redirect
476 * The feature is conditionally compiled, i.e. it
477 * can be disabled with --disable-fast-redirects,
478 * plus it must be activated by a "fast-redirects"
479 * line in the config file, has its own log level
480 * and of course wants to be displayed by show-proxy-args
481 * Note: Boy, all the #ifdefs in 1001 locations and
482 * all the fumbling with configure.in and acconfig.h
483 * were *way* more work than the feature itself :-(
485 * - Because a generic redirect template was needed for
486 * this, tinygif = 3 now uses the same.
488 * - Moved GIFs, and other static HTTP response templates
493 * - Removed some >400 CRs again (Jon, you really worked
496 * Revision 1.3 2001/05/20 01:21:20 jongfoster
497 * Version 2.9.4 checkin.
498 * - Merged popupfile and cookiefile, and added control over PCRS
499 * filtering, in new "permissionsfile".
500 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
501 * file error you now get a message box (in the Win32 GUI) rather
502 * than the program exiting with no explanation.
503 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
505 * - Removed tabs from "config"
506 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
507 * - Bumped up version number.
509 * Revision 1.2 2001/05/17 23:02:36 oes
510 * - Made referrer option accept 'L' as a substitute for '§'
512 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
513 * Initial import of version 2.9.3 source tree
516 *********************************************************************/
523 #include <sys/types.h>
532 #if !defined(_WIN32) && !defined(__OS2__)
541 /* jcc.h is for mutex semapores only */
542 #endif /* def OSX_DARWIN */
548 #include "jbsockets.h"
549 #include "miscutil.h"
552 #ifndef HAVE_STRPTIME
553 #include "strptime.h"
556 const char parsers_h_rcs[] = PARSERS_H_VERSION;
558 /* Fix a problem with Solaris. There should be no effect on other
560 * Solaris's isspace() is a macro which uses it's argument directly
561 * as an array index. Therefore we need to make sure that high-bit
562 * characters generate +ve values, and ideally we also want to make
563 * the argument match the declared parameter type of "int".
565 * Why did they write a character function that can't take a simple
566 * "char" argument? Doh!
568 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
569 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
572 const struct parsers client_patterns[] = {
573 { "referer:", 8, client_referrer },
574 { "user-agent:", 11, client_uagent },
575 { "ua-", 3, client_ua },
576 { "from:", 5, client_from },
577 { "cookie:", 7, client_send_cookie },
578 { "x-forwarded-for:", 16, client_x_forwarded },
579 { "Accept-Encoding:", 16, client_accept_encoding },
580 { "TE:", 3, client_te },
581 { "Host:", 5, client_host },
582 { "if-modified-since:", 18, client_if_modified_since },
583 { "Keep-Alive:", 11, crumble },
584 { "connection:", 11, crumble },
585 { "proxy-connection:", 17, crumble },
586 { "max-forwards:", 13, client_max_forwards },
587 { "Accept-Language:", 16, client_accept_language },
588 { "if-none-match:", 14, client_if_none_match },
589 { "X-Filter:", 9, client_x_filter },
590 { "*", 0, crunch_client_header },
591 { "*", 0, filter_client_header },
595 const struct parsers server_patterns[] = {
596 { "HTTP", 4, server_http },
597 { "set-cookie:", 11, server_set_cookie },
598 { "connection:", 11, crumble },
599 { "Content-Type:", 13, server_content_type },
600 { "Content-Length:", 15, server_content_length },
601 { "Content-MD5:", 12, server_content_md5 },
602 { "Content-Encoding:", 17, server_content_encoding },
603 { "Transfer-Encoding:", 18, server_transfer_coding },
604 { "Keep-Alive:", 11, crumble },
605 { "content-disposition:", 20, server_content_disposition },
606 { "Last-Modified:", 14, server_last_modified },
607 { "*", 0, crunch_server_header },
608 { "*", 0, filter_server_header },
612 const struct parsers server_patterns_light[] = {
613 { "Content-Length:", 15, server_content_length },
614 { "Transfer-Encoding:", 18, server_transfer_coding },
618 const add_header_func_ptr add_client_headers[] = {
621 client_x_forwarded_adder,
623 /* Temporarily disabled: client_accept_encoding_adder, */
624 connection_close_adder,
629 const add_header_func_ptr add_server_headers[] = {
630 connection_close_adder,
634 /*********************************************************************
636 * Function : flush_socket
638 * Description : Write any pending "buffered" content.
641 * 1 : fd = file descriptor of the socket to read
642 * 2 : csp = Current client state (buffers, headers, etc...)
644 * Returns : On success, the number of bytes written are returned (zero
645 * indicates nothing was written). On error, -1 is returned,
646 * and errno is set appropriately. If count is zero and the
647 * file descriptor refers to a regular file, 0 will be
648 * returned without causing any other effect. For a special
649 * file, the results are not portable.
651 *********************************************************************/
652 int flush_socket(jb_socket fd, struct client_state *csp)
654 struct iob *iob = csp->iob;
655 int len = iob->eod - iob->cur;
662 if (write_socket(fd, iob->cur, (size_t)len))
666 iob->eod = iob->cur = iob->buf;
672 /*********************************************************************
674 * Function : add_to_iob
676 * Description : Add content to the buffered page, expanding the
677 * buffer if necessary.
680 * 1 : csp = Current client state (buffers, headers, etc...)
681 * 2 : buf = holds the content to be added to the page
682 * 3 : n = number of bytes to be added
684 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
685 * or buffer limit reached.
687 *********************************************************************/
688 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
690 struct iob *iob = csp->iob;
691 size_t used, offset, need, want;
694 if (n <= 0) return JB_ERR_OK;
696 used = iob->eod - iob->buf;
697 offset = iob->cur - iob->buf;
701 * If the buffer can't hold the new data, extend it first.
702 * Use the next power of two if possible, else use the actual need.
704 if (need > csp->config->buffer_limit)
706 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
707 return JB_ERR_MEMORY;
710 if (need > iob->size)
712 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
714 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
718 else if (NULL != (p = (char *)realloc(iob->buf, need)))
724 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
725 return JB_ERR_MEMORY;
728 /* Update the iob pointers */
729 iob->cur = p + offset;
734 /* copy the new data into the iob buffer */
735 memcpy(iob->eod, buf, (size_t)n);
737 /* point to the end of the data */
740 /* null terminate == cheap insurance */
748 /*********************************************************************
750 * Function : get_header
752 * Description : This (odd) routine will parse the csp->iob
755 * 1 : csp = Current client state (buffers, headers, etc...)
757 * Returns : Any one of the following:
759 * 1) a pointer to a dynamically allocated string that contains a header line
760 * 2) NULL indicating that the end of the header was reached
761 * 3) "" indicating that the end of the iob was reached before finding
762 * a complete header line.
764 *********************************************************************/
765 char *get_header(struct client_state *csp)
771 if ((iob->cur == NULL)
772 || ((p = strchr(iob->cur, '\n')) == NULL))
774 return(""); /* couldn't find a complete header */
779 ret = strdup(iob->cur);
782 /* FIXME No way to handle error properly */
783 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
788 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
790 /* is this a blank line (i.e. the end of the header) ? */
802 /*********************************************************************
804 * Function : get_header_value
806 * Description : Get the value of a given header from a chained list
807 * of header lines or return NULL if no such header is
808 * present in the list.
811 * 1 : header_list = pointer to list
812 * 2 : header_name = string with name of header to look for.
813 * Trailing colon required, capitalization
816 * Returns : NULL if not found, else value of header
818 *********************************************************************/
819 char *get_header_value(const struct list *header_list, const char *header_name)
821 struct list_entry *cur_entry;
827 length = strlen(header_name);
829 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
833 if (!strncmpic(cur_entry->str, header_name, length))
836 * Found: return pointer to start of value
838 ret = (char *) (cur_entry->str + length);
839 while (*ret && ijb_isspace(*ret)) ret++;
852 /*********************************************************************
856 * Description : add, delete or modify lines in the HTTP header streams.
857 * On entry, it receives a linked list of headers space
858 * that was allocated dynamically (both the list nodes
859 * and the header contents).
861 * As a side effect it frees the space used by the original
865 * 1 : pats = list of patterns to match against headers
866 * 2 : more_headers = list of functions to add more
867 * headers (client or server)
868 * 3 : csp = Current client state (buffers, headers, etc...)
870 * Returns : Single pointer to a fully formed header, or NULL
871 * on out-of-memory error.
873 *********************************************************************/
874 char *sed(const struct parsers pats[],
875 const add_header_func_ptr more_headers[],
876 struct client_state *csp)
878 struct list_entry *p;
879 const struct parsers *v;
880 const add_header_func_ptr *f;
881 jb_err err = JB_ERR_OK;
885 * If filtering is enabled, sed is run twice,
886 * but most of the work needs to be done only once.
888 first_run = (more_headers != NULL ) ? 1 : 0;
890 if (first_run) /* Parse and print */
892 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
894 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
896 /* Header crunch()ed in previous run? -> ignore */
897 if (p->str == NULL) continue;
899 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
901 /* Does the current parser handle this header? */
902 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
904 err = v->parser(csp, (char **)&(p->str));
908 /* place any additional headers on the csp->headers list */
909 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
914 else /* Parse only */
917 * The second run is only needed if the body was modified
918 * and the content-lenght has changed.
920 if (strncmpic(csp->http->cmd, "HEAD", 4))
922 /*XXX: Code duplication*/
923 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
925 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
927 /* Header crunch()ed in previous run? -> ignore */
928 if (p->str == NULL) continue;
930 /* Does the current parser handle this header? */
931 if (strncmpic(p->str, v->str, v->len) == 0)
933 err = v->parser(csp, (char **)&(p->str));
940 if (err != JB_ERR_OK)
945 return list_to_text(csp->headers);
949 /* here begins the family of parser functions that reformat header lines */
951 /*********************************************************************
953 * Function : filter_server_header
955 * Description : Checks if server header filtering is enabled.
956 * If it is, filter_header is called to do the work.
959 * 1 : csp = Current client state (buffers, headers, etc...)
960 * 2 : header = On input, pointer to header to modify.
961 * On output, pointer to the modified header, or NULL
962 * to remove the header. This function frees the
963 * original string if necessary.
965 * Returns : JB_ERR_OK on success and always succeeds
967 *********************************************************************/
968 jb_err filter_server_header(struct client_state *csp, char **header)
970 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
972 filter_header(csp, header);
977 /*********************************************************************
979 * Function : filter_client_header
981 * Description : Checks if client header filtering is enabled.
982 * If it is, filter_header is called to do the work.
985 * 1 : csp = Current client state (buffers, headers, etc...)
986 * 2 : header = On input, pointer to header to modify.
987 * On output, pointer to the modified header, or NULL
988 * to remove the header. This function frees the
989 * original string if necessary.
991 * Returns : JB_ERR_OK on success and always succeeds
993 *********************************************************************/
994 jb_err filter_client_header(struct client_state *csp, char **header)
996 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
998 filter_header(csp, header);
1003 /*********************************************************************
1005 * Function : filter_header
1007 * Description : Executes all text substitutions from all applying
1008 * +filter actions on the header.
1009 * Most of the code was copied from pcrs_filter_response,
1010 * including the rather short variable names
1013 * 1 : csp = Current client state (buffers, headers, etc...)
1014 * 2 : header = On input, pointer to header to modify.
1015 * On output, pointer to the modified header, or NULL
1016 * to remove the header. This function frees the
1017 * original string if necessary.
1019 * Returns : JB_ERR_OK on success and always succeeds
1021 *********************************************************************/
1022 jb_err filter_header(struct client_state *csp, char **header)
1026 size_t size = strlen(*header);
1028 char *newheader = NULL;
1031 struct file_list *fl;
1032 struct re_filterfile_spec *b;
1033 struct list_entry *filtername;
1035 int i, found_filters = 0;
1038 * Need to check the set of re_filterfiles...
1040 for (i = 0; i < MAX_AF_FILES; i++)
1053 if (0 == found_filters)
1055 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1059 for (i = 0; i < MAX_AF_FILES; i++)
1062 if ((NULL == fl) || (NULL == fl->f))
1065 * For all applying +filter actions, look if a filter by that
1066 * name exists and if yes, execute its pcrs_joblist on the
1069 for (b = fl->f; b; b = b->next)
1071 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1072 filtername ; filtername = filtername->next)
1074 if (strcmp(b->name, filtername->str) == 0)
1076 int current_hits = 0;
1078 if ( NULL == b->joblist )
1080 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1084 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1085 *header, size, b->name);
1087 /* Apply all jobs from the joblist */
1088 for (job = b->joblist; NULL != job; job = job->next)
1090 matches = pcrs_execute(job, *header, size, &newheader, &size);
1093 current_hits += matches;
1094 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1096 *header = newheader;
1098 else if ( 0 == matches )
1100 /* Filter doesn't change header */
1106 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1107 *header, b->name, pcrs_strerror(matches));
1108 if( newheader != NULL)
1110 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1115 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1116 hits += current_hits;
1124 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1132 /*********************************************************************
1134 * Function : crumble
1136 * Description : This is called if a header matches a pattern to "crunch"
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, or
1146 * JB_ERR_MEMORY on out-of-memory error.
1148 *********************************************************************/
1149 jb_err crumble(struct client_state *csp, char **header)
1151 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1156 /*********************************************************************
1158 * Function : crunch_server_header
1160 * Description : Crunch server header if it matches a string supplied by the
1161 * user. Called from `sed'.
1164 * 1 : csp = Current client state (buffers, headers, etc...)
1165 * 2 : header = On input, pointer to header to modify.
1166 * On output, pointer to the modified header, or NULL
1167 * to remove the header. This function frees the
1168 * original string if necessary.
1170 * Returns : JB_ERR_OK on success and always succeeds
1172 *********************************************************************/
1173 jb_err crunch_server_header(struct client_state *csp, char **header)
1175 const char *crunch_pattern;
1176 /*Is there a header to crunch*/
1178 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1180 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1182 /*Is the current header the lucky one?*/
1183 if (strstr(*header, crunch_pattern))
1185 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1192 /*********************************************************************
1194 * Function : server_content_type
1196 * Description : Set the content-type for filterable types (text/.*,
1197 * javascript and image/gif) unless filtering has been
1198 * forbidden (CT_TABOO) while parsing earlier headers.
1199 * NOTE: Since text/plain is commonly used by web servers
1200 * for files whose correct type is unknown, we don't
1201 * set CT_TEXT for it.
1204 * 1 : csp = Current client state (buffers, headers, etc...)
1205 * 2 : header = On input, pointer to header to modify.
1206 * On output, pointer to the modified header, or NULL
1207 * to remove the header. This function frees the
1208 * original string if necessary.
1210 * Returns : JB_ERR_OK on success, or
1211 * JB_ERR_MEMORY on out-of-memory error.
1213 *********************************************************************/
1214 jb_err server_content_type(struct client_state *csp, char **header)
1218 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1220 if (csp->content_type != CT_TABOO)
1222 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1223 || strstr(*header, "xml")
1224 || strstr(*header, "application/x-javascript"))
1225 csp->content_type = CT_TEXT;
1226 else if (strstr(*header, " image/gif"))
1227 csp->content_type = CT_GIF;
1228 else if (strstr(*header, " image/jpeg"))
1229 csp->content_type = CT_JPEG;
1231 csp->content_type = 0;
1234 * Are we enabling text mode by force?
1236 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1239 * Do we really have to?
1241 if (csp->content_type == CT_TEXT)
1243 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1247 csp->content_type = CT_TEXT;
1248 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1252 * Are we messing with the content type?
1254 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1257 * Make sure the user doesn't accidently
1258 * change the content type of binary documents.
1260 if (csp->content_type == CT_TEXT)
1263 *header = strdup("Content-Type: ");
1264 string_append(header, newval);
1268 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1269 return JB_ERR_MEMORY;
1271 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1275 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1276 "Enable force-text-mode if you know what you're doing.", *header);
1283 /*********************************************************************
1285 * Function : server_transfer_coding
1287 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1288 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1289 * - Remove header if body was chunked but has been
1290 * de-chunked for filtering.
1293 * 1 : csp = Current client state (buffers, headers, etc...)
1294 * 2 : header = On input, pointer to header to modify.
1295 * On output, pointer to the modified header, or NULL
1296 * to remove the header. This function frees the
1297 * original string if necessary.
1299 * Returns : JB_ERR_OK on success, or
1300 * JB_ERR_MEMORY on out-of-memory error.
1302 *********************************************************************/
1303 jb_err server_transfer_coding(struct client_state *csp, char **header)
1306 * Turn off pcrs and gif filtering if body compressed
1308 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1310 csp->content_type = CT_TABOO;
1314 * Raise flag if body chunked
1316 if (strstr(*header, "chunked"))
1318 csp->flags |= CSP_FLAG_CHUNKED;
1321 * If the body was modified, it has been de-chunked first
1322 * and the header must be removed.
1324 if (csp->flags & CSP_FLAG_MODIFIED)
1326 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1335 /*********************************************************************
1337 * Function : server_content_encoding
1339 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1342 * 1 : csp = Current client state (buffers, headers, etc...)
1343 * 2 : header = On input, pointer to header to modify.
1344 * On output, pointer to the modified header, or NULL
1345 * to remove the header. This function frees the
1346 * original string if necessary.
1348 * Returns : JB_ERR_OK on success, or
1349 * JB_ERR_MEMORY on out-of-memory error.
1351 *********************************************************************/
1352 jb_err server_content_encoding(struct client_state *csp, char **header)
1355 * Turn off pcrs and gif filtering if body compressed
1357 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1359 csp->content_type = CT_TABOO;
1367 /*********************************************************************
1369 * Function : server_content_length
1371 * Description : Adjust Content-Length header if we modified
1375 * 1 : csp = Current client state (buffers, headers, etc...)
1376 * 2 : header = On input, pointer to header to modify.
1377 * On output, pointer to the modified header, or NULL
1378 * to remove the header. This function frees the
1379 * original string if necessary.
1381 * Returns : JB_ERR_OK on success, or
1382 * JB_ERR_MEMORY on out-of-memory error.
1384 *********************************************************************/
1385 jb_err server_content_length(struct client_state *csp, char **header)
1387 if (csp->content_length != 0) /* Content length could have been modified */
1390 * XXX: Shouldn't we check if csp->content_length
1391 * is different than the original value?
1394 *header = (char *) zalloc(100);
1395 if (*header == NULL)
1397 return JB_ERR_MEMORY;
1400 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1402 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1409 /*********************************************************************
1411 * Function : server_content_md5
1413 * Description : Crumble any Content-MD5 headers if the document was
1414 * modified. FIXME: Should we re-compute instead?
1417 * 1 : csp = Current client state (buffers, headers, etc...)
1418 * 2 : header = On input, pointer to header to modify.
1419 * On output, pointer to the modified header, or NULL
1420 * to remove the header. This function frees the
1421 * original string if necessary.
1423 * Returns : JB_ERR_OK on success, or
1424 * JB_ERR_MEMORY on out-of-memory error.
1426 *********************************************************************/
1427 jb_err server_content_md5(struct client_state *csp, char **header)
1429 if (csp->flags & CSP_FLAG_MODIFIED)
1431 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1438 /*********************************************************************
1440 * Function : server_content_disposition
1442 * Description : If enabled, blocks or modifies the "content-disposition" header.
1443 * Called from `sed'.
1446 * 1 : csp = Current client state (buffers, headers, etc...)
1447 * 2 : header = On input, pointer to header to modify.
1448 * On output, pointer to the modified header, or NULL
1449 * to remove the header. This function frees the
1450 * original string if necessary.
1452 * Returns : JB_ERR_OK on success, or
1453 * JB_ERR_MEMORY on out-of-memory error.
1455 *********************************************************************/
1456 jb_err server_content_disposition(struct client_state *csp, char **header)
1461 * Are we messing with the content-disposition header?
1463 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1469 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1471 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1474 * Blocking content-disposition header
1476 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1483 * Replacing content-disposition header
1486 *header = strdup("content-disposition: ");
1487 string_append(header, newval);
1489 if (*header == NULL)
1491 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1495 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1498 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1501 /*********************************************************************
1503 * Function : server_last_modified
1505 * Description : Changes Last-Modified header to the actual date
1506 * to help hide-if-modified-since.
1507 * Called from `sed'.
1510 * 1 : csp = Current client state (buffers, headers, etc...)
1511 * 2 : header = On input, pointer to header to modify.
1512 * On output, pointer to the modified header, or NULL
1513 * to remove the header. This function frees the
1514 * original string if necessary.
1516 * Returns : JB_ERR_OK on success, or
1517 * JB_ERR_MEMORY on out-of-memory error.
1519 *********************************************************************/
1520 jb_err server_last_modified(struct client_state *csp, char **header)
1523 char buf[BUFFER_SIZE];
1526 #ifdef HAVE_GMTIME_R
1529 struct tm *timeptr = NULL;
1530 time_t now, last_modified;
1532 long int days, hours, minutes, seconds;
1535 * Are we messing with the Last-Modified header?
1537 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1543 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1545 if (0 == strcmpic(newval, "block") )
1548 * Blocking Last-Modified header. Useless but why not.
1550 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1554 else if (0 == strcmpic(newval, "reset-to-request-time"))
1557 * Setting Last-Modified Header to now.
1559 get_http_time(0, buf);
1561 *header = strdup("Last-Modified: ");
1562 string_append(header, buf);
1564 if (*header == NULL)
1566 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1570 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1573 else if (0 == strcmpic(newval, "randomize"))
1575 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1577 #ifdef HAVE_GMTIME_R
1578 timeptr = gmtime_r(&now, &gmt);
1580 pthread_mutex_lock(&gmtime_mutex);
1581 timeptr = gmtime(&now);
1582 pthread_mutex_unlock(&gmtime_mutex);
1584 timeptr = gmtime(&now);
1586 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1588 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1593 rtime = difftime(now, last_modified);
1596 rtime = pick_from_range(rtime);
1597 last_modified += rtime;
1598 #ifdef HAVE_GMTIME_R
1599 timeptr = gmtime_r(&last_modified, &gmt);
1601 pthread_mutex_lock(&gmtime_mutex);
1602 timeptr = gmtime(&last_modified);
1603 pthread_mutex_unlock(&gmtime_mutex);
1605 timeptr = gmtime(&last_modified);
1607 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1609 *header = strdup("Last-Modified: ");
1610 string_append(header, newheader);
1612 if (*header == NULL)
1614 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1615 return JB_ERR_MEMORY;
1618 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1620 days = rtime / (3600 * 24);
1621 hours = rtime / 3600 % 24;
1622 minutes = rtime / 60 % 60;
1623 seconds = rtime % 60;
1625 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1626 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1627 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1632 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1640 /*********************************************************************
1642 * Function : client_accept_encoding
1644 * Description : Rewrite the client's Accept-Encoding header so that
1645 * if doesn't allow compression, if the action applies.
1646 * Note: For HTTP/1.0 the absence of the header is enough.
1649 * 1 : csp = Current client state (buffers, headers, etc...)
1650 * 2 : header = On input, pointer to header to modify.
1651 * On output, pointer to the modified header, or NULL
1652 * to remove the header. This function frees the
1653 * original string if necessary.
1655 * Returns : JB_ERR_OK on success, or
1656 * JB_ERR_MEMORY on out-of-memory error.
1658 *********************************************************************/
1659 jb_err client_accept_encoding(struct client_state *csp, char **header)
1661 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1663 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1667 /* Temporarily disable the correct behaviour to
1668 * work around a PHP bug.
1670 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1672 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1673 * if (*header == NULL)
1675 * return JB_ERR_MEMORY;
1686 /*********************************************************************
1688 * Function : client_te
1690 * Description : Rewrite the client's TE header so that
1691 * if doesn't allow compression, if the action applies.
1694 * 1 : csp = Current client state (buffers, headers, etc...)
1695 * 2 : header = On input, pointer to header to modify.
1696 * On output, pointer to the modified header, or NULL
1697 * to remove the header. This function frees the
1698 * original string if necessary.
1700 * Returns : JB_ERR_OK on success, or
1701 * JB_ERR_MEMORY on out-of-memory error.
1703 *********************************************************************/
1704 jb_err client_te(struct client_state *csp, char **header)
1706 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1709 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1715 /*********************************************************************
1717 * Function : client_referrer
1719 * Description : Handle the "referer" config setting properly.
1720 * Called from `sed'.
1723 * 1 : csp = Current client state (buffers, headers, etc...)
1724 * 2 : header = On input, pointer to header to modify.
1725 * On output, pointer to the modified header, or NULL
1726 * to remove the header. This function frees the
1727 * original string if necessary.
1729 * Returns : JB_ERR_OK on success, or
1730 * JB_ERR_MEMORY on out-of-memory error.
1732 *********************************************************************/
1733 jb_err client_referrer(struct client_state *csp, char **header)
1740 #ifdef FEATURE_FORCE_LOAD
1741 /* Since the referrer can include the prefix even
1742 * if the request itself is non-forced, we must
1743 * clean it unconditionally
1745 strclean(*header, FORCE_PREFIX);
1746 #endif /* def FEATURE_FORCE_LOAD */
1749 * Are we sending referer?
1751 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1756 newval = csp->action->string[ACTION_STRING_REFERER];
1758 if ((0 != strcmpic(newval, "conditional-block")))
1762 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1767 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1770 else if (0 == strcmpic(newval, "conditional-block"))
1773 * Block referer if host has changed.
1776 if (NULL == (host = strdup(csp->http->hostport)))
1779 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1780 return JB_ERR_MEMORY;
1782 if (NULL == (referer = strdup(*header)))
1786 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1787 return JB_ERR_MEMORY;
1789 hostlenght = strlen(host);
1790 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1792 /*Shorten referer to make sure the referer is blocked
1793 *if www.example.org/www.example.com-shall-see-the-referer/
1794 *links to www.example.com/
1796 referer[hostlenght+17] = '\0';
1798 if ( 0 == strstr(referer, host)) /*Host has changed*/
1800 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1805 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1811 else if (0 != strcmpic(newval, "forge"))
1814 * We have a specific (fixed) referer we want to send.
1816 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1818 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1820 *header = strdup("Referer: ");
1821 string_append(header, newval);
1822 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1824 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1829 * Forge a referer as http://[hostname:port of REQUEST]/
1830 * to fool stupid checks for in-site links
1833 *header = strdup("Referer: http://");
1834 string_append(header, csp->http->hostport);
1835 string_append(header, "/");
1836 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1838 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1842 /*********************************************************************
1844 * Function : client_accept_language
1846 * Description : Handle the "Accept-Language" config setting properly.
1847 * Called from `sed'.
1850 * 1 : csp = Current client state (buffers, headers, etc...)
1851 * 2 : header = On input, pointer to header to modify.
1852 * On output, pointer to the modified header, or NULL
1853 * to remove the header. This function frees the
1854 * original string if necessary.
1856 * Returns : JB_ERR_OK on success, or
1857 * JB_ERR_MEMORY on out-of-memory error.
1859 *********************************************************************/
1860 jb_err client_accept_language(struct client_state *csp, char **header)
1865 * Are we messing with the Accept-Language?
1867 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1869 /*I don't think so*/
1873 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1875 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1878 * Blocking Accept-Language header
1880 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1887 * Replacing Accept-Language header
1890 *header = strdup("Accept-Language: ");
1891 string_append(header, newval);
1893 if (*header == NULL)
1895 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1899 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1902 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1905 /*********************************************************************
1907 * Function : crunch_client_header
1909 * Description : Crunch client header if it matches a string supplied by the
1910 * user. Called from `sed'.
1913 * 1 : csp = Current client state (buffers, headers, etc...)
1914 * 2 : header = On input, pointer to header to modify.
1915 * On output, pointer to the modified header, or NULL
1916 * to remove the header. This function frees the
1917 * original string if necessary.
1919 * Returns : JB_ERR_OK on success and always succeeds
1921 *********************************************************************/
1922 jb_err crunch_client_header(struct client_state *csp, char **header)
1924 const char *crunch_pattern;
1925 /*Is there a header to crunch*/
1927 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1929 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1931 /*Is the current header the lucky one?*/
1932 if (strstr(*header, crunch_pattern))
1934 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1942 /*********************************************************************
1944 * Function : client_uagent
1946 * Description : Handle the "user-agent" config setting properly
1947 * and remember its original value to enable browser
1948 * bug workarounds. Called from `sed'.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 jb_err client_uagent(struct client_state *csp, char **header)
1965 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1970 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1977 *header = strdup("User-Agent: ");
1978 string_append(header, newval);
1980 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1982 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1985 /*********************************************************************
1987 * Function : client_ua
1989 * Description : Handle "ua-" headers properly. Called from `sed'.
1992 * 1 : csp = Current client state (buffers, headers, etc...)
1993 * 2 : header = On input, pointer to header to modify.
1994 * On output, pointer to the modified header, or NULL
1995 * to remove the header. This function frees the
1996 * original string if necessary.
1998 * Returns : JB_ERR_OK on success, or
1999 * JB_ERR_MEMORY on out-of-memory error.
2001 *********************************************************************/
2002 jb_err client_ua(struct client_state *csp, char **header)
2004 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2006 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2014 /*********************************************************************
2016 * Function : client_from
2018 * Description : Handle the "from" config setting properly.
2019 * Called from `sed'.
2022 * 1 : csp = Current client state (buffers, headers, etc...)
2023 * 2 : header = On input, pointer to header to modify.
2024 * On output, pointer to the modified header, or NULL
2025 * to remove the header. This function frees the
2026 * original string if necessary.
2028 * Returns : JB_ERR_OK on success, or
2029 * JB_ERR_MEMORY on out-of-memory error.
2031 *********************************************************************/
2032 jb_err client_from(struct client_state *csp, char **header)
2036 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2043 newval = csp->action->string[ACTION_STRING_FROM];
2046 * Are we blocking the e-mail address?
2048 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2050 log_error(LOG_LEVEL_HEADER, "crunched From!");
2054 log_error(LOG_LEVEL_HEADER, " modified");
2056 *header = strdup("From: ");
2057 string_append(header, newval);
2059 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2063 /*********************************************************************
2065 * Function : client_send_cookie
2067 * Description : Handle the "cookie" header properly. Called from `sed'.
2068 * If cookie is accepted, add it to the cookie_list,
2069 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2072 * 1 : csp = Current client state (buffers, headers, etc...)
2073 * 2 : header = On input, pointer to header to modify.
2074 * On output, pointer to the modified header, or NULL
2075 * to remove the header. This function frees the
2076 * original string if necessary.
2078 * Returns : JB_ERR_OK on success, or
2079 * JB_ERR_MEMORY on out-of-memory error.
2081 *********************************************************************/
2082 jb_err client_send_cookie(struct client_state *csp, char **header)
2084 jb_err result = JB_ERR_OK;
2086 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2088 /* strlen("cookie: ") == 8 */
2089 result = enlist(csp->cookie_list, *header + 8);
2093 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2097 * Always remove the cookie here. The cookie header
2098 * will be sent at the end of the header.
2106 /*********************************************************************
2108 * Function : client_x_forwarded
2110 * Description : Handle the "x-forwarded-for" config setting properly,
2111 * also used in the add_client_headers list. Called from `sed'.
2114 * 1 : csp = Current client state (buffers, headers, etc...)
2115 * 2 : header = On input, pointer to header to modify.
2116 * On output, pointer to the modified header, or NULL
2117 * to remove the header. This function frees the
2118 * original string if necessary.
2120 * Returns : JB_ERR_OK on success, or
2121 * JB_ERR_MEMORY on out-of-memory error.
2123 *********************************************************************/
2124 jb_err client_x_forwarded(struct client_state *csp, char **header)
2126 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2128 /* Save it so we can re-add it later */
2129 freez(csp->x_forwarded);
2130 csp->x_forwarded = *header;
2133 * Always set *header = NULL, since this information
2134 * will be sent at the end of the header.
2141 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2148 /*********************************************************************
2150 * Function : client_max_forwards
2152 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2153 * from the value of the Max-Forwards header field.
2156 * 1 : csp = Current client state (buffers, headers, etc...)
2157 * 2 : header = On input, pointer to header to modify.
2158 * On output, pointer to the modified header, or NULL
2159 * to remove the header. This function frees the
2160 * original string if necessary.
2162 * Returns : JB_ERR_OK on success, or
2163 * JB_ERR_MEMORY on out-of-memory error.
2165 *********************************************************************/
2166 jb_err client_max_forwards(struct client_state *csp, char **header)
2168 unsigned int max_forwards;
2170 if ((0 == strcmpic(csp->http->gpc, "trace"))
2171 || (0 == strcmpic(csp->http->gpc, "options")))
2173 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2175 if (max_forwards-- >= 1)
2177 sprintf(*header, "Max-Forwards: %u", max_forwards);
2178 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2182 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2191 /*********************************************************************
2193 * Function : client_host
2195 * Description : If the request URI did not contain host and
2196 * port information, parse and evaluate the Host
2199 * Also, kill ill-formed HOST: headers as sent by
2200 * Apple's iTunes software when used with a proxy.
2203 * 1 : csp = Current client state (buffers, headers, etc...)
2204 * 2 : header = On input, pointer to header to modify.
2205 * On output, pointer to the modified header, or NULL
2206 * to remove the header. This function frees the
2207 * original string if necessary.
2209 * Returns : JB_ERR_OK on success, or
2210 * JB_ERR_MEMORY on out-of-memory error.
2212 *********************************************************************/
2213 jb_err client_host(struct client_state *csp, char **header)
2218 * If the header field name is all upper-case, chances are that it's
2219 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2220 * not a problem -- they are regenerated later.
2222 if ((*header)[1] == 'O')
2224 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2229 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2230 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2233 if (NULL == (p = strdup((*header)+6)))
2235 return JB_ERR_MEMORY;
2238 if (NULL == (q = strdup(p)))
2241 return JB_ERR_MEMORY;
2244 freez(csp->http->hostport);
2245 csp->http->hostport = p;
2246 freez(csp->http->host);
2247 csp->http->host = q;
2248 q = strchr(csp->http->host, ':');
2251 /* Terminate hostname and evaluate port string */
2253 csp->http->port = atoi(q);
2257 csp->http->port = csp->http->ssl ? 443 : 80;
2260 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2261 csp->http->hostport, csp->http->host, csp->http->port);
2267 /*********************************************************************
2269 * Function : client_if_modified_since
2271 * Description : Remove or modify the If-Modified-Since header.
2274 * 1 : csp = Current client state (buffers, headers, etc...)
2275 * 2 : header = On input, pointer to header to modify.
2276 * On output, pointer to the modified header, or NULL
2277 * to remove the header. This function frees the
2278 * original string if necessary.
2280 * Returns : JB_ERR_OK on success, or
2281 * JB_ERR_MEMORY on out-of-memory error.
2283 *********************************************************************/
2284 jb_err client_if_modified_since(struct client_state *csp, char **header)
2287 #ifdef HAVE_GMTIME_R
2290 struct tm *timeptr = NULL;
2294 long int hours, minutes, seconds;
2298 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2301 * The client got an error message because of a temporary problem,
2302 * the problem is gone and the client now tries to revalidate our
2303 * error message on the real server. The revalidation would always
2304 * end with the transmission of the whole document and there is
2305 * no need to expose the bogus If-Modified-Since header.
2307 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2310 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2312 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2314 if ((0 == strcmpic(newval, "block")))
2316 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2319 else /* add random value */
2321 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2323 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2328 rtime = strtol(newval, &endptr, 0);
2331 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2332 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2339 rtime = pick_from_range(rtime);
2343 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2346 tm += rtime * (negative ? -1 : 1);
2347 #ifdef HAVE_GMTIME_R
2348 timeptr = gmtime_r(&tm, &gmt);
2350 pthread_mutex_lock(&gmtime_mutex);
2351 timeptr = gmtime(&tm);
2352 pthread_mutex_unlock(&gmtime_mutex);
2354 timeptr = gmtime(&tm);
2356 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2359 *header = strdup("If-Modified-Since: ");
2360 string_append(header, newheader);
2362 if (*header == NULL)
2364 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2365 return JB_ERR_MEMORY;
2368 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2370 hours = rtime / 3600;
2371 minutes = rtime / 60 % 60;
2372 seconds = rtime % 60;
2374 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2375 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2376 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2385 /*********************************************************************
2387 * Function : client_if_none_match
2389 * Description : Remove the If-None-Match header.
2392 * 1 : csp = Current client state (buffers, headers, etc...)
2393 * 2 : header = On input, pointer to header to modify.
2394 * On output, pointer to the modified header, or NULL
2395 * to remove the header. This function frees the
2396 * original string if necessary.
2398 * Returns : JB_ERR_OK on success, or
2399 * JB_ERR_MEMORY on out-of-memory error.
2401 *********************************************************************/
2402 jb_err client_if_none_match(struct client_state *csp, char **header)
2404 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2406 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2413 /*********************************************************************
2415 * Function : client_x_filter
2417 * Description : Disables filtering if the client set "X-Filter: No".
2418 * Called from `sed'.
2421 * 1 : csp = Current client state (buffers, headers, etc...)
2422 * 2 : header = On input, pointer to header to modify.
2423 * On output, pointer to the modified header, or NULL
2424 * to remove the header. This function frees the
2425 * original string if necessary.
2427 * Returns : JB_ERR_OK on success
2429 *********************************************************************/
2430 jb_err client_x_filter(struct client_state *csp, char **header)
2432 if ( 0 == strcmpic(*header, "X-Filter: No"))
2434 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2436 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2440 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2442 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2446 csp->content_type = CT_TABOO;
2447 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2448 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2449 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2451 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2458 /* the following functions add headers directly to the header list */
2460 /*********************************************************************
2462 * Function : client_host_adder
2464 * Description : Adds the Host: header field if it is missing.
2465 * Called from `sed'.
2468 * 1 : csp = Current client state (buffers, headers, etc...)
2470 * Returns : JB_ERR_OK on success, or
2471 * JB_ERR_MEMORY on out-of-memory error.
2473 *********************************************************************/
2474 jb_err client_host_adder(struct client_state *csp)
2479 if ( !csp->http->hostport || !*(csp->http->hostport))
2485 * remove 'user:pass@' from 'proto://user:pass@host'
2487 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2493 p = csp->http->hostport;
2496 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2497 err = enlist_unique_header(csp->headers, "Host", p);
2503 /*********************************************************************
2505 * Function : client_cookie_adder
2507 * Description : Used in the add_client_headers list. Called from `sed'.
2510 * 1 : csp = Current client state (buffers, headers, etc...)
2512 * Returns : JB_ERR_OK on success, or
2513 * JB_ERR_MEMORY on out-of-memory error.
2515 *********************************************************************/
2516 jb_err client_cookie_adder(struct client_state *csp)
2518 struct list_entry *lst;
2520 struct list_entry *list1 = csp->cookie_list->first;
2521 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2522 int first_cookie = 1;
2525 if ((list1 == NULL) && (list2 == NULL))
2531 tmp = strdup("Cookie: ");
2533 for (lst = list1; lst ; lst = lst->next)
2541 string_append(&tmp, "; ");
2543 string_append(&tmp, lst->str);
2546 for (lst = list2; lst ; lst = lst->next)
2554 string_append(&tmp, "; ");
2556 string_join(&tmp, cookie_encode(lst->str));
2561 return JB_ERR_MEMORY;
2564 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2565 err = enlist(csp->headers, tmp);
2571 /*********************************************************************
2573 * Function : client_accept_encoding_adder
2575 * Description : Add an Accept-Encoding header to the client's request
2576 * that disables compression if the action applies, and
2577 * the header is not already there. Called from `sed'.
2578 * Note: For HTTP/1.0, the absence of the header is enough.
2581 * 1 : csp = Current client state (buffers, headers, etc...)
2583 * Returns : JB_ERR_OK on success, or
2584 * JB_ERR_MEMORY on out-of-memory error.
2586 *********************************************************************/
2587 jb_err client_accept_encoding_adder(struct client_state *csp)
2589 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2590 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2592 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2599 /*********************************************************************
2601 * Function : client_xtra_adder
2603 * Description : Used in the add_client_headers list. Called from `sed'.
2606 * 1 : csp = Current client state (buffers, headers, etc...)
2608 * Returns : JB_ERR_OK on success, or
2609 * JB_ERR_MEMORY on out-of-memory error.
2611 *********************************************************************/
2612 jb_err client_xtra_adder(struct client_state *csp)
2614 struct list_entry *lst;
2617 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2618 lst ; lst = lst->next)
2620 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2621 err = enlist(csp->headers, lst->str);
2633 /*********************************************************************
2635 * Function : client_x_forwarded_adder
2637 * Description : Used in the add_client_headers list. Called from `sed'.
2640 * 1 : csp = Current client state (buffers, headers, etc...)
2642 * Returns : JB_ERR_OK on success, or
2643 * JB_ERR_MEMORY on out-of-memory error.
2645 *********************************************************************/
2646 jb_err client_x_forwarded_adder(struct client_state *csp)
2651 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2656 if (csp->x_forwarded)
2658 p = strdup(csp->x_forwarded);
2659 string_append(&p, ", ");
2663 p = strdup("X-Forwarded-For: ");
2665 string_append(&p, csp->ip_addr_str);
2669 return JB_ERR_MEMORY;
2672 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2673 err = enlist(csp->headers, p);
2680 /*********************************************************************
2682 * Function : connection_close_adder
2684 * Description : Adds a "Connection: close" header to csp->headers
2685 * as a temporary fix for the needed but missing HTTP/1.1
2686 * support. Called from `sed'.
2687 * FIXME: This whole function shouldn't be neccessary!
2690 * 1 : csp = Current client state (buffers, headers, etc...)
2692 * Returns : JB_ERR_OK on success, or
2693 * JB_ERR_MEMORY on out-of-memory error.
2695 *********************************************************************/
2696 jb_err connection_close_adder(struct client_state *csp)
2698 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2699 return enlist(csp->headers, "Connection: close");
2703 /*********************************************************************
2705 * Function : server_http
2707 * Description : - Save the HTTP Status into csp->http->status
2708 * - Set CT_TABOO to prevent filtering if the answer
2709 * is a partial range (HTTP status 206)
2710 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2714 * 1 : csp = Current client state (buffers, headers, etc...)
2715 * 2 : header = On input, pointer to header to modify.
2716 * On output, pointer to the modified header, or NULL
2717 * to remove the header. This function frees the
2718 * original string if necessary.
2720 * Returns : JB_ERR_OK on success, or
2721 * JB_ERR_MEMORY on out-of-memory error.
2723 *********************************************************************/
2724 jb_err server_http(struct client_state *csp, char **header)
2726 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2727 if (csp->http->status == 206)
2729 csp->content_type = CT_TABOO;
2732 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2735 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2742 /*********************************************************************
2744 * Function : server_set_cookie
2746 * Description : Handle the server "cookie" header properly.
2747 * Log cookie to the jar file. Then "crunch" it,
2748 * or accept it. Called from `sed'.
2751 * 1 : csp = Current client state (buffers, headers, etc...)
2752 * 2 : header = On input, pointer to header to modify.
2753 * On output, pointer to the modified header, or NULL
2754 * to remove the header. This function frees the
2755 * original string if necessary.
2757 * Returns : JB_ERR_OK on success, or
2758 * JB_ERR_MEMORY on out-of-memory error.
2760 *********************************************************************/
2761 jb_err server_set_cookie(struct client_state *csp, char **header)
2763 #ifdef FEATURE_COOKIE_JAR
2764 if (csp->config->jar)
2767 * Write timestamp into outbuf.
2769 * Complex because not all OSs have tm_gmtoff or
2770 * the %z field in strftime()
2772 char tempbuf[ BUFFER_SIZE ];
2776 #ifdef HAVE_LOCALTIME_R
2777 tm_now = *localtime_r(&now, &tm_now);
2779 pthread_mutex_lock(&localtime_mutex);
2780 tm_now = *localtime (&now);
2781 pthread_mutex_unlock(&localtime_mutex);
2783 tm_now = *localtime (&now);
2785 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2787 /* strlen("set-cookie: ") = 12 */
2788 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2790 #endif /* def FEATURE_COOKIE_JAR */
2792 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2794 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2795 return crumble(csp, header);
2797 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2799 /* Flag whether or not to log a message */
2802 /* A variable to store the tag we're working on */
2805 /* Skip "Set-Cookie:" (11 characters) in header */
2806 cur_tag = *header + 11;
2808 /* skip whitespace between "Set-Cookie:" and value */
2809 while (*cur_tag && ijb_isspace(*cur_tag))
2814 /* Loop through each tag in the cookie */
2818 char *next_tag = strchr(cur_tag, ';');
2819 if (next_tag != NULL)
2821 /* Skip the ';' character itself */
2824 /* skip whitespace ";" and start of tag */
2825 while (*next_tag && ijb_isspace(*next_tag))
2832 /* "Next tag" is the end of the string */
2833 next_tag = cur_tag + strlen(cur_tag);
2836 /* Is this the "Expires" tag? */
2837 if (strncmpic(cur_tag, "expires=", 8) == 0)
2839 /* Delete the tag by copying the rest of the string over it.
2840 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2841 * since the behaviour of strcpy is undefined for overlapping
2844 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2846 /* That changed the header, need to issue a log message */
2849 /* Note that the next tag has now been moved to *cur_tag,
2850 * so we do not need to update the cur_tag pointer.
2855 /* Move on to next cookie tag */
2862 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2870 #ifdef FEATURE_FORCE_LOAD
2871 /*********************************************************************
2873 * Function : strclean
2875 * Description : In-Situ-Eliminate all occurances of substring in
2879 * 1 : string = string to clean
2880 * 2 : substring = substring to eliminate
2882 * Returns : Number of eliminations
2884 *********************************************************************/
2885 int strclean(const char *string, const char *substring)
2887 int hits = 0, len = strlen(substring);
2890 while((pos = strstr(string, substring)) != NULL)
2897 while (*p++ != '\0');
2904 #endif /* def FEATURE_FORCE_LOAD */
2906 /*********************************************************************
2908 * Function : parse_header_time
2910 * Description : Transforms time inside a HTTP header into
2911 * the usual time format.
2914 * 1 : header = header to parse
2915 * 2 : tm = storage for the resulting time in seconds
2917 * Returns : Time struct containing the header time, or
2918 * NULL in case of a parsing problem.
2920 *********************************************************************/
2921 struct tm *parse_header_time(char *header, time_t *tm) {
2925 struct tm * timeptr;
2927 /* Skipping header name */
2928 timestring = strstr(header, ": ");
2929 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)