1 const char parsers_rcs[] = "$Id: parsers.c,v 1.74 2006/10/02 16:59:12 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.74 2006/10/02 16:59:12 fabiankeil
44 * The special header "X-Filter: No" now disables
45 * header filtering as well.
47 * Revision 1.73 2006/09/23 13:26:38 roro
48 * Replace TABs by spaces in source code.
50 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
51 * Don't print a log message every time filter_headers is
52 * entered or left. It only creates noise without any real
55 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
56 * Fix +hide-if-modified-since{-n}.
58 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
59 * Have hide-if-modified-since interpret the random
60 * range value as minutes instead of hours. Allows
61 * more fine-grained configuration.
63 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
64 * Always have parse_header_time return a pointer
65 * that actual makes sense, even though we currently
66 * only need it to detect problems.
68 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
69 * Added config option enable-remote-http-toggle
70 * to specify if Privoxy should recognize special
71 * headers (currently only X-Filter) to change its
72 * behaviour. Disabled by default.
74 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
75 * After filtering de-chunked instances, remove
76 * "Transfer-Encoding" header entirely instead of changing
77 * it to "Transfer-Encoding: identity", which is invalid.
78 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
80 * Don't use localtime in parse_header_time. An empty time struct
81 * is good enough, it gets overwritten by strptime anyway.
83 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
84 * Use gmtime_r if available, fallback to gmtime with mutex
85 * protection for MacOSX and use vanilla gmtime for the rest.
87 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
88 * Changed client_referrer to use the right type (size_t) for
89 * hostlenght and to shorten the temporary referrer string with
90 * '\0' instead of adding a useless line break.
92 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
93 * - Back to timegm() using GnuPG's replacement if necessary.
94 * Using mktime() and localtime() could add a on hour offset if
95 * the randomize factor was big enough to lead to a summer/wintertime
98 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
100 * - Moved randomization code into pick_from_range().
102 * - Changed parse_header_time definition.
103 * time_t isn't guaranteed to be signed and
104 * if it isn't, -1 isn't available as error code.
105 * Changed some variable types in client_if_modified_since()
106 * because of the same reason.
108 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
109 * OS/2 compilation compatibility fixups
111 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
112 * Changed include from strptime.c to strptime.h
114 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
115 * Split filter-headers{} into filter-client-headers{}
116 * and filter-server-headers{}.
117 * Added parse_header_time() to share some code.
118 * Replaced timegm() with mktime().
120 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
121 * Windows service integration
123 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
124 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
126 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
127 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
128 * with what was really the latest development (the v_3_0_branch branch)
130 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
131 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
133 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
134 * Add the ability to check jpeg images for invalid
135 * lengths of comment blocks. Defensive strategy
136 * against the exploit:
137 * Microsoft Security Bulletin MS04-028
138 * Buffer Overrun in JPEG Processing (GDI+) Could
139 * Allow Code Execution (833987)
140 * Enabled with +inspect-jpegs in actions files.
142 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
143 * Excluded text/plain objects from filtering. This fixes a
144 * couple of client-crashing, download corruption and
145 * Privoxy performance issues, whose root cause lies in
146 * web servers labelling content of unknown type as text/plain.
148 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
149 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
151 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
152 * Completing the previous change
154 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
155 * Added temporary workaround for bug in PHP < 4.2.3
157 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
158 * 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.
160 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
161 * Fix typo: supressed -> suppressed
163 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
164 * Improved cookie logging
166 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
167 * Added basic support for OPTIONS and TRACE HTTP methods:
168 * - New parser function client_max_forwards which decrements
169 * the Max-Forwards HTTP header field of OPTIONS and TRACE
170 * requests by one before forwarding
171 * - New parser function client_host which extracts the host
172 * and port information from the HTTP header field if the
173 * request URI was not absolute
174 * - Don't crumble and re-add the Host: header, but only generate
175 * and append if missing
177 * Revision 1.56 2002/05/12 15:34:22 jongfoster
178 * Fixing typo in a comment
180 * Revision 1.55 2002/05/08 16:01:07 oes
181 * Optimized add_to_iob:
182 * - Use realloc instead of malloc(), memcpy(), free()
183 * - Expand to powers of two if possible, to get
184 * O(log n) reallocs instead of O(n).
185 * - Moved check for buffer limit here from chat
186 * - Report failure via returncode
188 * Revision 1.54 2002/04/02 15:03:16 oes
189 * Tiny code cosmetics
191 * Revision 1.53 2002/03/26 22:29:55 swa
192 * we have a new homepage!
194 * Revision 1.52 2002/03/24 13:25:43 swa
195 * name change related issues
197 * Revision 1.51 2002/03/13 00:27:05 jongfoster
200 * Revision 1.50 2002/03/12 01:45:35 oes
201 * More verbose logging
203 * Revision 1.49 2002/03/09 20:03:52 jongfoster
204 * - Making various functions return int rather than size_t.
205 * (Undoing a recent change). Since size_t is unsigned on
206 * Windows, functions like read_socket that return -1 on
207 * error cannot return a size_t.
209 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
210 * crashes, and also frequently caused JB to jump to 100%
211 * CPU and stay there. (Because it thought it had just
212 * read ((unsigned)-1) == 4Gb of data...)
214 * - The signature of write_socket has changed, it now simply
215 * returns success=0/failure=nonzero.
217 * - Trying to get rid of a few warnings --with-debug on
218 * Windows, I've introduced a new type "jb_socket". This is
219 * used for the socket file descriptors. On Windows, this
220 * is SOCKET (a typedef for unsigned). Everywhere else, it's
221 * an int. The error value can't be -1 any more, so it's
222 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
223 * Windows it maps to the #define INVALID_SOCKET.)
225 * - The signature of bind_port has changed.
227 * Revision 1.48 2002/03/07 03:46:53 oes
228 * Fixed compiler warnings etc
230 * Revision 1.47 2002/02/20 23:15:13 jongfoster
231 * Parsing functions now handle out-of-memory gracefully by returning
234 * Revision 1.46 2002/01/17 21:03:47 jongfoster
235 * Moving all our URL and URL pattern parsing code to urlmatch.c.
237 * Revision 1.45 2002/01/09 14:33:03 oes
238 * Added support for localtime_r.
240 * Revision 1.44 2001/12/14 01:22:54 steudten
241 * Remove 'user:pass@' from 'proto://user:pass@host' for the
242 * new added header 'Host: ..'. (See Req ID 491818)
244 * Revision 1.43 2001/11/23 00:26:38 jongfoster
245 * Fixing two really stupid errors in my previous commit
247 * Revision 1.42 2001/11/22 21:59:30 jongfoster
248 * Adding code to handle +no-cookies-keep
250 * Revision 1.41 2001/11/05 23:43:05 steudten
251 * Add time+date to log files.
253 * Revision 1.40 2001/10/26 20:13:09 jongfoster
254 * ctype.h is needed in Windows, too.
256 * Revision 1.39 2001/10/26 17:40:04 oes
257 * Introduced get_header_value()
258 * Removed http->user_agent, csp->referrer and csp->accept_types
259 * Removed client_accept()
261 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
262 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
263 * threads to call select() simultaneously. So, it's time to do a real, live,
264 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
265 * (native). Both versions will work, but using __OS2__ offers multi-threading.
267 * Revision 1.37 2001/10/23 21:36:02 jongfoster
268 * Documenting sed()'s error behaviou (doc change only)
270 * Revision 1.36 2001/10/13 12:51:51 joergs
271 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
272 * force-load), instead crumble Host: and add it (again) in client_host_adder
273 * (in case we get a HTTP/1.0 request without Host: header and forward it to
274 * a HTTP/1.1 server/proxy).
276 * Revision 1.35 2001/10/09 22:39:21 jongfoster
277 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
280 * Revision 1.34 2001/10/07 18:50:55 oes
281 * Added server_content_encoding, renamed server_transfer_encoding
283 * Revision 1.33 2001/10/07 18:04:49 oes
284 * Changed server_http11 to server_http and its pattern to "HTTP".
285 * Additional functionality: it now saves the HTTP status into
286 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
288 * Revision 1.32 2001/10/07 15:43:28 oes
289 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
290 * client_te and client_accept_encoding_adder, triggered by the new
291 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
292 * changed to allow only identity and chunked, and the TE header is
293 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
295 * parse_http_request no longer does anything than parsing. The rewriting
296 * of http->cmd and version mangling are gone. It now also recognizes
297 * the put and delete methods and saves the url in http->url. Removed
300 * renamed content_type and content_length to have the server_ prefix
302 * server_content_type now only works if csp->content_type != CT_TABOO
304 * added server_transfer_encoding, which
305 * - Sets CT_TABOO to prohibit filtering if encoding compresses
306 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
307 * - Change from "chunked" to "identity" if body was chunked
308 * but has been de-chunked for filtering.
310 * added server_content_md5 which crunches any Content-MD5 headers
311 * if the body was modified.
313 * made server_http11 conditional on +downgrade action
315 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
317 * Revision 1.31 2001/10/05 14:25:02 oes
318 * Crumble Keep-Alive from Server
320 * Revision 1.30 2001/09/29 12:56:03 joergs
321 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
323 * Revision 1.29 2001/09/24 21:09:24 jongfoster
324 * Fixing 2 memory leaks that Guy spotted, where the paramater to
325 * enlist() was not being free()d.
327 * Revision 1.28 2001/09/22 16:32:28 jongfoster
328 * Removing unused #includes.
330 * Revision 1.27 2001/09/20 15:45:25 steudten
332 * add casting from size_t to int for printf()
333 * remove local variable shadow s2
335 * Revision 1.26 2001/09/16 17:05:14 jongfoster
336 * Removing unused #include showarg.h
338 * Revision 1.25 2001/09/16 13:21:27 jongfoster
339 * Changes to use new list functions.
341 * Revision 1.24 2001/09/13 23:05:50 jongfoster
342 * Changing the string paramater to the header parsers a "const".
344 * Revision 1.23 2001/09/12 18:08:19 steudten
346 * In parse_http_request() header rewriting miss the host value, so
347 * from http://www.mydomain.com the result was just " / " not
348 * http://www.mydomain.com/ in case we forward.
350 * Revision 1.22 2001/09/10 10:58:53 oes
351 * Silenced compiler warnings
353 * Revision 1.21 2001/07/31 14:46:00 oes
354 * - Persistant connections now suppressed
355 * - sed() no longer appends empty header to csp->headers
357 * Revision 1.20 2001/07/30 22:08:36 jongfoster
358 * Tidying up #defines:
359 * - All feature #defines are now of the form FEATURE_xxx
360 * - Permanently turned off WIN_GUI_EDIT
361 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
363 * Revision 1.19 2001/07/25 17:21:54 oes
364 * client_uagent now saves copy of User-Agent: header value
366 * Revision 1.18 2001/07/13 14:02:46 oes
367 * - Included fix to repair broken HTTP requests that
368 * don't contain a path, not even '/'.
369 * - Removed all #ifdef PCRS
370 * - content_type now always inspected and classified as
371 * text, gif or other.
372 * - formatting / comments
374 * Revision 1.17 2001/06/29 21:45:41 oes
375 * Indentation, CRLF->LF, Tab-> Space
377 * Revision 1.16 2001/06/29 13:32:42 oes
379 * - Adapted free_http_request
380 * - Removed logentry from cancelled commit
382 * Revision 1.15 2001/06/03 19:12:38 oes
383 * deleted const struct interceptors
385 * Revision 1.14 2001/06/01 18:49:17 jongfoster
386 * Replaced "list_share" with "list" - the tiny memory gain was not
387 * worth the extra complexity.
389 * Revision 1.13 2001/05/31 21:30:33 jongfoster
390 * Removed list code - it's now in list.[ch]
391 * Renamed "permission" to "action", and changed many features
392 * to use the actions file rather than the global config.
394 * Revision 1.12 2001/05/31 17:33:13 oes
398 * Revision 1.11 2001/05/29 20:11:19 joergs
399 * '/ * inside comment' warning removed.
401 * Revision 1.10 2001/05/29 09:50:24 jongfoster
402 * Unified blocklist/imagelist/permissionslist.
403 * File format is still under discussion, but the internal changes
406 * Also modified interceptor behaviour:
407 * - We now intercept all URLs beginning with one of the following
408 * prefixes (and *only* these prefixes):
410 * * http://ijbswa.sf.net/config/
411 * * http://ijbswa.sourceforge.net/config/
412 * - New interceptors "home page" - go to http://i.j.b/ to see it.
413 * - Internal changes so that intercepted and fast redirect pages
414 * are not replaced with an image.
415 * - Interceptors now have the option to send a binary page direct
416 * to the client. (i.e. ijb-send-banner uses this)
417 * - Implemented show-url-info interceptor. (Which is why I needed
418 * the above interceptors changes - a typical URL is
419 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
420 * The previous mechanism would not have intercepted that, and
421 * if it had been intercepted then it then it would have replaced
424 * Revision 1.9 2001/05/28 17:26:33 jongfoster
425 * Fixing segfault if last header was crunched.
426 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
427 * can use the cross-platform sprintf() instead.)
429 * Revision 1.8 2001/05/27 22:17:04 oes
431 * - re_process_buffer no longer writes the modified buffer
432 * to the client, which was very ugly. It now returns the
433 * buffer, which it is then written by chat.
435 * - content_length now adjusts the Content-Length: header
436 * for modified documents rather than crunch()ing it.
437 * (Length info in csp->content_length, which is 0 for
438 * unmodified documents)
440 * - For this to work, sed() is called twice when filtering.
442 * Revision 1.7 2001/05/27 13:19:06 oes
443 * Patched Joergs solution for the content-length in.
445 * Revision 1.6 2001/05/26 13:39:32 jongfoster
446 * Only crunches Content-Length header if applying RE filtering.
447 * Without this fix, Microsoft Windows Update wouldn't work.
449 * Revision 1.5 2001/05/26 00:28:36 jongfoster
450 * Automatic reloading of config file.
451 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
452 * Most of the global variables have been moved to a new
453 * struct configuration_spec, accessed through csp->config->globalname
454 * Most of the globals remaining are used by the Win32 GUI.
456 * Revision 1.4 2001/05/22 18:46:04 oes
458 * - Enabled filtering banners by size rather than URL
459 * by adding patterns that replace all standard banner
460 * sizes with the "Junkbuster" gif to the re_filterfile
462 * - Enabled filtering WebBugs by providing a pattern
463 * which kills all 1x1 images
465 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
466 * which is selected by the (nonstandard and therefore
467 * capital) letter 'U' in the option string.
468 * It causes the quantifiers to be ungreedy by default.
469 * Appending a ? turns back to greedy (!).
471 * - Added a new interceptor ijb-send-banner, which
472 * sends back the "Junkbuster" gif. Without imagelist or
473 * MSIE detection support, or if tinygif = 1, or the
474 * URL isn't recognized as an imageurl, a lame HTML
475 * explanation is sent instead.
477 * - Added new feature, which permits blocking remote
478 * script redirects and firing back a local redirect
480 * The feature is conditionally compiled, i.e. it
481 * can be disabled with --disable-fast-redirects,
482 * plus it must be activated by a "fast-redirects"
483 * line in the config file, has its own log level
484 * and of course wants to be displayed by show-proxy-args
485 * Note: Boy, all the #ifdefs in 1001 locations and
486 * all the fumbling with configure.in and acconfig.h
487 * were *way* more work than the feature itself :-(
489 * - Because a generic redirect template was needed for
490 * this, tinygif = 3 now uses the same.
492 * - Moved GIFs, and other static HTTP response templates
497 * - Removed some >400 CRs again (Jon, you really worked
500 * Revision 1.3 2001/05/20 01:21:20 jongfoster
501 * Version 2.9.4 checkin.
502 * - Merged popupfile and cookiefile, and added control over PCRS
503 * filtering, in new "permissionsfile".
504 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
505 * file error you now get a message box (in the Win32 GUI) rather
506 * than the program exiting with no explanation.
507 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
509 * - Removed tabs from "config"
510 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
511 * - Bumped up version number.
513 * Revision 1.2 2001/05/17 23:02:36 oes
514 * - Made referrer option accept 'L' as a substitute for '§'
516 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
517 * Initial import of version 2.9.3 source tree
520 *********************************************************************/
527 #include <sys/types.h>
536 #if !defined(_WIN32) && !defined(__OS2__)
542 #ifdef FEATURE_PTHREAD
544 /* jcc.h is for mutex semapores only */
545 #endif /* def FEATURE_PTHREAD */
551 #include "jbsockets.h"
552 #include "miscutil.h"
555 #ifndef HAVE_STRPTIME
556 #include "strptime.h"
559 const char parsers_h_rcs[] = PARSERS_H_VERSION;
561 /* Fix a problem with Solaris. There should be no effect on other
563 * Solaris's isspace() is a macro which uses it's argument directly
564 * as an array index. Therefore we need to make sure that high-bit
565 * characters generate +ve values, and ideally we also want to make
566 * the argument match the declared parameter type of "int".
568 * Why did they write a character function that can't take a simple
569 * "char" argument? Doh!
571 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
572 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
575 const struct parsers client_patterns[] = {
576 { "referer:", 8, client_referrer },
577 { "user-agent:", 11, client_uagent },
578 { "ua-", 3, client_ua },
579 { "from:", 5, client_from },
580 { "cookie:", 7, client_send_cookie },
581 { "x-forwarded-for:", 16, client_x_forwarded },
582 { "Accept-Encoding:", 16, client_accept_encoding },
583 { "TE:", 3, client_te },
584 { "Host:", 5, client_host },
585 { "if-modified-since:", 18, client_if_modified_since },
586 { "Keep-Alive:", 11, crumble },
587 { "connection:", 11, crumble },
588 { "proxy-connection:", 17, crumble },
589 { "max-forwards:", 13, client_max_forwards },
590 { "Accept-Language:", 16, client_accept_language },
591 { "if-none-match:", 14, client_if_none_match },
592 { "X-Filter:", 9, client_x_filter },
593 { "*", 0, crunch_client_header },
594 { "*", 0, filter_client_header },
598 const struct parsers server_patterns[] = {
599 { "HTTP", 4, server_http },
600 { "set-cookie:", 11, server_set_cookie },
601 { "connection:", 11, crumble },
602 { "Content-Type:", 13, server_content_type },
603 { "Content-Length:", 15, server_content_length },
604 { "Content-MD5:", 12, server_content_md5 },
605 { "Content-Encoding:", 17, server_content_encoding },
606 { "Transfer-Encoding:", 18, server_transfer_coding },
607 { "Keep-Alive:", 11, crumble },
608 { "content-disposition:", 20, server_content_disposition },
609 { "Last-Modified:", 14, server_last_modified },
610 { "*", 0, crunch_server_header },
611 { "*", 0, filter_server_header },
615 const struct parsers server_patterns_light[] = {
616 { "Content-Length:", 15, server_content_length },
617 { "Transfer-Encoding:", 18, server_transfer_coding },
621 const add_header_func_ptr add_client_headers[] = {
624 client_x_forwarded_adder,
626 /* Temporarily disabled: client_accept_encoding_adder, */
627 connection_close_adder,
632 const add_header_func_ptr add_server_headers[] = {
633 connection_close_adder,
637 /*********************************************************************
639 * Function : flush_socket
641 * Description : Write any pending "buffered" content.
644 * 1 : fd = file descriptor of the socket to read
645 * 2 : csp = Current client state (buffers, headers, etc...)
647 * Returns : On success, the number of bytes written are returned (zero
648 * indicates nothing was written). On error, -1 is returned,
649 * and errno is set appropriately. If count is zero and the
650 * file descriptor refers to a regular file, 0 will be
651 * returned without causing any other effect. For a special
652 * file, the results are not portable.
654 *********************************************************************/
655 int flush_socket(jb_socket fd, struct client_state *csp)
657 struct iob *iob = csp->iob;
658 int len = iob->eod - iob->cur;
665 if (write_socket(fd, iob->cur, (size_t)len))
669 iob->eod = iob->cur = iob->buf;
675 /*********************************************************************
677 * Function : add_to_iob
679 * Description : Add content to the buffered page, expanding the
680 * buffer if necessary.
683 * 1 : csp = Current client state (buffers, headers, etc...)
684 * 2 : buf = holds the content to be added to the page
685 * 3 : n = number of bytes to be added
687 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
688 * or buffer limit reached.
690 *********************************************************************/
691 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
693 struct iob *iob = csp->iob;
694 size_t used, offset, need, want;
697 if (n <= 0) return JB_ERR_OK;
699 used = iob->eod - iob->buf;
700 offset = iob->cur - iob->buf;
704 * If the buffer can't hold the new data, extend it first.
705 * Use the next power of two if possible, else use the actual need.
707 if (need > csp->config->buffer_limit)
709 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
710 return JB_ERR_MEMORY;
713 if (need > iob->size)
715 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
717 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
721 else if (NULL != (p = (char *)realloc(iob->buf, need)))
727 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
728 return JB_ERR_MEMORY;
731 /* Update the iob pointers */
732 iob->cur = p + offset;
737 /* copy the new data into the iob buffer */
738 memcpy(iob->eod, buf, (size_t)n);
740 /* point to the end of the data */
743 /* null terminate == cheap insurance */
751 /*********************************************************************
753 * Function : get_header
755 * Description : This (odd) routine will parse the csp->iob
758 * 1 : csp = Current client state (buffers, headers, etc...)
760 * Returns : Any one of the following:
762 * 1) a pointer to a dynamically allocated string that contains a header line
763 * 2) NULL indicating that the end of the header was reached
764 * 3) "" indicating that the end of the iob was reached before finding
765 * a complete header line.
767 *********************************************************************/
768 char *get_header(struct client_state *csp)
774 if ((iob->cur == NULL)
775 || ((p = strchr(iob->cur, '\n')) == NULL))
777 return(""); /* couldn't find a complete header */
782 ret = strdup(iob->cur);
785 /* FIXME No way to handle error properly */
786 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
791 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
793 /* is this a blank line (i.e. the end of the header) ? */
805 /*********************************************************************
807 * Function : get_header_value
809 * Description : Get the value of a given header from a chained list
810 * of header lines or return NULL if no such header is
811 * present in the list.
814 * 1 : header_list = pointer to list
815 * 2 : header_name = string with name of header to look for.
816 * Trailing colon required, capitalization
819 * Returns : NULL if not found, else value of header
821 *********************************************************************/
822 char *get_header_value(const struct list *header_list, const char *header_name)
824 struct list_entry *cur_entry;
830 length = strlen(header_name);
832 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
836 if (!strncmpic(cur_entry->str, header_name, length))
839 * Found: return pointer to start of value
841 ret = (char *) (cur_entry->str + length);
842 while (*ret && ijb_isspace(*ret)) ret++;
855 /*********************************************************************
859 * Description : add, delete or modify lines in the HTTP header streams.
860 * On entry, it receives a linked list of headers space
861 * that was allocated dynamically (both the list nodes
862 * and the header contents).
864 * As a side effect it frees the space used by the original
868 * 1 : pats = list of patterns to match against headers
869 * 2 : more_headers = list of functions to add more
870 * headers (client or server)
871 * 3 : csp = Current client state (buffers, headers, etc...)
873 * Returns : Single pointer to a fully formed header, or NULL
874 * on out-of-memory error.
876 *********************************************************************/
877 char *sed(const struct parsers pats[],
878 const add_header_func_ptr more_headers[],
879 struct client_state *csp)
881 struct list_entry *p;
882 const struct parsers *v;
883 const add_header_func_ptr *f;
884 jb_err err = JB_ERR_OK;
888 * If filtering is enabled, sed is run twice,
889 * but most of the work needs to be done only once.
891 first_run = (more_headers != NULL ) ? 1 : 0;
893 if (first_run) /* Parse and print */
895 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
897 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
899 /* Header crunch()ed in previous run? -> ignore */
900 if (p->str == NULL) continue;
902 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
904 /* Does the current parser handle this header? */
905 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
907 err = v->parser(csp, (char **)&(p->str));
911 /* place any additional headers on the csp->headers list */
912 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
917 else /* Parse only */
920 * The second run is only needed if the body was modified
921 * and the content-lenght has changed.
923 if (strncmpic(csp->http->cmd, "HEAD", 4))
925 /*XXX: Code duplication*/
926 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
928 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
930 /* Header crunch()ed in previous run? -> ignore */
931 if (p->str == NULL) continue;
933 /* Does the current parser handle this header? */
934 if (strncmpic(p->str, v->str, v->len) == 0)
936 err = v->parser(csp, (char **)&(p->str));
943 if (err != JB_ERR_OK)
948 return list_to_text(csp->headers);
952 /* here begins the family of parser functions that reformat header lines */
954 /*********************************************************************
956 * Function : filter_server_header
958 * Description : Checks if server header filtering is enabled.
959 * If it is, filter_header is called to do the work.
962 * 1 : csp = Current client state (buffers, headers, etc...)
963 * 2 : header = On input, pointer to header to modify.
964 * On output, pointer to the modified header, or NULL
965 * to remove the header. This function frees the
966 * original string if necessary.
968 * Returns : JB_ERR_OK on success and always succeeds
970 *********************************************************************/
971 jb_err filter_server_header(struct client_state *csp, char **header)
973 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
975 filter_header(csp, header);
980 /*********************************************************************
982 * Function : filter_client_header
984 * Description : Checks if client header filtering is enabled.
985 * If it is, filter_header is called to do the work.
988 * 1 : csp = Current client state (buffers, headers, etc...)
989 * 2 : header = On input, pointer to header to modify.
990 * On output, pointer to the modified header, or NULL
991 * to remove the header. This function frees the
992 * original string if necessary.
994 * Returns : JB_ERR_OK on success and always succeeds
996 *********************************************************************/
997 jb_err filter_client_header(struct client_state *csp, char **header)
999 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1001 filter_header(csp, header);
1006 /*********************************************************************
1008 * Function : filter_header
1010 * Description : Executes all text substitutions from all applying
1011 * +filter actions on the header.
1012 * Most of the code was copied from pcrs_filter_response,
1013 * including the rather short variable names
1016 * 1 : csp = Current client state (buffers, headers, etc...)
1017 * 2 : header = On input, pointer to header to modify.
1018 * On output, pointer to the modified header, or NULL
1019 * to remove the header. This function frees the
1020 * original string if necessary.
1022 * Returns : JB_ERR_OK on success and always succeeds
1024 *********************************************************************/
1025 jb_err filter_header(struct client_state *csp, char **header)
1029 size_t size = strlen(*header);
1031 char *newheader = NULL;
1034 struct file_list *fl;
1035 struct re_filterfile_spec *b;
1036 struct list_entry *filtername;
1038 int i, found_filters = 0;
1041 * Need to check the set of re_filterfiles...
1043 for (i = 0; i < MAX_AF_FILES; i++)
1056 if (0 == found_filters)
1058 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1062 for (i = 0; i < MAX_AF_FILES; i++)
1065 if ((NULL == fl) || (NULL == fl->f))
1068 * For all applying +filter actions, look if a filter by that
1069 * name exists and if yes, execute its pcrs_joblist on the
1072 for (b = fl->f; b; b = b->next)
1074 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1075 filtername ; filtername = filtername->next)
1077 if (strcmp(b->name, filtername->str) == 0)
1079 int current_hits = 0;
1081 if ( NULL == b->joblist )
1083 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1087 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1088 *header, size, b->name);
1090 /* Apply all jobs from the joblist */
1091 for (job = b->joblist; NULL != job; job = job->next)
1093 matches = pcrs_execute(job, *header, size, &newheader, &size);
1096 current_hits += matches;
1097 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1099 *header = newheader;
1101 else if ( 0 == matches )
1103 /* Filter doesn't change header */
1109 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1110 *header, b->name, pcrs_strerror(matches));
1111 if( newheader != NULL)
1113 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1118 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1119 hits += current_hits;
1127 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1135 /*********************************************************************
1137 * Function : crumble
1139 * Description : This is called if a header matches a pattern to "crunch"
1142 * 1 : csp = Current client state (buffers, headers, etc...)
1143 * 2 : header = On input, pointer to header to modify.
1144 * On output, pointer to the modified header, or NULL
1145 * to remove the header. This function frees the
1146 * original string if necessary.
1148 * Returns : JB_ERR_OK on success, or
1149 * JB_ERR_MEMORY on out-of-memory error.
1151 *********************************************************************/
1152 jb_err crumble(struct client_state *csp, char **header)
1154 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1159 /*********************************************************************
1161 * Function : crunch_server_header
1163 * Description : Crunch server header if it matches a string supplied by the
1164 * user. Called from `sed'.
1167 * 1 : csp = Current client state (buffers, headers, etc...)
1168 * 2 : header = On input, pointer to header to modify.
1169 * On output, pointer to the modified header, or NULL
1170 * to remove the header. This function frees the
1171 * original string if necessary.
1173 * Returns : JB_ERR_OK on success and always succeeds
1175 *********************************************************************/
1176 jb_err crunch_server_header(struct client_state *csp, char **header)
1178 const char *crunch_pattern;
1179 /*Is there a header to crunch*/
1181 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1183 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1185 /*Is the current header the lucky one?*/
1186 if (strstr(*header, crunch_pattern))
1188 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1195 /*********************************************************************
1197 * Function : server_content_type
1199 * Description : Set the content-type for filterable types (text/.*,
1200 * javascript and image/gif) unless filtering has been
1201 * forbidden (CT_TABOO) while parsing earlier headers.
1202 * NOTE: Since text/plain is commonly used by web servers
1203 * for files whose correct type is unknown, we don't
1204 * set CT_TEXT for it.
1207 * 1 : csp = Current client state (buffers, headers, etc...)
1208 * 2 : header = On input, pointer to header to modify.
1209 * On output, pointer to the modified header, or NULL
1210 * to remove the header. This function frees the
1211 * original string if necessary.
1213 * Returns : JB_ERR_OK on success, or
1214 * JB_ERR_MEMORY on out-of-memory error.
1216 *********************************************************************/
1217 jb_err server_content_type(struct client_state *csp, char **header)
1221 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1223 if (csp->content_type != CT_TABOO)
1225 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1226 || strstr(*header, "xml")
1227 || strstr(*header, "application/x-javascript"))
1228 csp->content_type = CT_TEXT;
1229 else if (strstr(*header, " image/gif"))
1230 csp->content_type = CT_GIF;
1231 else if (strstr(*header, " image/jpeg"))
1232 csp->content_type = CT_JPEG;
1234 csp->content_type = 0;
1237 * Are we enabling text mode by force?
1239 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1242 * Do we really have to?
1244 if (csp->content_type == CT_TEXT)
1246 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1250 csp->content_type = CT_TEXT;
1251 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1255 * Are we messing with the content type?
1257 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1260 * Make sure the user doesn't accidently
1261 * change the content type of binary documents.
1263 if (csp->content_type == CT_TEXT)
1266 *header = strdup("Content-Type: ");
1267 string_append(header, newval);
1271 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1272 return JB_ERR_MEMORY;
1274 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1278 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1279 "Enable force-text-mode if you know what you're doing.", *header);
1286 /*********************************************************************
1288 * Function : server_transfer_coding
1290 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1291 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1292 * - Remove header if body was chunked but has been
1293 * de-chunked for filtering.
1296 * 1 : csp = Current client state (buffers, headers, etc...)
1297 * 2 : header = On input, pointer to header to modify.
1298 * On output, pointer to the modified header, or NULL
1299 * to remove the header. This function frees the
1300 * original string if necessary.
1302 * Returns : JB_ERR_OK on success, or
1303 * JB_ERR_MEMORY on out-of-memory error.
1305 *********************************************************************/
1306 jb_err server_transfer_coding(struct client_state *csp, char **header)
1309 * Turn off pcrs and gif filtering if body compressed
1311 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1313 csp->content_type = CT_TABOO;
1317 * Raise flag if body chunked
1319 if (strstr(*header, "chunked"))
1321 csp->flags |= CSP_FLAG_CHUNKED;
1324 * If the body was modified, it has been de-chunked first
1325 * and the header must be removed.
1327 if (csp->flags & CSP_FLAG_MODIFIED)
1329 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1338 /*********************************************************************
1340 * Function : server_content_encoding
1342 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1345 * 1 : csp = Current client state (buffers, headers, etc...)
1346 * 2 : header = On input, pointer to header to modify.
1347 * On output, pointer to the modified header, or NULL
1348 * to remove the header. This function frees the
1349 * original string if necessary.
1351 * Returns : JB_ERR_OK on success, or
1352 * JB_ERR_MEMORY on out-of-memory error.
1354 *********************************************************************/
1355 jb_err server_content_encoding(struct client_state *csp, char **header)
1358 * Turn off pcrs and gif filtering if body compressed
1360 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1362 csp->content_type = CT_TABOO;
1370 /*********************************************************************
1372 * Function : server_content_length
1374 * Description : Adjust Content-Length header if we modified
1378 * 1 : csp = Current client state (buffers, headers, etc...)
1379 * 2 : header = On input, pointer to header to modify.
1380 * On output, pointer to the modified header, or NULL
1381 * to remove the header. This function frees the
1382 * original string if necessary.
1384 * Returns : JB_ERR_OK on success, or
1385 * JB_ERR_MEMORY on out-of-memory error.
1387 *********************************************************************/
1388 jb_err server_content_length(struct client_state *csp, char **header)
1390 if (csp->content_length != 0) /* Content length could have been modified */
1393 * XXX: Shouldn't we check if csp->content_length
1394 * is different than the original value?
1397 *header = (char *) zalloc(100);
1398 if (*header == NULL)
1400 return JB_ERR_MEMORY;
1403 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1405 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1412 /*********************************************************************
1414 * Function : server_content_md5
1416 * Description : Crumble any Content-MD5 headers if the document was
1417 * modified. FIXME: Should we re-compute instead?
1420 * 1 : csp = Current client state (buffers, headers, etc...)
1421 * 2 : header = On input, pointer to header to modify.
1422 * On output, pointer to the modified header, or NULL
1423 * to remove the header. This function frees the
1424 * original string if necessary.
1426 * Returns : JB_ERR_OK on success, or
1427 * JB_ERR_MEMORY on out-of-memory error.
1429 *********************************************************************/
1430 jb_err server_content_md5(struct client_state *csp, char **header)
1432 if (csp->flags & CSP_FLAG_MODIFIED)
1434 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1441 /*********************************************************************
1443 * Function : server_content_disposition
1445 * Description : If enabled, blocks or modifies the "content-disposition" header.
1446 * Called from `sed'.
1449 * 1 : csp = Current client state (buffers, headers, etc...)
1450 * 2 : header = On input, pointer to header to modify.
1451 * On output, pointer to the modified header, or NULL
1452 * to remove the header. This function frees the
1453 * original string if necessary.
1455 * Returns : JB_ERR_OK on success, or
1456 * JB_ERR_MEMORY on out-of-memory error.
1458 *********************************************************************/
1459 jb_err server_content_disposition(struct client_state *csp, char **header)
1464 * Are we messing with the content-disposition header?
1466 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1472 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1474 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1477 * Blocking content-disposition header
1479 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1486 * Replacing content-disposition header
1489 *header = strdup("content-disposition: ");
1490 string_append(header, newval);
1492 if (*header == NULL)
1494 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1498 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1501 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1504 /*********************************************************************
1506 * Function : server_last_modified
1508 * Description : Changes Last-Modified header to the actual date
1509 * to help hide-if-modified-since.
1510 * Called from `sed'.
1513 * 1 : csp = Current client state (buffers, headers, etc...)
1514 * 2 : header = On input, pointer to header to modify.
1515 * On output, pointer to the modified header, or NULL
1516 * to remove the header. This function frees the
1517 * original string if necessary.
1519 * Returns : JB_ERR_OK on success, or
1520 * JB_ERR_MEMORY on out-of-memory error.
1522 *********************************************************************/
1523 jb_err server_last_modified(struct client_state *csp, char **header)
1526 char buf[BUFFER_SIZE];
1529 #ifdef HAVE_GMTIME_R
1532 struct tm *timeptr = NULL;
1533 time_t now, last_modified;
1535 long int days, hours, minutes, seconds;
1538 * Are we messing with the Last-Modified header?
1540 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1546 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1548 if (0 == strcmpic(newval, "block") )
1551 * Blocking Last-Modified header. Useless but why not.
1553 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1557 else if (0 == strcmpic(newval, "reset-to-request-time"))
1560 * Setting Last-Modified Header to now.
1562 get_http_time(0, buf);
1564 *header = strdup("Last-Modified: ");
1565 string_append(header, buf);
1567 if (*header == NULL)
1569 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1573 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1576 else if (0 == strcmpic(newval, "randomize"))
1578 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1580 #ifdef HAVE_GMTIME_R
1581 timeptr = gmtime_r(&now, &gmt);
1582 #elif FEATURE_PTHREAD
1583 pthread_mutex_lock(&gmtime_mutex);
1584 timeptr = gmtime(&now);
1585 pthread_mutex_unlock(&gmtime_mutex);
1587 timeptr = gmtime(&now);
1589 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1591 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1596 rtime = difftime(now, last_modified);
1599 rtime = pick_from_range(rtime);
1600 last_modified += rtime;
1601 #ifdef HAVE_GMTIME_R
1602 timeptr = gmtime_r(&last_modified, &gmt);
1603 #elif FEATURE_PTHREAD
1604 pthread_mutex_lock(&gmtime_mutex);
1605 timeptr = gmtime(&last_modified);
1606 pthread_mutex_unlock(&gmtime_mutex);
1608 timeptr = gmtime(&last_modified);
1610 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1612 *header = strdup("Last-Modified: ");
1613 string_append(header, newheader);
1615 if (*header == NULL)
1617 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1618 return JB_ERR_MEMORY;
1621 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1623 days = rtime / (3600 * 24);
1624 hours = rtime / 3600 % 24;
1625 minutes = rtime / 60 % 60;
1626 seconds = rtime % 60;
1628 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1629 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1630 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1635 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1643 /*********************************************************************
1645 * Function : client_accept_encoding
1647 * Description : Rewrite the client's Accept-Encoding header so that
1648 * if doesn't allow compression, if the action applies.
1649 * Note: For HTTP/1.0 the absence of the header is enough.
1652 * 1 : csp = Current client state (buffers, headers, etc...)
1653 * 2 : header = On input, pointer to header to modify.
1654 * On output, pointer to the modified header, or NULL
1655 * to remove the header. This function frees the
1656 * original string if necessary.
1658 * Returns : JB_ERR_OK on success, or
1659 * JB_ERR_MEMORY on out-of-memory error.
1661 *********************************************************************/
1662 jb_err client_accept_encoding(struct client_state *csp, char **header)
1664 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1666 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1670 /* Temporarily disable the correct behaviour to
1671 * work around a PHP bug.
1673 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1675 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1676 * if (*header == NULL)
1678 * return JB_ERR_MEMORY;
1689 /*********************************************************************
1691 * Function : client_te
1693 * Description : Rewrite the client's TE header so that
1694 * if doesn't allow compression, if the action applies.
1697 * 1 : csp = Current client state (buffers, headers, etc...)
1698 * 2 : header = On input, pointer to header to modify.
1699 * On output, pointer to the modified header, or NULL
1700 * to remove the header. This function frees the
1701 * original string if necessary.
1703 * Returns : JB_ERR_OK on success, or
1704 * JB_ERR_MEMORY on out-of-memory error.
1706 *********************************************************************/
1707 jb_err client_te(struct client_state *csp, char **header)
1709 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1712 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1718 /*********************************************************************
1720 * Function : client_referrer
1722 * Description : Handle the "referer" config setting properly.
1723 * Called from `sed'.
1726 * 1 : csp = Current client state (buffers, headers, etc...)
1727 * 2 : header = On input, pointer to header to modify.
1728 * On output, pointer to the modified header, or NULL
1729 * to remove the header. This function frees the
1730 * original string if necessary.
1732 * Returns : JB_ERR_OK on success, or
1733 * JB_ERR_MEMORY on out-of-memory error.
1735 *********************************************************************/
1736 jb_err client_referrer(struct client_state *csp, char **header)
1743 #ifdef FEATURE_FORCE_LOAD
1744 /* Since the referrer can include the prefix even
1745 * if the request itself is non-forced, we must
1746 * clean it unconditionally
1748 strclean(*header, FORCE_PREFIX);
1749 #endif /* def FEATURE_FORCE_LOAD */
1752 * Are we sending referer?
1754 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1759 newval = csp->action->string[ACTION_STRING_REFERER];
1761 if ((0 != strcmpic(newval, "conditional-block")))
1765 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1770 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1773 else if (0 == strcmpic(newval, "conditional-block"))
1776 * Block referer if host has changed.
1779 if (NULL == (host = strdup(csp->http->hostport)))
1782 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1783 return JB_ERR_MEMORY;
1785 if (NULL == (referer = strdup(*header)))
1789 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1790 return JB_ERR_MEMORY;
1792 hostlenght = strlen(host);
1793 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1795 /*Shorten referer to make sure the referer is blocked
1796 *if www.example.org/www.example.com-shall-see-the-referer/
1797 *links to www.example.com/
1799 referer[hostlenght+17] = '\0';
1801 if ( 0 == strstr(referer, host)) /*Host has changed*/
1803 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1808 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1814 else if (0 != strcmpic(newval, "forge"))
1817 * We have a specific (fixed) referer we want to send.
1819 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1821 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1823 *header = strdup("Referer: ");
1824 string_append(header, newval);
1825 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1827 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1832 * Forge a referer as http://[hostname:port of REQUEST]/
1833 * to fool stupid checks for in-site links
1836 *header = strdup("Referer: http://");
1837 string_append(header, csp->http->hostport);
1838 string_append(header, "/");
1839 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1841 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1845 /*********************************************************************
1847 * Function : client_accept_language
1849 * Description : Handle the "Accept-Language" config setting properly.
1850 * Called from `sed'.
1853 * 1 : csp = Current client state (buffers, headers, etc...)
1854 * 2 : header = On input, pointer to header to modify.
1855 * On output, pointer to the modified header, or NULL
1856 * to remove the header. This function frees the
1857 * original string if necessary.
1859 * Returns : JB_ERR_OK on success, or
1860 * JB_ERR_MEMORY on out-of-memory error.
1862 *********************************************************************/
1863 jb_err client_accept_language(struct client_state *csp, char **header)
1868 * Are we messing with the Accept-Language?
1870 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1872 /*I don't think so*/
1876 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1878 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1881 * Blocking Accept-Language header
1883 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1890 * Replacing Accept-Language header
1893 *header = strdup("Accept-Language: ");
1894 string_append(header, newval);
1896 if (*header == NULL)
1898 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1902 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1905 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1908 /*********************************************************************
1910 * Function : crunch_client_header
1912 * Description : Crunch client header if it matches a string supplied by the
1913 * user. Called from `sed'.
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * 2 : header = On input, pointer to header to modify.
1918 * On output, pointer to the modified header, or NULL
1919 * to remove the header. This function frees the
1920 * original string if necessary.
1922 * Returns : JB_ERR_OK on success and always succeeds
1924 *********************************************************************/
1925 jb_err crunch_client_header(struct client_state *csp, char **header)
1927 const char *crunch_pattern;
1928 /*Is there a header to crunch*/
1930 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1932 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1934 /*Is the current header the lucky one?*/
1935 if (strstr(*header, crunch_pattern))
1937 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1945 /*********************************************************************
1947 * Function : client_uagent
1949 * Description : Handle the "user-agent" config setting properly
1950 * and remember its original value to enable browser
1951 * bug workarounds. Called from `sed'.
1954 * 1 : csp = Current client state (buffers, headers, etc...)
1955 * 2 : header = On input, pointer to header to modify.
1956 * On output, pointer to the modified header, or NULL
1957 * to remove the header. This function frees the
1958 * original string if necessary.
1960 * Returns : JB_ERR_OK on success, or
1961 * JB_ERR_MEMORY on out-of-memory error.
1963 *********************************************************************/
1964 jb_err client_uagent(struct client_state *csp, char **header)
1968 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1973 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1980 *header = strdup("User-Agent: ");
1981 string_append(header, newval);
1983 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1985 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1988 /*********************************************************************
1990 * Function : client_ua
1992 * Description : Handle "ua-" headers properly. Called from `sed'.
1995 * 1 : csp = Current client state (buffers, headers, etc...)
1996 * 2 : header = On input, pointer to header to modify.
1997 * On output, pointer to the modified header, or NULL
1998 * to remove the header. This function frees the
1999 * original string if necessary.
2001 * Returns : JB_ERR_OK on success, or
2002 * JB_ERR_MEMORY on out-of-memory error.
2004 *********************************************************************/
2005 jb_err client_ua(struct client_state *csp, char **header)
2007 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2009 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2017 /*********************************************************************
2019 * Function : client_from
2021 * Description : Handle the "from" config setting properly.
2022 * Called from `sed'.
2025 * 1 : csp = Current client state (buffers, headers, etc...)
2026 * 2 : header = On input, pointer to header to modify.
2027 * On output, pointer to the modified header, or NULL
2028 * to remove the header. This function frees the
2029 * original string if necessary.
2031 * Returns : JB_ERR_OK on success, or
2032 * JB_ERR_MEMORY on out-of-memory error.
2034 *********************************************************************/
2035 jb_err client_from(struct client_state *csp, char **header)
2039 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2046 newval = csp->action->string[ACTION_STRING_FROM];
2049 * Are we blocking the e-mail address?
2051 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2053 log_error(LOG_LEVEL_HEADER, "crunched From!");
2057 log_error(LOG_LEVEL_HEADER, " modified");
2059 *header = strdup("From: ");
2060 string_append(header, newval);
2062 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2066 /*********************************************************************
2068 * Function : client_send_cookie
2070 * Description : Handle the "cookie" header properly. Called from `sed'.
2071 * If cookie is accepted, add it to the cookie_list,
2072 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2075 * 1 : csp = Current client state (buffers, headers, etc...)
2076 * 2 : header = On input, pointer to header to modify.
2077 * On output, pointer to the modified header, or NULL
2078 * to remove the header. This function frees the
2079 * original string if necessary.
2081 * Returns : JB_ERR_OK on success, or
2082 * JB_ERR_MEMORY on out-of-memory error.
2084 *********************************************************************/
2085 jb_err client_send_cookie(struct client_state *csp, char **header)
2087 jb_err result = JB_ERR_OK;
2089 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2091 /* strlen("cookie: ") == 8 */
2092 result = enlist(csp->cookie_list, *header + 8);
2096 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2100 * Always remove the cookie here. The cookie header
2101 * will be sent at the end of the header.
2109 /*********************************************************************
2111 * Function : client_x_forwarded
2113 * Description : Handle the "x-forwarded-for" config setting properly,
2114 * also used in the add_client_headers list. Called from `sed'.
2117 * 1 : csp = Current client state (buffers, headers, etc...)
2118 * 2 : header = On input, pointer to header to modify.
2119 * On output, pointer to the modified header, or NULL
2120 * to remove the header. This function frees the
2121 * original string if necessary.
2123 * Returns : JB_ERR_OK on success, or
2124 * JB_ERR_MEMORY on out-of-memory error.
2126 *********************************************************************/
2127 jb_err client_x_forwarded(struct client_state *csp, char **header)
2129 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2131 /* Save it so we can re-add it later */
2132 freez(csp->x_forwarded);
2133 csp->x_forwarded = *header;
2136 * Always set *header = NULL, since this information
2137 * will be sent at the end of the header.
2144 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2151 /*********************************************************************
2153 * Function : client_max_forwards
2155 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2156 * from the value of the Max-Forwards header field.
2159 * 1 : csp = Current client state (buffers, headers, etc...)
2160 * 2 : header = On input, pointer to header to modify.
2161 * On output, pointer to the modified header, or NULL
2162 * to remove the header. This function frees the
2163 * original string if necessary.
2165 * Returns : JB_ERR_OK on success, or
2166 * JB_ERR_MEMORY on out-of-memory error.
2168 *********************************************************************/
2169 jb_err client_max_forwards(struct client_state *csp, char **header)
2171 unsigned int max_forwards;
2173 if ((0 == strcmpic(csp->http->gpc, "trace"))
2174 || (0 == strcmpic(csp->http->gpc, "options")))
2176 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2178 if (max_forwards-- >= 1)
2180 sprintf(*header, "Max-Forwards: %u", max_forwards);
2181 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2185 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2194 /*********************************************************************
2196 * Function : client_host
2198 * Description : If the request URI did not contain host and
2199 * port information, parse and evaluate the Host
2202 * Also, kill ill-formed HOST: headers as sent by
2203 * Apple's iTunes software when used with a proxy.
2206 * 1 : csp = Current client state (buffers, headers, etc...)
2207 * 2 : header = On input, pointer to header to modify.
2208 * On output, pointer to the modified header, or NULL
2209 * to remove the header. This function frees the
2210 * original string if necessary.
2212 * Returns : JB_ERR_OK on success, or
2213 * JB_ERR_MEMORY on out-of-memory error.
2215 *********************************************************************/
2216 jb_err client_host(struct client_state *csp, char **header)
2221 * If the header field name is all upper-case, chances are that it's
2222 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2223 * not a problem -- they are regenerated later.
2225 if ((*header)[1] == 'O')
2227 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2232 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2233 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2236 if (NULL == (p = strdup((*header)+6)))
2238 return JB_ERR_MEMORY;
2241 if (NULL == (q = strdup(p)))
2244 return JB_ERR_MEMORY;
2247 freez(csp->http->hostport);
2248 csp->http->hostport = p;
2249 freez(csp->http->host);
2250 csp->http->host = q;
2251 q = strchr(csp->http->host, ':');
2254 /* Terminate hostname and evaluate port string */
2256 csp->http->port = atoi(q);
2260 csp->http->port = csp->http->ssl ? 443 : 80;
2263 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2264 csp->http->hostport, csp->http->host, csp->http->port);
2270 /*********************************************************************
2272 * Function : client_if_modified_since
2274 * Description : Remove or modify the If-Modified-Since header.
2277 * 1 : csp = Current client state (buffers, headers, etc...)
2278 * 2 : header = On input, pointer to header to modify.
2279 * On output, pointer to the modified header, or NULL
2280 * to remove the header. This function frees the
2281 * original string if necessary.
2283 * Returns : JB_ERR_OK on success, or
2284 * JB_ERR_MEMORY on out-of-memory error.
2286 *********************************************************************/
2287 jb_err client_if_modified_since(struct client_state *csp, char **header)
2290 #ifdef HAVE_GMTIME_R
2293 struct tm *timeptr = NULL;
2297 long int hours, minutes, seconds;
2301 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2304 * The client got an error message because of a temporary problem,
2305 * the problem is gone and the client now tries to revalidate our
2306 * error message on the real server. The revalidation would always
2307 * end with the transmission of the whole document and there is
2308 * no need to expose the bogus If-Modified-Since header.
2310 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2313 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2315 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2317 if ((0 == strcmpic(newval, "block")))
2319 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2322 else /* add random value */
2324 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2326 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2331 rtime = strtol(newval, &endptr, 0);
2334 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2335 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2342 rtime = pick_from_range(rtime);
2346 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2349 tm += rtime * (negative ? -1 : 1);
2350 #ifdef HAVE_GMTIME_R
2351 timeptr = gmtime_r(&tm, &gmt);
2352 #elif FEATURE_PTHREAD
2353 pthread_mutex_lock(&gmtime_mutex);
2354 timeptr = gmtime(&tm);
2355 pthread_mutex_unlock(&gmtime_mutex);
2357 timeptr = gmtime(&tm);
2359 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2362 *header = strdup("If-Modified-Since: ");
2363 string_append(header, newheader);
2365 if (*header == NULL)
2367 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2368 return JB_ERR_MEMORY;
2371 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2373 hours = rtime / 3600;
2374 minutes = rtime / 60 % 60;
2375 seconds = rtime % 60;
2377 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2378 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2379 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2388 /*********************************************************************
2390 * Function : client_if_none_match
2392 * Description : Remove the If-None-Match header.
2395 * 1 : csp = Current client state (buffers, headers, etc...)
2396 * 2 : header = On input, pointer to header to modify.
2397 * On output, pointer to the modified header, or NULL
2398 * to remove the header. This function frees the
2399 * original string if necessary.
2401 * Returns : JB_ERR_OK on success, or
2402 * JB_ERR_MEMORY on out-of-memory error.
2404 *********************************************************************/
2405 jb_err client_if_none_match(struct client_state *csp, char **header)
2407 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2409 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2416 /*********************************************************************
2418 * Function : client_x_filter
2420 * Description : Disables filtering if the client set "X-Filter: No".
2421 * Called from `sed'.
2424 * 1 : csp = Current client state (buffers, headers, etc...)
2425 * 2 : header = On input, pointer to header to modify.
2426 * On output, pointer to the modified header, or NULL
2427 * to remove the header. This function frees the
2428 * original string if necessary.
2430 * Returns : JB_ERR_OK on success
2432 *********************************************************************/
2433 jb_err client_x_filter(struct client_state *csp, char **header)
2435 if ( 0 == strcmpic(*header, "X-Filter: No"))
2437 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2439 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2443 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2445 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2449 csp->content_type = CT_TABOO;
2450 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2451 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2452 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2454 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2461 /* the following functions add headers directly to the header list */
2463 /*********************************************************************
2465 * Function : client_host_adder
2467 * Description : Adds the Host: header field if it is missing.
2468 * Called from `sed'.
2471 * 1 : csp = Current client state (buffers, headers, etc...)
2473 * Returns : JB_ERR_OK on success, or
2474 * JB_ERR_MEMORY on out-of-memory error.
2476 *********************************************************************/
2477 jb_err client_host_adder(struct client_state *csp)
2482 if ( !csp->http->hostport || !*(csp->http->hostport))
2488 * remove 'user:pass@' from 'proto://user:pass@host'
2490 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2496 p = csp->http->hostport;
2499 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2500 err = enlist_unique_header(csp->headers, "Host", p);
2506 /*********************************************************************
2508 * Function : client_cookie_adder
2510 * Description : Used in the add_client_headers list. Called from `sed'.
2513 * 1 : csp = Current client state (buffers, headers, etc...)
2515 * Returns : JB_ERR_OK on success, or
2516 * JB_ERR_MEMORY on out-of-memory error.
2518 *********************************************************************/
2519 jb_err client_cookie_adder(struct client_state *csp)
2521 struct list_entry *lst;
2523 struct list_entry *list1 = csp->cookie_list->first;
2524 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2525 int first_cookie = 1;
2528 if ((list1 == NULL) && (list2 == NULL))
2534 tmp = strdup("Cookie: ");
2536 for (lst = list1; lst ; lst = lst->next)
2544 string_append(&tmp, "; ");
2546 string_append(&tmp, lst->str);
2549 for (lst = list2; lst ; lst = lst->next)
2557 string_append(&tmp, "; ");
2559 string_join(&tmp, cookie_encode(lst->str));
2564 return JB_ERR_MEMORY;
2567 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2568 err = enlist(csp->headers, tmp);
2574 /*********************************************************************
2576 * Function : client_accept_encoding_adder
2578 * Description : Add an Accept-Encoding header to the client's request
2579 * that disables compression if the action applies, and
2580 * the header is not already there. Called from `sed'.
2581 * Note: For HTTP/1.0, the absence of the header is enough.
2584 * 1 : csp = Current client state (buffers, headers, etc...)
2586 * Returns : JB_ERR_OK on success, or
2587 * JB_ERR_MEMORY on out-of-memory error.
2589 *********************************************************************/
2590 jb_err client_accept_encoding_adder(struct client_state *csp)
2592 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2593 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2595 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2602 /*********************************************************************
2604 * Function : client_xtra_adder
2606 * Description : Used in the add_client_headers list. Called from `sed'.
2609 * 1 : csp = Current client state (buffers, headers, etc...)
2611 * Returns : JB_ERR_OK on success, or
2612 * JB_ERR_MEMORY on out-of-memory error.
2614 *********************************************************************/
2615 jb_err client_xtra_adder(struct client_state *csp)
2617 struct list_entry *lst;
2620 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2621 lst ; lst = lst->next)
2623 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2624 err = enlist(csp->headers, lst->str);
2636 /*********************************************************************
2638 * Function : client_x_forwarded_adder
2640 * Description : Used in the add_client_headers list. Called from `sed'.
2643 * 1 : csp = Current client state (buffers, headers, etc...)
2645 * Returns : JB_ERR_OK on success, or
2646 * JB_ERR_MEMORY on out-of-memory error.
2648 *********************************************************************/
2649 jb_err client_x_forwarded_adder(struct client_state *csp)
2654 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2659 if (csp->x_forwarded)
2661 p = strdup(csp->x_forwarded);
2662 string_append(&p, ", ");
2666 p = strdup("X-Forwarded-For: ");
2668 string_append(&p, csp->ip_addr_str);
2672 return JB_ERR_MEMORY;
2675 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2676 err = enlist(csp->headers, p);
2683 /*********************************************************************
2685 * Function : connection_close_adder
2687 * Description : Adds a "Connection: close" header to csp->headers
2688 * as a temporary fix for the needed but missing HTTP/1.1
2689 * support. Called from `sed'.
2690 * FIXME: This whole function shouldn't be neccessary!
2693 * 1 : csp = Current client state (buffers, headers, etc...)
2695 * Returns : JB_ERR_OK on success, or
2696 * JB_ERR_MEMORY on out-of-memory error.
2698 *********************************************************************/
2699 jb_err connection_close_adder(struct client_state *csp)
2701 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2702 return enlist(csp->headers, "Connection: close");
2706 /*********************************************************************
2708 * Function : server_http
2710 * Description : - Save the HTTP Status into csp->http->status
2711 * - Set CT_TABOO to prevent filtering if the answer
2712 * is a partial range (HTTP status 206)
2713 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2717 * 1 : csp = Current client state (buffers, headers, etc...)
2718 * 2 : header = On input, pointer to header to modify.
2719 * On output, pointer to the modified header, or NULL
2720 * to remove the header. This function frees the
2721 * original string if necessary.
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 jb_err server_http(struct client_state *csp, char **header)
2729 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2730 if (csp->http->status == 206)
2732 csp->content_type = CT_TABOO;
2735 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2738 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2745 /*********************************************************************
2747 * Function : server_set_cookie
2749 * Description : Handle the server "cookie" header properly.
2750 * Log cookie to the jar file. Then "crunch" it,
2751 * or accept it. Called from `sed'.
2754 * 1 : csp = Current client state (buffers, headers, etc...)
2755 * 2 : header = On input, pointer to header to modify.
2756 * On output, pointer to the modified header, or NULL
2757 * to remove the header. This function frees the
2758 * original string if necessary.
2760 * Returns : JB_ERR_OK on success, or
2761 * JB_ERR_MEMORY on out-of-memory error.
2763 *********************************************************************/
2764 jb_err server_set_cookie(struct client_state *csp, char **header)
2766 #ifdef FEATURE_COOKIE_JAR
2767 if (csp->config->jar)
2770 * Write timestamp into outbuf.
2772 * Complex because not all OSs have tm_gmtoff or
2773 * the %z field in strftime()
2775 char tempbuf[ BUFFER_SIZE ];
2779 #ifdef HAVE_LOCALTIME_R
2780 tm_now = *localtime_r(&now, &tm_now);
2781 #elif FEATURE_PTHREAD
2782 pthread_mutex_lock(&localtime_mutex);
2783 tm_now = *localtime (&now);
2784 pthread_mutex_unlock(&localtime_mutex);
2786 tm_now = *localtime (&now);
2788 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2790 /* strlen("set-cookie: ") = 12 */
2791 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2793 #endif /* def FEATURE_COOKIE_JAR */
2795 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2797 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2798 return crumble(csp, header);
2800 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2802 /* Flag whether or not to log a message */
2805 /* A variable to store the tag we're working on */
2808 /* Skip "Set-Cookie:" (11 characters) in header */
2809 cur_tag = *header + 11;
2811 /* skip whitespace between "Set-Cookie:" and value */
2812 while (*cur_tag && ijb_isspace(*cur_tag))
2817 /* Loop through each tag in the cookie */
2821 char *next_tag = strchr(cur_tag, ';');
2822 if (next_tag != NULL)
2824 /* Skip the ';' character itself */
2827 /* skip whitespace ";" and start of tag */
2828 while (*next_tag && ijb_isspace(*next_tag))
2835 /* "Next tag" is the end of the string */
2836 next_tag = cur_tag + strlen(cur_tag);
2839 /* Is this the "Expires" tag? */
2840 if (strncmpic(cur_tag, "expires=", 8) == 0)
2842 /* Delete the tag by copying the rest of the string over it.
2843 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2844 * since the behaviour of strcpy is undefined for overlapping
2847 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2849 /* That changed the header, need to issue a log message */
2852 /* Note that the next tag has now been moved to *cur_tag,
2853 * so we do not need to update the cur_tag pointer.
2858 /* Move on to next cookie tag */
2865 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2873 #ifdef FEATURE_FORCE_LOAD
2874 /*********************************************************************
2876 * Function : strclean
2878 * Description : In-Situ-Eliminate all occurances of substring in
2882 * 1 : string = string to clean
2883 * 2 : substring = substring to eliminate
2885 * Returns : Number of eliminations
2887 *********************************************************************/
2888 int strclean(const char *string, const char *substring)
2890 int hits = 0, len = strlen(substring);
2893 while((pos = strstr(string, substring)) != NULL)
2900 while (*p++ != '\0');
2907 #endif /* def FEATURE_FORCE_LOAD */
2909 /*********************************************************************
2911 * Function : parse_header_time
2913 * Description : Transforms time inside a HTTP header into
2914 * the usual time format.
2917 * 1 : header = header to parse
2918 * 2 : tm = storage for the resulting time in seconds
2920 * Returns : Time struct containing the header time, or
2921 * NULL in case of a parsing problem.
2923 *********************************************************************/
2924 struct tm *parse_header_time(char *header, time_t *tm) {
2928 struct tm * timeptr;
2930 /* Skipping header name */
2931 timestring = strstr(header, ": ");
2932 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)