1 const char parsers_rcs[] = "$Id: parsers.c,v 1.79 2006/12/29 18:04:40 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_server_header'
14 * `filter_client_header', `filter_header', `crunch_server_header',
15 * `server_content_encoding', `server_content_disposition',
16 * `server_last_modified', `client_accept_language',
17 * `crunch_client_header', `client_if_modified_since',
18 * `client_if_none_match', `get_destination_from_headers',
19 * `parse_header_time' and `server_set_cookie'.
21 * Copyright : Written by and Copyright (C) 2001-2006 the SourceForge
22 * Privoxy team. http://www.privoxy.org/
24 * Based on the Internet Junkbuster originally written
25 * by and Copyright (C) 1997 Anonymous Coders and
26 * Junkbusters Corporation. http://www.junkbusters.com
28 * This program is free software; you can redistribute it
29 * and/or modify it under the terms of the GNU General
30 * Public License as published by the Free Software
31 * Foundation; either version 2 of the License, or (at
32 * your option) any later version.
34 * This program is distributed in the hope that it will
35 * be useful, but WITHOUT ANY WARRANTY; without even the
36 * implied warranty of MERCHANTABILITY or FITNESS FOR A
37 * PARTICULAR PURPOSE. See the GNU General Public
38 * License for more details.
40 * The GNU General Public License should be included with
41 * this file. If not, you can view it at
42 * http://www.gnu.org/copyleft/gpl.html
43 * or write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
48 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
49 * Fixed gcc43 conversion warnings.
51 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
52 * Bringing back the "useless" localtime() call
53 * I removed in revision 1.67. On some platforms
54 * it's necessary to prevent time zone offsets.
56 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
57 * Rebuild request URL in get_destination_from_headers()
58 * to make sure redirect{pcrs command} works as expected
59 * for intercepted requests.
61 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
62 * Added get_destination_from_headers().
64 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
65 * Make pthread mutex locking more generic. Instead of
66 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
67 * and use mutex locking unless there is an _r function
68 * available. Better safe than sorry.
70 * Fixes "./configure --disable-pthread" and should result
71 * in less threading-related problems on pthread-using platforms,
72 * but it still doesn't fix BR#1122404.
74 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
75 * The special header "X-Filter: No" now disables
76 * header filtering as well.
78 * Revision 1.73 2006/09/23 13:26:38 roro
79 * Replace TABs by spaces in source code.
81 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
82 * Don't print a log message every time filter_headers is
83 * entered or left. It only creates noise without any real
86 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
87 * Fix +hide-if-modified-since{-n}.
89 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
90 * Have hide-if-modified-since interpret the random
91 * range value as minutes instead of hours. Allows
92 * more fine-grained configuration.
94 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
95 * Always have parse_header_time return a pointer
96 * that actual makes sense, even though we currently
97 * only need it to detect problems.
99 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
100 * Added config option enable-remote-http-toggle
101 * to specify if Privoxy should recognize special
102 * headers (currently only X-Filter) to change its
103 * behaviour. Disabled by default.
105 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
106 * After filtering de-chunked instances, remove
107 * "Transfer-Encoding" header entirely instead of changing
108 * it to "Transfer-Encoding: identity", which is invalid.
109 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
111 * Don't use localtime in parse_header_time. An empty time struct
112 * is good enough, it gets overwritten by strptime anyway.
114 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
115 * Use gmtime_r if available, fallback to gmtime with mutex
116 * protection for MacOSX and use vanilla gmtime for the rest.
118 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
119 * Changed client_referrer to use the right type (size_t) for
120 * hostlenght and to shorten the temporary referrer string with
121 * '\0' instead of adding a useless line break.
123 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
124 * - Back to timegm() using GnuPG's replacement if necessary.
125 * Using mktime() and localtime() could add a on hour offset if
126 * the randomize factor was big enough to lead to a summer/wintertime
129 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
131 * - Moved randomization code into pick_from_range().
133 * - Changed parse_header_time definition.
134 * time_t isn't guaranteed to be signed and
135 * if it isn't, -1 isn't available as error code.
136 * Changed some variable types in client_if_modified_since()
137 * because of the same reason.
139 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
140 * OS/2 compilation compatibility fixups
142 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
143 * Changed include from strptime.c to strptime.h
145 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
146 * Split filter-headers{} into filter-client-headers{}
147 * and filter-server-headers{}.
148 * Added parse_header_time() to share some code.
149 * Replaced timegm() with mktime().
151 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
152 * Windows service integration
154 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
155 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
157 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
158 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
159 * with what was really the latest development (the v_3_0_branch branch)
161 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
162 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
164 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
165 * Add the ability to check jpeg images for invalid
166 * lengths of comment blocks. Defensive strategy
167 * against the exploit:
168 * Microsoft Security Bulletin MS04-028
169 * Buffer Overrun in JPEG Processing (GDI+) Could
170 * Allow Code Execution (833987)
171 * Enabled with +inspect-jpegs in actions files.
173 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
174 * Excluded text/plain objects from filtering. This fixes a
175 * couple of client-crashing, download corruption and
176 * Privoxy performance issues, whose root cause lies in
177 * web servers labelling content of unknown type as text/plain.
179 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
180 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
182 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
183 * Completing the previous change
185 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
186 * Added temporary workaround for bug in PHP < 4.2.3
188 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
189 * 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.
191 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
192 * Fix typo: supressed -> suppressed
194 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
195 * Improved cookie logging
197 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
198 * Added basic support for OPTIONS and TRACE HTTP methods:
199 * - New parser function client_max_forwards which decrements
200 * the Max-Forwards HTTP header field of OPTIONS and TRACE
201 * requests by one before forwarding
202 * - New parser function client_host which extracts the host
203 * and port information from the HTTP header field if the
204 * request URI was not absolute
205 * - Don't crumble and re-add the Host: header, but only generate
206 * and append if missing
208 * Revision 1.56 2002/05/12 15:34:22 jongfoster
209 * Fixing typo in a comment
211 * Revision 1.55 2002/05/08 16:01:07 oes
212 * Optimized add_to_iob:
213 * - Use realloc instead of malloc(), memcpy(), free()
214 * - Expand to powers of two if possible, to get
215 * O(log n) reallocs instead of O(n).
216 * - Moved check for buffer limit here from chat
217 * - Report failure via returncode
219 * Revision 1.54 2002/04/02 15:03:16 oes
220 * Tiny code cosmetics
222 * Revision 1.53 2002/03/26 22:29:55 swa
223 * we have a new homepage!
225 * Revision 1.52 2002/03/24 13:25:43 swa
226 * name change related issues
228 * Revision 1.51 2002/03/13 00:27:05 jongfoster
231 * Revision 1.50 2002/03/12 01:45:35 oes
232 * More verbose logging
234 * Revision 1.49 2002/03/09 20:03:52 jongfoster
235 * - Making various functions return int rather than size_t.
236 * (Undoing a recent change). Since size_t is unsigned on
237 * Windows, functions like read_socket that return -1 on
238 * error cannot return a size_t.
240 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
241 * crashes, and also frequently caused JB to jump to 100%
242 * CPU and stay there. (Because it thought it had just
243 * read ((unsigned)-1) == 4Gb of data...)
245 * - The signature of write_socket has changed, it now simply
246 * returns success=0/failure=nonzero.
248 * - Trying to get rid of a few warnings --with-debug on
249 * Windows, I've introduced a new type "jb_socket". This is
250 * used for the socket file descriptors. On Windows, this
251 * is SOCKET (a typedef for unsigned). Everywhere else, it's
252 * an int. The error value can't be -1 any more, so it's
253 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
254 * Windows it maps to the #define INVALID_SOCKET.)
256 * - The signature of bind_port has changed.
258 * Revision 1.48 2002/03/07 03:46:53 oes
259 * Fixed compiler warnings etc
261 * Revision 1.47 2002/02/20 23:15:13 jongfoster
262 * Parsing functions now handle out-of-memory gracefully by returning
265 * Revision 1.46 2002/01/17 21:03:47 jongfoster
266 * Moving all our URL and URL pattern parsing code to urlmatch.c.
268 * Revision 1.45 2002/01/09 14:33:03 oes
269 * Added support for localtime_r.
271 * Revision 1.44 2001/12/14 01:22:54 steudten
272 * Remove 'user:pass@' from 'proto://user:pass@host' for the
273 * new added header 'Host: ..'. (See Req ID 491818)
275 * Revision 1.43 2001/11/23 00:26:38 jongfoster
276 * Fixing two really stupid errors in my previous commit
278 * Revision 1.42 2001/11/22 21:59:30 jongfoster
279 * Adding code to handle +no-cookies-keep
281 * Revision 1.41 2001/11/05 23:43:05 steudten
282 * Add time+date to log files.
284 * Revision 1.40 2001/10/26 20:13:09 jongfoster
285 * ctype.h is needed in Windows, too.
287 * Revision 1.39 2001/10/26 17:40:04 oes
288 * Introduced get_header_value()
289 * Removed http->user_agent, csp->referrer and csp->accept_types
290 * Removed client_accept()
292 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
293 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
294 * threads to call select() simultaneously. So, it's time to do a real, live,
295 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
296 * (native). Both versions will work, but using __OS2__ offers multi-threading.
298 * Revision 1.37 2001/10/23 21:36:02 jongfoster
299 * Documenting sed()'s error behaviou (doc change only)
301 * Revision 1.36 2001/10/13 12:51:51 joergs
302 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
303 * force-load), instead crumble Host: and add it (again) in client_host_adder
304 * (in case we get a HTTP/1.0 request without Host: header and forward it to
305 * a HTTP/1.1 server/proxy).
307 * Revision 1.35 2001/10/09 22:39:21 jongfoster
308 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
311 * Revision 1.34 2001/10/07 18:50:55 oes
312 * Added server_content_encoding, renamed server_transfer_encoding
314 * Revision 1.33 2001/10/07 18:04:49 oes
315 * Changed server_http11 to server_http and its pattern to "HTTP".
316 * Additional functionality: it now saves the HTTP status into
317 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
319 * Revision 1.32 2001/10/07 15:43:28 oes
320 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
321 * client_te and client_accept_encoding_adder, triggered by the new
322 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
323 * changed to allow only identity and chunked, and the TE header is
324 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
326 * parse_http_request no longer does anything than parsing. The rewriting
327 * of http->cmd and version mangling are gone. It now also recognizes
328 * the put and delete methods and saves the url in http->url. Removed
331 * renamed content_type and content_length to have the server_ prefix
333 * server_content_type now only works if csp->content_type != CT_TABOO
335 * added server_transfer_encoding, which
336 * - Sets CT_TABOO to prohibit filtering if encoding compresses
337 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
338 * - Change from "chunked" to "identity" if body was chunked
339 * but has been de-chunked for filtering.
341 * added server_content_md5 which crunches any Content-MD5 headers
342 * if the body was modified.
344 * made server_http11 conditional on +downgrade action
346 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
348 * Revision 1.31 2001/10/05 14:25:02 oes
349 * Crumble Keep-Alive from Server
351 * Revision 1.30 2001/09/29 12:56:03 joergs
352 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
354 * Revision 1.29 2001/09/24 21:09:24 jongfoster
355 * Fixing 2 memory leaks that Guy spotted, where the paramater to
356 * enlist() was not being free()d.
358 * Revision 1.28 2001/09/22 16:32:28 jongfoster
359 * Removing unused #includes.
361 * Revision 1.27 2001/09/20 15:45:25 steudten
363 * add casting from size_t to int for printf()
364 * remove local variable shadow s2
366 * Revision 1.26 2001/09/16 17:05:14 jongfoster
367 * Removing unused #include showarg.h
369 * Revision 1.25 2001/09/16 13:21:27 jongfoster
370 * Changes to use new list functions.
372 * Revision 1.24 2001/09/13 23:05:50 jongfoster
373 * Changing the string paramater to the header parsers a "const".
375 * Revision 1.23 2001/09/12 18:08:19 steudten
377 * In parse_http_request() header rewriting miss the host value, so
378 * from http://www.mydomain.com the result was just " / " not
379 * http://www.mydomain.com/ in case we forward.
381 * Revision 1.22 2001/09/10 10:58:53 oes
382 * Silenced compiler warnings
384 * Revision 1.21 2001/07/31 14:46:00 oes
385 * - Persistant connections now suppressed
386 * - sed() no longer appends empty header to csp->headers
388 * Revision 1.20 2001/07/30 22:08:36 jongfoster
389 * Tidying up #defines:
390 * - All feature #defines are now of the form FEATURE_xxx
391 * - Permanently turned off WIN_GUI_EDIT
392 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
394 * Revision 1.19 2001/07/25 17:21:54 oes
395 * client_uagent now saves copy of User-Agent: header value
397 * Revision 1.18 2001/07/13 14:02:46 oes
398 * - Included fix to repair broken HTTP requests that
399 * don't contain a path, not even '/'.
400 * - Removed all #ifdef PCRS
401 * - content_type now always inspected and classified as
402 * text, gif or other.
403 * - formatting / comments
405 * Revision 1.17 2001/06/29 21:45:41 oes
406 * Indentation, CRLF->LF, Tab-> Space
408 * Revision 1.16 2001/06/29 13:32:42 oes
410 * - Adapted free_http_request
411 * - Removed logentry from cancelled commit
413 * Revision 1.15 2001/06/03 19:12:38 oes
414 * deleted const struct interceptors
416 * Revision 1.14 2001/06/01 18:49:17 jongfoster
417 * Replaced "list_share" with "list" - the tiny memory gain was not
418 * worth the extra complexity.
420 * Revision 1.13 2001/05/31 21:30:33 jongfoster
421 * Removed list code - it's now in list.[ch]
422 * Renamed "permission" to "action", and changed many features
423 * to use the actions file rather than the global config.
425 * Revision 1.12 2001/05/31 17:33:13 oes
429 * Revision 1.11 2001/05/29 20:11:19 joergs
430 * '/ * inside comment' warning removed.
432 * Revision 1.10 2001/05/29 09:50:24 jongfoster
433 * Unified blocklist/imagelist/permissionslist.
434 * File format is still under discussion, but the internal changes
437 * Also modified interceptor behaviour:
438 * - We now intercept all URLs beginning with one of the following
439 * prefixes (and *only* these prefixes):
441 * * http://ijbswa.sf.net/config/
442 * * http://ijbswa.sourceforge.net/config/
443 * - New interceptors "home page" - go to http://i.j.b/ to see it.
444 * - Internal changes so that intercepted and fast redirect pages
445 * are not replaced with an image.
446 * - Interceptors now have the option to send a binary page direct
447 * to the client. (i.e. ijb-send-banner uses this)
448 * - Implemented show-url-info interceptor. (Which is why I needed
449 * the above interceptors changes - a typical URL is
450 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
451 * The previous mechanism would not have intercepted that, and
452 * if it had been intercepted then it then it would have replaced
455 * Revision 1.9 2001/05/28 17:26:33 jongfoster
456 * Fixing segfault if last header was crunched.
457 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
458 * can use the cross-platform sprintf() instead.)
460 * Revision 1.8 2001/05/27 22:17:04 oes
462 * - re_process_buffer no longer writes the modified buffer
463 * to the client, which was very ugly. It now returns the
464 * buffer, which it is then written by chat.
466 * - content_length now adjusts the Content-Length: header
467 * for modified documents rather than crunch()ing it.
468 * (Length info in csp->content_length, which is 0 for
469 * unmodified documents)
471 * - For this to work, sed() is called twice when filtering.
473 * Revision 1.7 2001/05/27 13:19:06 oes
474 * Patched Joergs solution for the content-length in.
476 * Revision 1.6 2001/05/26 13:39:32 jongfoster
477 * Only crunches Content-Length header if applying RE filtering.
478 * Without this fix, Microsoft Windows Update wouldn't work.
480 * Revision 1.5 2001/05/26 00:28:36 jongfoster
481 * Automatic reloading of config file.
482 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
483 * Most of the global variables have been moved to a new
484 * struct configuration_spec, accessed through csp->config->globalname
485 * Most of the globals remaining are used by the Win32 GUI.
487 * Revision 1.4 2001/05/22 18:46:04 oes
489 * - Enabled filtering banners by size rather than URL
490 * by adding patterns that replace all standard banner
491 * sizes with the "Junkbuster" gif to the re_filterfile
493 * - Enabled filtering WebBugs by providing a pattern
494 * which kills all 1x1 images
496 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
497 * which is selected by the (nonstandard and therefore
498 * capital) letter 'U' in the option string.
499 * It causes the quantifiers to be ungreedy by default.
500 * Appending a ? turns back to greedy (!).
502 * - Added a new interceptor ijb-send-banner, which
503 * sends back the "Junkbuster" gif. Without imagelist or
504 * MSIE detection support, or if tinygif = 1, or the
505 * URL isn't recognized as an imageurl, a lame HTML
506 * explanation is sent instead.
508 * - Added new feature, which permits blocking remote
509 * script redirects and firing back a local redirect
511 * The feature is conditionally compiled, i.e. it
512 * can be disabled with --disable-fast-redirects,
513 * plus it must be activated by a "fast-redirects"
514 * line in the config file, has its own log level
515 * and of course wants to be displayed by show-proxy-args
516 * Note: Boy, all the #ifdefs in 1001 locations and
517 * all the fumbling with configure.in and acconfig.h
518 * were *way* more work than the feature itself :-(
520 * - Because a generic redirect template was needed for
521 * this, tinygif = 3 now uses the same.
523 * - Moved GIFs, and other static HTTP response templates
528 * - Removed some >400 CRs again (Jon, you really worked
531 * Revision 1.3 2001/05/20 01:21:20 jongfoster
532 * Version 2.9.4 checkin.
533 * - Merged popupfile and cookiefile, and added control over PCRS
534 * filtering, in new "permissionsfile".
535 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
536 * file error you now get a message box (in the Win32 GUI) rather
537 * than the program exiting with no explanation.
538 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
540 * - Removed tabs from "config"
541 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
542 * - Bumped up version number.
544 * Revision 1.2 2001/05/17 23:02:36 oes
545 * - Made referrer option accept 'L' as a substitute for '§'
547 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
548 * Initial import of version 2.9.3 source tree
551 *********************************************************************/
558 #include <sys/types.h>
567 #if !defined(_WIN32) && !defined(__OS2__)
573 #ifdef FEATURE_PTHREAD
575 /* jcc.h is for mutex semapores only */
576 #endif /* def FEATURE_PTHREAD */
582 #include "jbsockets.h"
583 #include "miscutil.h"
586 #ifndef HAVE_STRPTIME
587 #include "strptime.h"
590 const char parsers_h_rcs[] = PARSERS_H_VERSION;
592 /* Fix a problem with Solaris. There should be no effect on other
594 * Solaris's isspace() is a macro which uses it's argument directly
595 * as an array index. Therefore we need to make sure that high-bit
596 * characters generate +ve values, and ideally we also want to make
597 * the argument match the declared parameter type of "int".
599 * Why did they write a character function that can't take a simple
600 * "char" argument? Doh!
602 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
603 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
606 const struct parsers client_patterns[] = {
607 { "referer:", 8, client_referrer },
608 { "user-agent:", 11, client_uagent },
609 { "ua-", 3, client_ua },
610 { "from:", 5, client_from },
611 { "cookie:", 7, client_send_cookie },
612 { "x-forwarded-for:", 16, client_x_forwarded },
613 { "Accept-Encoding:", 16, client_accept_encoding },
614 { "TE:", 3, client_te },
615 { "Host:", 5, client_host },
616 { "if-modified-since:", 18, client_if_modified_since },
617 { "Keep-Alive:", 11, crumble },
618 { "connection:", 11, crumble },
619 { "proxy-connection:", 17, crumble },
620 { "max-forwards:", 13, client_max_forwards },
621 { "Accept-Language:", 16, client_accept_language },
622 { "if-none-match:", 14, client_if_none_match },
623 { "X-Filter:", 9, client_x_filter },
624 { "*", 0, crunch_client_header },
625 { "*", 0, filter_client_header },
629 const struct parsers server_patterns[] = {
630 { "HTTP", 4, server_http },
631 { "set-cookie:", 11, server_set_cookie },
632 { "connection:", 11, crumble },
633 { "Content-Type:", 13, server_content_type },
634 { "Content-Length:", 15, server_content_length },
635 { "Content-MD5:", 12, server_content_md5 },
636 { "Content-Encoding:", 17, server_content_encoding },
637 { "Transfer-Encoding:", 18, server_transfer_coding },
638 { "Keep-Alive:", 11, crumble },
639 { "content-disposition:", 20, server_content_disposition },
640 { "Last-Modified:", 14, server_last_modified },
641 { "*", 0, crunch_server_header },
642 { "*", 0, filter_server_header },
646 const struct parsers server_patterns_light[] = {
647 { "Content-Length:", 15, server_content_length },
648 { "Transfer-Encoding:", 18, server_transfer_coding },
652 const add_header_func_ptr add_client_headers[] = {
655 client_x_forwarded_adder,
657 /* Temporarily disabled: client_accept_encoding_adder, */
658 connection_close_adder,
663 const add_header_func_ptr add_server_headers[] = {
664 connection_close_adder,
668 /*********************************************************************
670 * Function : flush_socket
672 * Description : Write any pending "buffered" content.
675 * 1 : fd = file descriptor of the socket to read
676 * 2 : csp = Current client state (buffers, headers, etc...)
678 * Returns : On success, the number of bytes written are returned (zero
679 * indicates nothing was written). On error, -1 is returned,
680 * and errno is set appropriately. If count is zero and the
681 * file descriptor refers to a regular file, 0 will be
682 * returned without causing any other effect. For a special
683 * file, the results are not portable.
685 *********************************************************************/
686 int flush_socket(jb_socket fd, struct client_state *csp)
688 struct iob *iob = csp->iob;
689 int len = iob->eod - iob->cur;
696 if (write_socket(fd, iob->cur, (size_t)len))
700 iob->eod = iob->cur = iob->buf;
706 /*********************************************************************
708 * Function : add_to_iob
710 * Description : Add content to the buffered page, expanding the
711 * buffer if necessary.
714 * 1 : csp = Current client state (buffers, headers, etc...)
715 * 2 : buf = holds the content to be added to the page
716 * 3 : n = number of bytes to be added
718 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
719 * or buffer limit reached.
721 *********************************************************************/
722 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
724 struct iob *iob = csp->iob;
725 size_t used, offset, need, want;
728 if (n <= 0) return JB_ERR_OK;
730 used = (size_t)(iob->eod - iob->buf);
731 offset = (size_t)(iob->cur - iob->buf);
732 need = used + (size_t)n + 1;
735 * If the buffer can't hold the new data, extend it first.
736 * Use the next power of two if possible, else use the actual need.
738 if (need > csp->config->buffer_limit)
740 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
741 return JB_ERR_MEMORY;
744 if (need > iob->size)
746 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
748 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
752 else if (NULL != (p = (char *)realloc(iob->buf, need)))
758 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
759 return JB_ERR_MEMORY;
762 /* Update the iob pointers */
763 iob->cur = p + offset;
768 /* copy the new data into the iob buffer */
769 memcpy(iob->eod, buf, (size_t)n);
771 /* point to the end of the data */
774 /* null terminate == cheap insurance */
782 /*********************************************************************
784 * Function : get_header
786 * Description : This (odd) routine will parse the csp->iob
789 * 1 : csp = Current client state (buffers, headers, etc...)
791 * Returns : Any one of the following:
793 * 1) a pointer to a dynamically allocated string that contains a header line
794 * 2) NULL indicating that the end of the header was reached
795 * 3) "" indicating that the end of the iob was reached before finding
796 * a complete header line.
798 *********************************************************************/
799 char *get_header(struct client_state *csp)
805 if ((iob->cur == NULL)
806 || ((p = strchr(iob->cur, '\n')) == NULL))
808 return(""); /* couldn't find a complete header */
813 ret = strdup(iob->cur);
816 /* FIXME No way to handle error properly */
817 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
822 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
824 /* is this a blank line (i.e. the end of the header) ? */
836 /*********************************************************************
838 * Function : get_header_value
840 * Description : Get the value of a given header from a chained list
841 * of header lines or return NULL if no such header is
842 * present in the list.
845 * 1 : header_list = pointer to list
846 * 2 : header_name = string with name of header to look for.
847 * Trailing colon required, capitalization
850 * Returns : NULL if not found, else value of header
852 *********************************************************************/
853 char *get_header_value(const struct list *header_list, const char *header_name)
855 struct list_entry *cur_entry;
861 length = strlen(header_name);
863 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
867 if (!strncmpic(cur_entry->str, header_name, length))
870 * Found: return pointer to start of value
872 ret = (char *) (cur_entry->str + length);
873 while (*ret && ijb_isspace(*ret)) ret++;
886 /*********************************************************************
890 * Description : add, delete or modify lines in the HTTP header streams.
891 * On entry, it receives a linked list of headers space
892 * that was allocated dynamically (both the list nodes
893 * and the header contents).
895 * As a side effect it frees the space used by the original
899 * 1 : pats = list of patterns to match against headers
900 * 2 : more_headers = list of functions to add more
901 * headers (client or server)
902 * 3 : csp = Current client state (buffers, headers, etc...)
904 * Returns : Single pointer to a fully formed header, or NULL
905 * on out-of-memory error.
907 *********************************************************************/
908 char *sed(const struct parsers pats[],
909 const add_header_func_ptr more_headers[],
910 struct client_state *csp)
912 struct list_entry *p;
913 const struct parsers *v;
914 const add_header_func_ptr *f;
915 jb_err err = JB_ERR_OK;
919 * If filtering is enabled, sed is run twice,
920 * but most of the work needs to be done only once.
922 first_run = (more_headers != NULL ) ? 1 : 0;
924 if (first_run) /* Parse and print */
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 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
935 /* Does the current parser handle this header? */
936 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
938 err = v->parser(csp, (char **)&(p->str));
942 /* place any additional headers on the csp->headers list */
943 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
948 else /* Parse only */
951 * The second run is only needed if the body was modified
952 * and the content-lenght has changed.
954 if (strncmpic(csp->http->cmd, "HEAD", 4))
956 /*XXX: Code duplication*/
957 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
959 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
961 /* Header crunch()ed in previous run? -> ignore */
962 if (p->str == NULL) continue;
964 /* Does the current parser handle this header? */
965 if (strncmpic(p->str, v->str, v->len) == 0)
967 err = v->parser(csp, (char **)&(p->str));
974 if (err != JB_ERR_OK)
979 return list_to_text(csp->headers);
983 /* here begins the family of parser functions that reformat header lines */
985 /*********************************************************************
987 * Function : filter_server_header
989 * Description : Checks if server header filtering is enabled.
990 * If it is, filter_header is called to do the work.
993 * 1 : csp = Current client state (buffers, headers, etc...)
994 * 2 : header = On input, pointer to header to modify.
995 * On output, pointer to the modified header, or NULL
996 * to remove the header. This function frees the
997 * original string if necessary.
999 * Returns : JB_ERR_OK on success and always succeeds
1001 *********************************************************************/
1002 jb_err filter_server_header(struct client_state *csp, char **header)
1004 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1006 filter_header(csp, header);
1011 /*********************************************************************
1013 * Function : filter_client_header
1015 * Description : Checks if client header filtering is enabled.
1016 * If it is, filter_header is called to do the work.
1019 * 1 : csp = Current client state (buffers, headers, etc...)
1020 * 2 : header = On input, pointer to header to modify.
1021 * On output, pointer to the modified header, or NULL
1022 * to remove the header. This function frees the
1023 * original string if necessary.
1025 * Returns : JB_ERR_OK on success and always succeeds
1027 *********************************************************************/
1028 jb_err filter_client_header(struct client_state *csp, char **header)
1030 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1032 filter_header(csp, header);
1037 /*********************************************************************
1039 * Function : filter_header
1041 * Description : Executes all text substitutions from all applying
1042 * +filter actions on the header.
1043 * Most of the code was copied from pcrs_filter_response,
1044 * including the rather short variable names
1047 * 1 : csp = Current client state (buffers, headers, etc...)
1048 * 2 : header = On input, pointer to header to modify.
1049 * On output, pointer to the modified header, or NULL
1050 * to remove the header. This function frees the
1051 * original string if necessary.
1053 * Returns : JB_ERR_OK on success and always succeeds
1055 *********************************************************************/
1056 jb_err filter_header(struct client_state *csp, char **header)
1060 size_t size = strlen(*header);
1062 char *newheader = NULL;
1065 struct file_list *fl;
1066 struct re_filterfile_spec *b;
1067 struct list_entry *filtername;
1069 int i, found_filters = 0;
1072 * Need to check the set of re_filterfiles...
1074 for (i = 0; i < MAX_AF_FILES; i++)
1087 if (0 == found_filters)
1089 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1093 for (i = 0; i < MAX_AF_FILES; i++)
1096 if ((NULL == fl) || (NULL == fl->f))
1099 * For all applying +filter actions, look if a filter by that
1100 * name exists and if yes, execute its pcrs_joblist on the
1103 for (b = fl->f; b; b = b->next)
1105 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1106 filtername ; filtername = filtername->next)
1108 if (strcmp(b->name, filtername->str) == 0)
1110 int current_hits = 0;
1112 if ( NULL == b->joblist )
1114 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1118 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1119 *header, size, b->name);
1121 /* Apply all jobs from the joblist */
1122 for (job = b->joblist; NULL != job; job = job->next)
1124 matches = pcrs_execute(job, *header, size, &newheader, &size);
1127 current_hits += matches;
1128 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1130 *header = newheader;
1132 else if ( 0 == matches )
1134 /* Filter doesn't change header */
1140 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1141 *header, b->name, pcrs_strerror(matches));
1142 if( newheader != NULL)
1144 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1149 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1150 hits += current_hits;
1158 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1166 /*********************************************************************
1168 * Function : crumble
1170 * Description : This is called if a header matches a pattern to "crunch"
1173 * 1 : csp = Current client state (buffers, headers, etc...)
1174 * 2 : header = On input, pointer to header to modify.
1175 * On output, pointer to the modified header, or NULL
1176 * to remove the header. This function frees the
1177 * original string if necessary.
1179 * Returns : JB_ERR_OK on success, or
1180 * JB_ERR_MEMORY on out-of-memory error.
1182 *********************************************************************/
1183 jb_err crumble(struct client_state *csp, char **header)
1185 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1190 /*********************************************************************
1192 * Function : crunch_server_header
1194 * Description : Crunch server header if it matches a string supplied by the
1195 * user. Called from `sed'.
1198 * 1 : csp = Current client state (buffers, headers, etc...)
1199 * 2 : header = On input, pointer to header to modify.
1200 * On output, pointer to the modified header, or NULL
1201 * to remove the header. This function frees the
1202 * original string if necessary.
1204 * Returns : JB_ERR_OK on success and always succeeds
1206 *********************************************************************/
1207 jb_err crunch_server_header(struct client_state *csp, char **header)
1209 const char *crunch_pattern;
1210 /*Is there a header to crunch*/
1212 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1214 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1216 /*Is the current header the lucky one?*/
1217 if (strstr(*header, crunch_pattern))
1219 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1226 /*********************************************************************
1228 * Function : server_content_type
1230 * Description : Set the content-type for filterable types (text/.*,
1231 * javascript and image/gif) unless filtering has been
1232 * forbidden (CT_TABOO) while parsing earlier headers.
1233 * NOTE: Since text/plain is commonly used by web servers
1234 * for files whose correct type is unknown, we don't
1235 * set CT_TEXT for it.
1238 * 1 : csp = Current client state (buffers, headers, etc...)
1239 * 2 : header = On input, pointer to header to modify.
1240 * On output, pointer to the modified header, or NULL
1241 * to remove the header. This function frees the
1242 * original string if necessary.
1244 * Returns : JB_ERR_OK on success, or
1245 * JB_ERR_MEMORY on out-of-memory error.
1247 *********************************************************************/
1248 jb_err server_content_type(struct client_state *csp, char **header)
1252 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1254 if (csp->content_type != CT_TABOO)
1256 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1257 || strstr(*header, "xml")
1258 || strstr(*header, "application/x-javascript"))
1259 csp->content_type = CT_TEXT;
1260 else if (strstr(*header, " image/gif"))
1261 csp->content_type = CT_GIF;
1262 else if (strstr(*header, " image/jpeg"))
1263 csp->content_type = CT_JPEG;
1265 csp->content_type = 0;
1268 * Are we enabling text mode by force?
1270 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1273 * Do we really have to?
1275 if (csp->content_type == CT_TEXT)
1277 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1281 csp->content_type = CT_TEXT;
1282 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1286 * Are we messing with the content type?
1288 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1291 * Make sure the user doesn't accidently
1292 * change the content type of binary documents.
1294 if (csp->content_type == CT_TEXT)
1297 *header = strdup("Content-Type: ");
1298 string_append(header, newval);
1302 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1303 return JB_ERR_MEMORY;
1305 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1309 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1310 "Enable force-text-mode if you know what you're doing.", *header);
1317 /*********************************************************************
1319 * Function : server_transfer_coding
1321 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1322 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1323 * - Remove header if body was chunked but has been
1324 * de-chunked for filtering.
1327 * 1 : csp = Current client state (buffers, headers, etc...)
1328 * 2 : header = On input, pointer to header to modify.
1329 * On output, pointer to the modified header, or NULL
1330 * to remove the header. This function frees the
1331 * original string if necessary.
1333 * Returns : JB_ERR_OK on success, or
1334 * JB_ERR_MEMORY on out-of-memory error.
1336 *********************************************************************/
1337 jb_err server_transfer_coding(struct client_state *csp, char **header)
1340 * Turn off pcrs and gif filtering if body compressed
1342 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1344 csp->content_type = CT_TABOO;
1348 * Raise flag if body chunked
1350 if (strstr(*header, "chunked"))
1352 csp->flags |= CSP_FLAG_CHUNKED;
1355 * If the body was modified, it has been de-chunked first
1356 * and the header must be removed.
1358 if (csp->flags & CSP_FLAG_MODIFIED)
1360 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1369 /*********************************************************************
1371 * Function : server_content_encoding
1373 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1376 * 1 : csp = Current client state (buffers, headers, etc...)
1377 * 2 : header = On input, pointer to header to modify.
1378 * On output, pointer to the modified header, or NULL
1379 * to remove the header. This function frees the
1380 * original string if necessary.
1382 * Returns : JB_ERR_OK on success, or
1383 * JB_ERR_MEMORY on out-of-memory error.
1385 *********************************************************************/
1386 jb_err server_content_encoding(struct client_state *csp, char **header)
1389 * Turn off pcrs and gif filtering if body compressed
1391 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1393 csp->content_type = CT_TABOO;
1401 /*********************************************************************
1403 * Function : server_content_length
1405 * Description : Adjust Content-Length header if we modified
1409 * 1 : csp = Current client state (buffers, headers, etc...)
1410 * 2 : header = On input, pointer to header to modify.
1411 * On output, pointer to the modified header, or NULL
1412 * to remove the header. This function frees the
1413 * original string if necessary.
1415 * Returns : JB_ERR_OK on success, or
1416 * JB_ERR_MEMORY on out-of-memory error.
1418 *********************************************************************/
1419 jb_err server_content_length(struct client_state *csp, char **header)
1421 if (csp->content_length != 0) /* Content length could have been modified */
1424 * XXX: Shouldn't we check if csp->content_length
1425 * is different than the original value?
1428 *header = (char *) zalloc(100);
1429 if (*header == NULL)
1431 return JB_ERR_MEMORY;
1434 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1436 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1443 /*********************************************************************
1445 * Function : server_content_md5
1447 * Description : Crumble any Content-MD5 headers if the document was
1448 * modified. FIXME: Should we re-compute instead?
1451 * 1 : csp = Current client state (buffers, headers, etc...)
1452 * 2 : header = On input, pointer to header to modify.
1453 * On output, pointer to the modified header, or NULL
1454 * to remove the header. This function frees the
1455 * original string if necessary.
1457 * Returns : JB_ERR_OK on success, or
1458 * JB_ERR_MEMORY on out-of-memory error.
1460 *********************************************************************/
1461 jb_err server_content_md5(struct client_state *csp, char **header)
1463 if (csp->flags & CSP_FLAG_MODIFIED)
1465 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1472 /*********************************************************************
1474 * Function : server_content_disposition
1476 * Description : If enabled, blocks or modifies the "content-disposition" header.
1477 * Called from `sed'.
1480 * 1 : csp = Current client state (buffers, headers, etc...)
1481 * 2 : header = On input, pointer to header to modify.
1482 * On output, pointer to the modified header, or NULL
1483 * to remove the header. This function frees the
1484 * original string if necessary.
1486 * Returns : JB_ERR_OK on success, or
1487 * JB_ERR_MEMORY on out-of-memory error.
1489 *********************************************************************/
1490 jb_err server_content_disposition(struct client_state *csp, char **header)
1495 * Are we messing with the content-disposition header?
1497 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1503 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1505 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1508 * Blocking content-disposition header
1510 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1517 * Replacing content-disposition header
1520 *header = strdup("content-disposition: ");
1521 string_append(header, newval);
1523 if (*header == NULL)
1525 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1529 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1532 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1535 /*********************************************************************
1537 * Function : server_last_modified
1539 * Description : Changes Last-Modified header to the actual date
1540 * to help hide-if-modified-since.
1541 * Called from `sed'.
1544 * 1 : csp = Current client state (buffers, headers, etc...)
1545 * 2 : header = On input, pointer to header to modify.
1546 * On output, pointer to the modified header, or NULL
1547 * to remove the header. This function frees the
1548 * original string if necessary.
1550 * Returns : JB_ERR_OK on success, or
1551 * JB_ERR_MEMORY on out-of-memory error.
1553 *********************************************************************/
1554 jb_err server_last_modified(struct client_state *csp, char **header)
1557 char buf[BUFFER_SIZE];
1560 #ifdef HAVE_GMTIME_R
1563 struct tm *timeptr = NULL;
1564 time_t now, last_modified;
1566 long int days, hours, minutes, seconds;
1569 * Are we messing with the Last-Modified header?
1571 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1577 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1579 if (0 == strcmpic(newval, "block") )
1582 * Blocking Last-Modified header. Useless but why not.
1584 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1588 else if (0 == strcmpic(newval, "reset-to-request-time"))
1591 * Setting Last-Modified Header to now.
1593 get_http_time(0, buf);
1595 *header = strdup("Last-Modified: ");
1596 string_append(header, buf);
1598 if (*header == NULL)
1600 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1604 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1607 else if (0 == strcmpic(newval, "randomize"))
1609 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1611 #ifdef HAVE_GMTIME_R
1612 timeptr = gmtime_r(&now, &gmt);
1613 #elif FEATURE_PTHREAD
1614 pthread_mutex_lock(&gmtime_mutex);
1615 timeptr = gmtime(&now);
1616 pthread_mutex_unlock(&gmtime_mutex);
1618 timeptr = gmtime(&now);
1620 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1622 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1627 rtime = (long int)difftime(now, last_modified);
1630 rtime = pick_from_range(rtime);
1631 last_modified += rtime;
1632 #ifdef HAVE_GMTIME_R
1633 timeptr = gmtime_r(&last_modified, &gmt);
1634 #elif FEATURE_PTHREAD
1635 pthread_mutex_lock(&gmtime_mutex);
1636 timeptr = gmtime(&last_modified);
1637 pthread_mutex_unlock(&gmtime_mutex);
1639 timeptr = gmtime(&last_modified);
1641 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1643 *header = strdup("Last-Modified: ");
1644 string_append(header, newheader);
1646 if (*header == NULL)
1648 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1649 return JB_ERR_MEMORY;
1652 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1654 days = rtime / (3600 * 24);
1655 hours = rtime / 3600 % 24;
1656 minutes = rtime / 60 % 60;
1657 seconds = rtime % 60;
1659 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1660 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1661 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1666 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1674 /*********************************************************************
1676 * Function : client_accept_encoding
1678 * Description : Rewrite the client's Accept-Encoding header so that
1679 * if doesn't allow compression, if the action applies.
1680 * Note: For HTTP/1.0 the absence of the header is enough.
1683 * 1 : csp = Current client state (buffers, headers, etc...)
1684 * 2 : header = On input, pointer to header to modify.
1685 * On output, pointer to the modified header, or NULL
1686 * to remove the header. This function frees the
1687 * original string if necessary.
1689 * Returns : JB_ERR_OK on success, or
1690 * JB_ERR_MEMORY on out-of-memory error.
1692 *********************************************************************/
1693 jb_err client_accept_encoding(struct client_state *csp, char **header)
1695 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1697 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1701 /* Temporarily disable the correct behaviour to
1702 * work around a PHP bug.
1704 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1706 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1707 * if (*header == NULL)
1709 * return JB_ERR_MEMORY;
1720 /*********************************************************************
1722 * Function : client_te
1724 * Description : Rewrite the client's TE header so that
1725 * if doesn't allow compression, if the action applies.
1728 * 1 : csp = Current client state (buffers, headers, etc...)
1729 * 2 : header = On input, pointer to header to modify.
1730 * On output, pointer to the modified header, or NULL
1731 * to remove the header. This function frees the
1732 * original string if necessary.
1734 * Returns : JB_ERR_OK on success, or
1735 * JB_ERR_MEMORY on out-of-memory error.
1737 *********************************************************************/
1738 jb_err client_te(struct client_state *csp, char **header)
1740 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1743 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1749 /*********************************************************************
1751 * Function : client_referrer
1753 * Description : Handle the "referer" config setting properly.
1754 * Called from `sed'.
1757 * 1 : csp = Current client state (buffers, headers, etc...)
1758 * 2 : header = On input, pointer to header to modify.
1759 * On output, pointer to the modified header, or NULL
1760 * to remove the header. This function frees the
1761 * original string if necessary.
1763 * Returns : JB_ERR_OK on success, or
1764 * JB_ERR_MEMORY on out-of-memory error.
1766 *********************************************************************/
1767 jb_err client_referrer(struct client_state *csp, char **header)
1774 #ifdef FEATURE_FORCE_LOAD
1775 /* Since the referrer can include the prefix even
1776 * if the request itself is non-forced, we must
1777 * clean it unconditionally
1779 strclean(*header, FORCE_PREFIX);
1780 #endif /* def FEATURE_FORCE_LOAD */
1783 * Are we sending referer?
1785 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1790 newval = csp->action->string[ACTION_STRING_REFERER];
1792 if ((0 != strcmpic(newval, "conditional-block")))
1796 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1801 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1804 else if (0 == strcmpic(newval, "conditional-block"))
1807 * Block referer if host has changed.
1810 if (NULL == (host = strdup(csp->http->hostport)))
1813 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1814 return JB_ERR_MEMORY;
1816 if (NULL == (referer = strdup(*header)))
1820 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1821 return JB_ERR_MEMORY;
1823 hostlenght = strlen(host);
1824 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1826 /*Shorten referer to make sure the referer is blocked
1827 *if www.example.org/www.example.com-shall-see-the-referer/
1828 *links to www.example.com/
1830 referer[hostlenght+17] = '\0';
1832 if ( 0 == strstr(referer, host)) /*Host has changed*/
1834 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1839 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1845 else if (0 != strcmpic(newval, "forge"))
1848 * We have a specific (fixed) referer we want to send.
1850 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1852 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1854 *header = strdup("Referer: ");
1855 string_append(header, newval);
1856 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1858 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1863 * Forge a referer as http://[hostname:port of REQUEST]/
1864 * to fool stupid checks for in-site links
1867 *header = strdup("Referer: http://");
1868 string_append(header, csp->http->hostport);
1869 string_append(header, "/");
1870 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1872 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1876 /*********************************************************************
1878 * Function : client_accept_language
1880 * Description : Handle the "Accept-Language" config setting properly.
1881 * Called from `sed'.
1884 * 1 : csp = Current client state (buffers, headers, etc...)
1885 * 2 : header = On input, pointer to header to modify.
1886 * On output, pointer to the modified header, or NULL
1887 * to remove the header. This function frees the
1888 * original string if necessary.
1890 * Returns : JB_ERR_OK on success, or
1891 * JB_ERR_MEMORY on out-of-memory error.
1893 *********************************************************************/
1894 jb_err client_accept_language(struct client_state *csp, char **header)
1899 * Are we messing with the Accept-Language?
1901 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1903 /*I don't think so*/
1907 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1909 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1912 * Blocking Accept-Language header
1914 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1921 * Replacing Accept-Language header
1924 *header = strdup("Accept-Language: ");
1925 string_append(header, newval);
1927 if (*header == NULL)
1929 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1933 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1936 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1939 /*********************************************************************
1941 * Function : crunch_client_header
1943 * Description : Crunch client header if it matches a string supplied by the
1944 * user. Called from `sed'.
1947 * 1 : csp = Current client state (buffers, headers, etc...)
1948 * 2 : header = On input, pointer to header to modify.
1949 * On output, pointer to the modified header, or NULL
1950 * to remove the header. This function frees the
1951 * original string if necessary.
1953 * Returns : JB_ERR_OK on success and always succeeds
1955 *********************************************************************/
1956 jb_err crunch_client_header(struct client_state *csp, char **header)
1958 const char *crunch_pattern;
1959 /*Is there a header to crunch*/
1961 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1963 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1965 /*Is the current header the lucky one?*/
1966 if (strstr(*header, crunch_pattern))
1968 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1976 /*********************************************************************
1978 * Function : client_uagent
1980 * Description : Handle the "user-agent" config setting properly
1981 * and remember its original value to enable browser
1982 * bug workarounds. Called from `sed'.
1985 * 1 : csp = Current client state (buffers, headers, etc...)
1986 * 2 : header = On input, pointer to header to modify.
1987 * On output, pointer to the modified header, or NULL
1988 * to remove the header. This function frees the
1989 * original string if necessary.
1991 * Returns : JB_ERR_OK on success, or
1992 * JB_ERR_MEMORY on out-of-memory error.
1994 *********************************************************************/
1995 jb_err client_uagent(struct client_state *csp, char **header)
1999 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2004 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2011 *header = strdup("User-Agent: ");
2012 string_append(header, newval);
2014 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2016 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2019 /*********************************************************************
2021 * Function : client_ua
2023 * Description : Handle "ua-" headers properly. Called from `sed'.
2026 * 1 : csp = Current client state (buffers, headers, etc...)
2027 * 2 : header = On input, pointer to header to modify.
2028 * On output, pointer to the modified header, or NULL
2029 * to remove the header. This function frees the
2030 * original string if necessary.
2032 * Returns : JB_ERR_OK on success, or
2033 * JB_ERR_MEMORY on out-of-memory error.
2035 *********************************************************************/
2036 jb_err client_ua(struct client_state *csp, char **header)
2038 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2040 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2048 /*********************************************************************
2050 * Function : client_from
2052 * Description : Handle the "from" config setting properly.
2053 * Called from `sed'.
2056 * 1 : csp = Current client state (buffers, headers, etc...)
2057 * 2 : header = On input, pointer to header to modify.
2058 * On output, pointer to the modified header, or NULL
2059 * to remove the header. This function frees the
2060 * original string if necessary.
2062 * Returns : JB_ERR_OK on success, or
2063 * JB_ERR_MEMORY on out-of-memory error.
2065 *********************************************************************/
2066 jb_err client_from(struct client_state *csp, char **header)
2070 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2077 newval = csp->action->string[ACTION_STRING_FROM];
2080 * Are we blocking the e-mail address?
2082 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2084 log_error(LOG_LEVEL_HEADER, "crunched From!");
2088 log_error(LOG_LEVEL_HEADER, " modified");
2090 *header = strdup("From: ");
2091 string_append(header, newval);
2093 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2097 /*********************************************************************
2099 * Function : client_send_cookie
2101 * Description : Handle the "cookie" header properly. Called from `sed'.
2102 * If cookie is accepted, add it to the cookie_list,
2103 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2106 * 1 : csp = Current client state (buffers, headers, etc...)
2107 * 2 : header = On input, pointer to header to modify.
2108 * On output, pointer to the modified header, or NULL
2109 * to remove the header. This function frees the
2110 * original string if necessary.
2112 * Returns : JB_ERR_OK on success, or
2113 * JB_ERR_MEMORY on out-of-memory error.
2115 *********************************************************************/
2116 jb_err client_send_cookie(struct client_state *csp, char **header)
2118 jb_err result = JB_ERR_OK;
2120 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2122 /* strlen("cookie: ") == 8 */
2123 result = enlist(csp->cookie_list, *header + 8);
2127 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2131 * Always remove the cookie here. The cookie header
2132 * will be sent at the end of the header.
2140 /*********************************************************************
2142 * Function : client_x_forwarded
2144 * Description : Handle the "x-forwarded-for" config setting properly,
2145 * also used in the add_client_headers list. Called from `sed'.
2148 * 1 : csp = Current client state (buffers, headers, etc...)
2149 * 2 : header = On input, pointer to header to modify.
2150 * On output, pointer to the modified header, or NULL
2151 * to remove the header. This function frees the
2152 * original string if necessary.
2154 * Returns : JB_ERR_OK on success, or
2155 * JB_ERR_MEMORY on out-of-memory error.
2157 *********************************************************************/
2158 jb_err client_x_forwarded(struct client_state *csp, char **header)
2160 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2162 /* Save it so we can re-add it later */
2163 freez(csp->x_forwarded);
2164 csp->x_forwarded = *header;
2167 * Always set *header = NULL, since this information
2168 * will be sent at the end of the header.
2175 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2182 /*********************************************************************
2184 * Function : client_max_forwards
2186 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2187 * from the value of the Max-Forwards header field.
2190 * 1 : csp = Current client state (buffers, headers, etc...)
2191 * 2 : header = On input, pointer to header to modify.
2192 * On output, pointer to the modified header, or NULL
2193 * to remove the header. This function frees the
2194 * original string if necessary.
2196 * Returns : JB_ERR_OK on success, or
2197 * JB_ERR_MEMORY on out-of-memory error.
2199 *********************************************************************/
2200 jb_err client_max_forwards(struct client_state *csp, char **header)
2202 unsigned int max_forwards;
2204 if ((0 == strcmpic(csp->http->gpc, "trace"))
2205 || (0 == strcmpic(csp->http->gpc, "options")))
2207 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2209 if (max_forwards-- >= 1)
2211 sprintf(*header, "Max-Forwards: %u", max_forwards);
2212 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2216 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2225 /*********************************************************************
2227 * Function : client_host
2229 * Description : If the request URI did not contain host and
2230 * port information, parse and evaluate the Host
2233 * Also, kill ill-formed HOST: headers as sent by
2234 * Apple's iTunes software when used with a proxy.
2237 * 1 : csp = Current client state (buffers, headers, etc...)
2238 * 2 : header = On input, pointer to header to modify.
2239 * On output, pointer to the modified header, or NULL
2240 * to remove the header. This function frees the
2241 * original string if necessary.
2243 * Returns : JB_ERR_OK on success, or
2244 * JB_ERR_MEMORY on out-of-memory error.
2246 *********************************************************************/
2247 jb_err client_host(struct client_state *csp, char **header)
2252 * If the header field name is all upper-case, chances are that it's
2253 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2254 * not a problem -- they are regenerated later.
2256 if ((*header)[1] == 'O')
2258 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2263 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2264 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2267 if (NULL == (p = strdup((*header)+6)))
2269 return JB_ERR_MEMORY;
2272 if (NULL == (q = strdup(p)))
2275 return JB_ERR_MEMORY;
2278 freez(csp->http->hostport);
2279 csp->http->hostport = p;
2280 freez(csp->http->host);
2281 csp->http->host = q;
2282 q = strchr(csp->http->host, ':');
2285 /* Terminate hostname and evaluate port string */
2287 csp->http->port = atoi(q);
2291 csp->http->port = csp->http->ssl ? 443 : 80;
2294 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2295 csp->http->hostport, csp->http->host, csp->http->port);
2301 /*********************************************************************
2303 * Function : client_if_modified_since
2305 * Description : Remove or modify the If-Modified-Since header.
2308 * 1 : csp = Current client state (buffers, headers, etc...)
2309 * 2 : header = On input, pointer to header to modify.
2310 * On output, pointer to the modified header, or NULL
2311 * to remove the header. This function frees the
2312 * original string if necessary.
2314 * Returns : JB_ERR_OK on success, or
2315 * JB_ERR_MEMORY on out-of-memory error.
2317 *********************************************************************/
2318 jb_err client_if_modified_since(struct client_state *csp, char **header)
2321 #ifdef HAVE_GMTIME_R
2324 struct tm *timeptr = NULL;
2328 long int hours, minutes, seconds;
2332 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2335 * The client got an error message because of a temporary problem,
2336 * the problem is gone and the client now tries to revalidate our
2337 * error message on the real server. The revalidation would always
2338 * end with the transmission of the whole document and there is
2339 * no need to expose the bogus If-Modified-Since header.
2341 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2344 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2346 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2348 if ((0 == strcmpic(newval, "block")))
2350 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2353 else /* add random value */
2355 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2357 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2362 rtime = strtol(newval, &endptr, 0);
2365 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2366 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2373 rtime = pick_from_range(rtime);
2377 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2380 tm += rtime * (negative ? -1 : 1);
2381 #ifdef HAVE_GMTIME_R
2382 timeptr = gmtime_r(&tm, &gmt);
2383 #elif FEATURE_PTHREAD
2384 pthread_mutex_lock(&gmtime_mutex);
2385 timeptr = gmtime(&tm);
2386 pthread_mutex_unlock(&gmtime_mutex);
2388 timeptr = gmtime(&tm);
2390 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2393 *header = strdup("If-Modified-Since: ");
2394 string_append(header, newheader);
2396 if (*header == NULL)
2398 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2399 return JB_ERR_MEMORY;
2402 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2404 hours = rtime / 3600;
2405 minutes = rtime / 60 % 60;
2406 seconds = rtime % 60;
2408 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2409 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2410 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2419 /*********************************************************************
2421 * Function : client_if_none_match
2423 * Description : Remove the If-None-Match header.
2426 * 1 : csp = Current client state (buffers, headers, etc...)
2427 * 2 : header = On input, pointer to header to modify.
2428 * On output, pointer to the modified header, or NULL
2429 * to remove the header. This function frees the
2430 * original string if necessary.
2432 * Returns : JB_ERR_OK on success, or
2433 * JB_ERR_MEMORY on out-of-memory error.
2435 *********************************************************************/
2436 jb_err client_if_none_match(struct client_state *csp, char **header)
2438 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2440 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2447 /*********************************************************************
2449 * Function : client_x_filter
2451 * Description : Disables filtering if the client set "X-Filter: No".
2452 * Called from `sed'.
2455 * 1 : csp = Current client state (buffers, headers, etc...)
2456 * 2 : header = On input, pointer to header to modify.
2457 * On output, pointer to the modified header, or NULL
2458 * to remove the header. This function frees the
2459 * original string if necessary.
2461 * Returns : JB_ERR_OK on success
2463 *********************************************************************/
2464 jb_err client_x_filter(struct client_state *csp, char **header)
2466 if ( 0 == strcmpic(*header, "X-Filter: No"))
2468 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2470 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2474 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2476 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2480 csp->content_type = CT_TABOO;
2481 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2482 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2483 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2485 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2492 /* the following functions add headers directly to the header list */
2494 /*********************************************************************
2496 * Function : client_host_adder
2498 * Description : Adds the Host: header field if it is missing.
2499 * Called from `sed'.
2502 * 1 : csp = Current client state (buffers, headers, etc...)
2504 * Returns : JB_ERR_OK on success, or
2505 * JB_ERR_MEMORY on out-of-memory error.
2507 *********************************************************************/
2508 jb_err client_host_adder(struct client_state *csp)
2513 if ( !csp->http->hostport || !*(csp->http->hostport))
2519 * remove 'user:pass@' from 'proto://user:pass@host'
2521 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2527 p = csp->http->hostport;
2530 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2531 err = enlist_unique_header(csp->headers, "Host", p);
2537 /*********************************************************************
2539 * Function : client_cookie_adder
2541 * Description : Used in the add_client_headers list. Called from `sed'.
2544 * 1 : csp = Current client state (buffers, headers, etc...)
2546 * Returns : JB_ERR_OK on success, or
2547 * JB_ERR_MEMORY on out-of-memory error.
2549 *********************************************************************/
2550 jb_err client_cookie_adder(struct client_state *csp)
2552 struct list_entry *lst;
2554 struct list_entry *list1 = csp->cookie_list->first;
2555 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2556 int first_cookie = 1;
2559 if ((list1 == NULL) && (list2 == NULL))
2565 tmp = strdup("Cookie: ");
2567 for (lst = list1; lst ; lst = lst->next)
2575 string_append(&tmp, "; ");
2577 string_append(&tmp, lst->str);
2580 for (lst = list2; lst ; lst = lst->next)
2588 string_append(&tmp, "; ");
2590 string_join(&tmp, cookie_encode(lst->str));
2595 return JB_ERR_MEMORY;
2598 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2599 err = enlist(csp->headers, tmp);
2605 /*********************************************************************
2607 * Function : client_accept_encoding_adder
2609 * Description : Add an Accept-Encoding header to the client's request
2610 * that disables compression if the action applies, and
2611 * the header is not already there. Called from `sed'.
2612 * Note: For HTTP/1.0, the absence of the header is enough.
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2617 * Returns : JB_ERR_OK on success, or
2618 * JB_ERR_MEMORY on out-of-memory error.
2620 *********************************************************************/
2621 jb_err client_accept_encoding_adder(struct client_state *csp)
2623 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2624 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2626 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2633 /*********************************************************************
2635 * Function : client_xtra_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_xtra_adder(struct client_state *csp)
2648 struct list_entry *lst;
2651 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2652 lst ; lst = lst->next)
2654 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2655 err = enlist(csp->headers, lst->str);
2667 /*********************************************************************
2669 * Function : client_x_forwarded_adder
2671 * Description : Used in the add_client_headers list. Called from `sed'.
2674 * 1 : csp = Current client state (buffers, headers, etc...)
2676 * Returns : JB_ERR_OK on success, or
2677 * JB_ERR_MEMORY on out-of-memory error.
2679 *********************************************************************/
2680 jb_err client_x_forwarded_adder(struct client_state *csp)
2685 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2690 if (csp->x_forwarded)
2692 p = strdup(csp->x_forwarded);
2693 string_append(&p, ", ");
2697 p = strdup("X-Forwarded-For: ");
2699 string_append(&p, csp->ip_addr_str);
2703 return JB_ERR_MEMORY;
2706 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2707 err = enlist(csp->headers, p);
2714 /*********************************************************************
2716 * Function : connection_close_adder
2718 * Description : Adds a "Connection: close" header to csp->headers
2719 * as a temporary fix for the needed but missing HTTP/1.1
2720 * support. Called from `sed'.
2721 * FIXME: This whole function shouldn't be neccessary!
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * Returns : JB_ERR_OK on success, or
2727 * JB_ERR_MEMORY on out-of-memory error.
2729 *********************************************************************/
2730 jb_err connection_close_adder(struct client_state *csp)
2732 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2733 return enlist(csp->headers, "Connection: close");
2737 /*********************************************************************
2739 * Function : server_http
2741 * Description : - Save the HTTP Status into csp->http->status
2742 * - Set CT_TABOO to prevent filtering if the answer
2743 * is a partial range (HTTP status 206)
2744 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2748 * 1 : csp = Current client state (buffers, headers, etc...)
2749 * 2 : header = On input, pointer to header to modify.
2750 * On output, pointer to the modified header, or NULL
2751 * to remove the header. This function frees the
2752 * original string if necessary.
2754 * Returns : JB_ERR_OK on success, or
2755 * JB_ERR_MEMORY on out-of-memory error.
2757 *********************************************************************/
2758 jb_err server_http(struct client_state *csp, char **header)
2760 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2761 if (csp->http->status == 206)
2763 csp->content_type = CT_TABOO;
2766 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2769 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2776 /*********************************************************************
2778 * Function : server_set_cookie
2780 * Description : Handle the server "cookie" header properly.
2781 * Log cookie to the jar file. Then "crunch" it,
2782 * or accept it. Called from `sed'.
2785 * 1 : csp = Current client state (buffers, headers, etc...)
2786 * 2 : header = On input, pointer to header to modify.
2787 * On output, pointer to the modified header, or NULL
2788 * to remove the header. This function frees the
2789 * original string if necessary.
2791 * Returns : JB_ERR_OK on success, or
2792 * JB_ERR_MEMORY on out-of-memory error.
2794 *********************************************************************/
2795 jb_err server_set_cookie(struct client_state *csp, char **header)
2797 #ifdef FEATURE_COOKIE_JAR
2798 if (csp->config->jar)
2801 * Write timestamp into outbuf.
2803 * Complex because not all OSs have tm_gmtoff or
2804 * the %z field in strftime()
2806 char tempbuf[ BUFFER_SIZE ];
2810 #ifdef HAVE_LOCALTIME_R
2811 tm_now = *localtime_r(&now, &tm_now);
2812 #elif FEATURE_PTHREAD
2813 pthread_mutex_lock(&localtime_mutex);
2814 tm_now = *localtime (&now);
2815 pthread_mutex_unlock(&localtime_mutex);
2817 tm_now = *localtime (&now);
2819 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2821 /* strlen("set-cookie: ") = 12 */
2822 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2824 #endif /* def FEATURE_COOKIE_JAR */
2826 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2828 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2829 return crumble(csp, header);
2831 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2833 /* Flag whether or not to log a message */
2836 /* A variable to store the tag we're working on */
2839 /* Skip "Set-Cookie:" (11 characters) in header */
2840 cur_tag = *header + 11;
2842 /* skip whitespace between "Set-Cookie:" and value */
2843 while (*cur_tag && ijb_isspace(*cur_tag))
2848 /* Loop through each tag in the cookie */
2852 char *next_tag = strchr(cur_tag, ';');
2853 if (next_tag != NULL)
2855 /* Skip the ';' character itself */
2858 /* skip whitespace ";" and start of tag */
2859 while (*next_tag && ijb_isspace(*next_tag))
2866 /* "Next tag" is the end of the string */
2867 next_tag = cur_tag + strlen(cur_tag);
2870 /* Is this the "Expires" tag? */
2871 if (strncmpic(cur_tag, "expires=", 8) == 0)
2873 /* Delete the tag by copying the rest of the string over it.
2874 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2875 * since the behaviour of strcpy is undefined for overlapping
2878 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2880 /* That changed the header, need to issue a log message */
2883 /* Note that the next tag has now been moved to *cur_tag,
2884 * so we do not need to update the cur_tag pointer.
2889 /* Move on to next cookie tag */
2896 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2904 #ifdef FEATURE_FORCE_LOAD
2905 /*********************************************************************
2907 * Function : strclean
2909 * Description : In-Situ-Eliminate all occurances of substring in
2913 * 1 : string = string to clean
2914 * 2 : substring = substring to eliminate
2916 * Returns : Number of eliminations
2918 *********************************************************************/
2919 int strclean(const char *string, const char *substring)
2925 len = strlen(substring);
2927 while((pos = strstr(string, substring)) != NULL)
2934 while (*p++ != '\0');
2941 #endif /* def FEATURE_FORCE_LOAD */
2943 /*********************************************************************
2945 * Function : parse_header_time
2947 * Description : Transforms time inside a HTTP header into
2948 * the usual time format.
2951 * 1 : header = header to parse
2952 * 2 : tm = storage for the resulting time in seconds
2954 * Returns : Time struct containing the header time, or
2955 * NULL in case of a parsing problems.
2957 *********************************************************************/
2958 struct tm *parse_header_time(char *header, time_t *tm) {
2962 struct tm * timeptr;
2965 * Initializing gmt to prevent time zone offsets.
2967 * While this is only necessary on some platforms
2968 * (mingw32 for example), I don't know how to
2969 * detect these automatically and doing it everywhere
2973 #ifdef HAVE_LOCALTIME_R
2974 gmt = *localtime_r(tm, &gmt);
2975 #elif FEATURE_PTHREAD
2976 pthread_mutex_lock(&localtime_mutex);
2977 gmt = *localtime(tm);
2978 pthread_mutex_unlock(&localtime_mutex);
2980 gmt = *localtime(tm);
2983 /* Skipping header name */
2984 timestring = strstr(header, ": ");
2985 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
2998 /*********************************************************************
3000 * Function : get_destination_from_headers
3002 * Description : Parse the "Host:" header to get the request's destination.
3003 * Only needed if the client's request was forcefully
3004 * redirected into Privoxy.
3006 * Code mainly copied from client_host() which is currently
3007 * run too late for this purpose.
3010 * 1 : headers = List of headers (one of them hopefully being
3011 * the "Host:" header)
3012 * 2 : http = storage for the result (host, port and hostport).
3014 * Returns : JB_ERR_MEMORY in case of memory problems,
3015 * JB_ERR_PARSE if the host header couldn't be found,
3016 * JB_ERR_OK otherwise.
3018 *********************************************************************/
3019 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3025 host = get_header_value(headers, "Host:");
3029 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3030 return JB_ERR_PARSE;
3033 if (NULL == (p = strdup((host))))
3035 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3036 return JB_ERR_MEMORY;
3039 if (NULL == (q = strdup(p)))
3042 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3043 return JB_ERR_MEMORY;
3046 freez(http->hostport);
3050 q = strchr(http->host, ':');
3053 /* Terminate hostname and evaluate port string */
3055 http->port = atoi(q);
3059 http->port = http->ssl ? 443 : 80;
3062 /* Rebuild request URL */
3064 http->url = strdup(http->ssl ? "https://" : "http://");
3065 string_append(&http->url, http->hostport);
3066 string_append(&http->url, http->path);
3067 if (http->url == NULL)
3069 return JB_ERR_MEMORY;
3072 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",