1 const char parsers_rcs[] = "$Id: parsers.c,v 1.86 2007/01/30 13:05:26 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `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-2007 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.86 2007/01/30 13:05:26 fabiankeil
49 * - Let server_set_cookie() check the expiration date
50 * of cookies and don't touch the ones that are already
51 * expired. Fixes problems with low quality web applications
52 * as described in BR 932612.
54 * - Adjust comment in client_max_forwards to reality;
55 * remove invalid Max-Forwards headers.
57 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
58 * Stop filter_header() from unintentionally removing
59 * empty header lines that were enlisted by the continue
62 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
63 * - Repeat the request URL before logging any headers.
64 * Makes reading the log easier in case of simultaneous requests.
65 * - If there are more than one Content-Type headers in one request,
66 * use the first one and remove the others.
67 * - Remove "newval" variable in server_content_type().
68 * It's only used once.
70 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
71 * Correct a cast, check inflateEnd() exit code
72 * to see if we have to, replace sprintf calls
75 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
76 * Integrate a modified version of Wil Mahan's
77 * zlib patch (PR #895531).
79 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
80 * Skip empty filter files in filter_header()
81 * but don't ignore the ones that come afterwards.
82 * Fixes BR 1619208, this time for real.
84 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
85 * Reverted parts of my last commit
86 * to keep error handling working.
88 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
89 * Fixed gcc43 conversion warnings.
91 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
92 * Bringing back the "useless" localtime() call
93 * I removed in revision 1.67. On some platforms
94 * it's necessary to prevent time zone offsets.
96 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
97 * Rebuild request URL in get_destination_from_headers()
98 * to make sure redirect{pcrs command} works as expected
99 * for intercepted requests.
101 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
102 * Added get_destination_from_headers().
104 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
105 * Make pthread mutex locking more generic. Instead of
106 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
107 * and use mutex locking unless there is an _r function
108 * available. Better safe than sorry.
110 * Fixes "./configure --disable-pthread" and should result
111 * in less threading-related problems on pthread-using platforms,
112 * but it still doesn't fix BR#1122404.
114 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
115 * The special header "X-Filter: No" now disables
116 * header filtering as well.
118 * Revision 1.73 2006/09/23 13:26:38 roro
119 * Replace TABs by spaces in source code.
121 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
122 * Don't print a log message every time filter_headers is
123 * entered or left. It only creates noise without any real
126 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
127 * Fix +hide-if-modified-since{-n}.
129 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
130 * Have hide-if-modified-since interpret the random
131 * range value as minutes instead of hours. Allows
132 * more fine-grained configuration.
134 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
135 * Always have parse_header_time return a pointer
136 * that actual makes sense, even though we currently
137 * only need it to detect problems.
139 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
140 * Added config option enable-remote-http-toggle
141 * to specify if Privoxy should recognize special
142 * headers (currently only X-Filter) to change its
143 * behaviour. Disabled by default.
145 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
146 * After filtering de-chunked instances, remove
147 * "Transfer-Encoding" header entirely instead of changing
148 * it to "Transfer-Encoding: identity", which is invalid.
149 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
151 * Don't use localtime in parse_header_time. An empty time struct
152 * is good enough, it gets overwritten by strptime anyway.
154 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
155 * Use gmtime_r if available, fallback to gmtime with mutex
156 * protection for MacOSX and use vanilla gmtime for the rest.
158 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
159 * Changed client_referrer to use the right type (size_t) for
160 * hostlenght and to shorten the temporary referrer string with
161 * '\0' instead of adding a useless line break.
163 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
164 * - Back to timegm() using GnuPG's replacement if necessary.
165 * Using mktime() and localtime() could add a on hour offset if
166 * the randomize factor was big enough to lead to a summer/wintertime
169 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
171 * - Moved randomization code into pick_from_range().
173 * - Changed parse_header_time definition.
174 * time_t isn't guaranteed to be signed and
175 * if it isn't, -1 isn't available as error code.
176 * Changed some variable types in client_if_modified_since()
177 * because of the same reason.
179 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
180 * OS/2 compilation compatibility fixups
182 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
183 * Changed include from strptime.c to strptime.h
185 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
186 * Split filter-headers{} into filter-client-headers{}
187 * and filter-server-headers{}.
188 * Added parse_header_time() to share some code.
189 * Replaced timegm() with mktime().
191 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
192 * Windows service integration
194 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
195 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
197 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
198 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
199 * with what was really the latest development (the v_3_0_branch branch)
201 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
202 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
204 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
205 * Add the ability to check jpeg images for invalid
206 * lengths of comment blocks. Defensive strategy
207 * against the exploit:
208 * Microsoft Security Bulletin MS04-028
209 * Buffer Overrun in JPEG Processing (GDI+) Could
210 * Allow Code Execution (833987)
211 * Enabled with +inspect-jpegs in actions files.
213 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
214 * Excluded text/plain objects from filtering. This fixes a
215 * couple of client-crashing, download corruption and
216 * Privoxy performance issues, whose root cause lies in
217 * web servers labelling content of unknown type as text/plain.
219 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
220 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
222 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
223 * Completing the previous change
225 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
226 * Added temporary workaround for bug in PHP < 4.2.3
228 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
229 * 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.
231 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
232 * Fix typo: supressed -> suppressed
234 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
235 * Improved cookie logging
237 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
238 * Added basic support for OPTIONS and TRACE HTTP methods:
239 * - New parser function client_max_forwards which decrements
240 * the Max-Forwards HTTP header field of OPTIONS and TRACE
241 * requests by one before forwarding
242 * - New parser function client_host which extracts the host
243 * and port information from the HTTP header field if the
244 * request URI was not absolute
245 * - Don't crumble and re-add the Host: header, but only generate
246 * and append if missing
248 * Revision 1.56 2002/05/12 15:34:22 jongfoster
249 * Fixing typo in a comment
251 * Revision 1.55 2002/05/08 16:01:07 oes
252 * Optimized add_to_iob:
253 * - Use realloc instead of malloc(), memcpy(), free()
254 * - Expand to powers of two if possible, to get
255 * O(log n) reallocs instead of O(n).
256 * - Moved check for buffer limit here from chat
257 * - Report failure via returncode
259 * Revision 1.54 2002/04/02 15:03:16 oes
260 * Tiny code cosmetics
262 * Revision 1.53 2002/03/26 22:29:55 swa
263 * we have a new homepage!
265 * Revision 1.52 2002/03/24 13:25:43 swa
266 * name change related issues
268 * Revision 1.51 2002/03/13 00:27:05 jongfoster
271 * Revision 1.50 2002/03/12 01:45:35 oes
272 * More verbose logging
274 * Revision 1.49 2002/03/09 20:03:52 jongfoster
275 * - Making various functions return int rather than size_t.
276 * (Undoing a recent change). Since size_t is unsigned on
277 * Windows, functions like read_socket that return -1 on
278 * error cannot return a size_t.
280 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
281 * crashes, and also frequently caused JB to jump to 100%
282 * CPU and stay there. (Because it thought it had just
283 * read ((unsigned)-1) == 4Gb of data...)
285 * - The signature of write_socket has changed, it now simply
286 * returns success=0/failure=nonzero.
288 * - Trying to get rid of a few warnings --with-debug on
289 * Windows, I've introduced a new type "jb_socket". This is
290 * used for the socket file descriptors. On Windows, this
291 * is SOCKET (a typedef for unsigned). Everywhere else, it's
292 * an int. The error value can't be -1 any more, so it's
293 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
294 * Windows it maps to the #define INVALID_SOCKET.)
296 * - The signature of bind_port has changed.
298 * Revision 1.48 2002/03/07 03:46:53 oes
299 * Fixed compiler warnings etc
301 * Revision 1.47 2002/02/20 23:15:13 jongfoster
302 * Parsing functions now handle out-of-memory gracefully by returning
305 * Revision 1.46 2002/01/17 21:03:47 jongfoster
306 * Moving all our URL and URL pattern parsing code to urlmatch.c.
308 * Revision 1.45 2002/01/09 14:33:03 oes
309 * Added support for localtime_r.
311 * Revision 1.44 2001/12/14 01:22:54 steudten
312 * Remove 'user:pass@' from 'proto://user:pass@host' for the
313 * new added header 'Host: ..'. (See Req ID 491818)
315 * Revision 1.43 2001/11/23 00:26:38 jongfoster
316 * Fixing two really stupid errors in my previous commit
318 * Revision 1.42 2001/11/22 21:59:30 jongfoster
319 * Adding code to handle +no-cookies-keep
321 * Revision 1.41 2001/11/05 23:43:05 steudten
322 * Add time+date to log files.
324 * Revision 1.40 2001/10/26 20:13:09 jongfoster
325 * ctype.h is needed in Windows, too.
327 * Revision 1.39 2001/10/26 17:40:04 oes
328 * Introduced get_header_value()
329 * Removed http->user_agent, csp->referrer and csp->accept_types
330 * Removed client_accept()
332 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
333 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
334 * threads to call select() simultaneously. So, it's time to do a real, live,
335 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
336 * (native). Both versions will work, but using __OS2__ offers multi-threading.
338 * Revision 1.37 2001/10/23 21:36:02 jongfoster
339 * Documenting sed()'s error behaviou (doc change only)
341 * Revision 1.36 2001/10/13 12:51:51 joergs
342 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
343 * force-load), instead crumble Host: and add it (again) in client_host_adder
344 * (in case we get a HTTP/1.0 request without Host: header and forward it to
345 * a HTTP/1.1 server/proxy).
347 * Revision 1.35 2001/10/09 22:39:21 jongfoster
348 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
351 * Revision 1.34 2001/10/07 18:50:55 oes
352 * Added server_content_encoding, renamed server_transfer_encoding
354 * Revision 1.33 2001/10/07 18:04:49 oes
355 * Changed server_http11 to server_http and its pattern to "HTTP".
356 * Additional functionality: it now saves the HTTP status into
357 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
359 * Revision 1.32 2001/10/07 15:43:28 oes
360 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
361 * client_te and client_accept_encoding_adder, triggered by the new
362 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
363 * changed to allow only identity and chunked, and the TE header is
364 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
366 * parse_http_request no longer does anything than parsing. The rewriting
367 * of http->cmd and version mangling are gone. It now also recognizes
368 * the put and delete methods and saves the url in http->url. Removed
371 * renamed content_type and content_length to have the server_ prefix
373 * server_content_type now only works if csp->content_type != CT_TABOO
375 * added server_transfer_encoding, which
376 * - Sets CT_TABOO to prohibit filtering if encoding compresses
377 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
378 * - Change from "chunked" to "identity" if body was chunked
379 * but has been de-chunked for filtering.
381 * added server_content_md5 which crunches any Content-MD5 headers
382 * if the body was modified.
384 * made server_http11 conditional on +downgrade action
386 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
388 * Revision 1.31 2001/10/05 14:25:02 oes
389 * Crumble Keep-Alive from Server
391 * Revision 1.30 2001/09/29 12:56:03 joergs
392 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
394 * Revision 1.29 2001/09/24 21:09:24 jongfoster
395 * Fixing 2 memory leaks that Guy spotted, where the paramater to
396 * enlist() was not being free()d.
398 * Revision 1.28 2001/09/22 16:32:28 jongfoster
399 * Removing unused #includes.
401 * Revision 1.27 2001/09/20 15:45:25 steudten
403 * add casting from size_t to int for printf()
404 * remove local variable shadow s2
406 * Revision 1.26 2001/09/16 17:05:14 jongfoster
407 * Removing unused #include showarg.h
409 * Revision 1.25 2001/09/16 13:21:27 jongfoster
410 * Changes to use new list functions.
412 * Revision 1.24 2001/09/13 23:05:50 jongfoster
413 * Changing the string paramater to the header parsers a "const".
415 * Revision 1.23 2001/09/12 18:08:19 steudten
417 * In parse_http_request() header rewriting miss the host value, so
418 * from http://www.mydomain.com the result was just " / " not
419 * http://www.mydomain.com/ in case we forward.
421 * Revision 1.22 2001/09/10 10:58:53 oes
422 * Silenced compiler warnings
424 * Revision 1.21 2001/07/31 14:46:00 oes
425 * - Persistant connections now suppressed
426 * - sed() no longer appends empty header to csp->headers
428 * Revision 1.20 2001/07/30 22:08:36 jongfoster
429 * Tidying up #defines:
430 * - All feature #defines are now of the form FEATURE_xxx
431 * - Permanently turned off WIN_GUI_EDIT
432 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
434 * Revision 1.19 2001/07/25 17:21:54 oes
435 * client_uagent now saves copy of User-Agent: header value
437 * Revision 1.18 2001/07/13 14:02:46 oes
438 * - Included fix to repair broken HTTP requests that
439 * don't contain a path, not even '/'.
440 * - Removed all #ifdef PCRS
441 * - content_type now always inspected and classified as
442 * text, gif or other.
443 * - formatting / comments
445 * Revision 1.17 2001/06/29 21:45:41 oes
446 * Indentation, CRLF->LF, Tab-> Space
448 * Revision 1.16 2001/06/29 13:32:42 oes
450 * - Adapted free_http_request
451 * - Removed logentry from cancelled commit
453 * Revision 1.15 2001/06/03 19:12:38 oes
454 * deleted const struct interceptors
456 * Revision 1.14 2001/06/01 18:49:17 jongfoster
457 * Replaced "list_share" with "list" - the tiny memory gain was not
458 * worth the extra complexity.
460 * Revision 1.13 2001/05/31 21:30:33 jongfoster
461 * Removed list code - it's now in list.[ch]
462 * Renamed "permission" to "action", and changed many features
463 * to use the actions file rather than the global config.
465 * Revision 1.12 2001/05/31 17:33:13 oes
469 * Revision 1.11 2001/05/29 20:11:19 joergs
470 * '/ * inside comment' warning removed.
472 * Revision 1.10 2001/05/29 09:50:24 jongfoster
473 * Unified blocklist/imagelist/permissionslist.
474 * File format is still under discussion, but the internal changes
477 * Also modified interceptor behaviour:
478 * - We now intercept all URLs beginning with one of the following
479 * prefixes (and *only* these prefixes):
481 * * http://ijbswa.sf.net/config/
482 * * http://ijbswa.sourceforge.net/config/
483 * - New interceptors "home page" - go to http://i.j.b/ to see it.
484 * - Internal changes so that intercepted and fast redirect pages
485 * are not replaced with an image.
486 * - Interceptors now have the option to send a binary page direct
487 * to the client. (i.e. ijb-send-banner uses this)
488 * - Implemented show-url-info interceptor. (Which is why I needed
489 * the above interceptors changes - a typical URL is
490 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
491 * The previous mechanism would not have intercepted that, and
492 * if it had been intercepted then it then it would have replaced
495 * Revision 1.9 2001/05/28 17:26:33 jongfoster
496 * Fixing segfault if last header was crunched.
497 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
498 * can use the cross-platform sprintf() instead.)
500 * Revision 1.8 2001/05/27 22:17:04 oes
502 * - re_process_buffer no longer writes the modified buffer
503 * to the client, which was very ugly. It now returns the
504 * buffer, which it is then written by chat.
506 * - content_length now adjusts the Content-Length: header
507 * for modified documents rather than crunch()ing it.
508 * (Length info in csp->content_length, which is 0 for
509 * unmodified documents)
511 * - For this to work, sed() is called twice when filtering.
513 * Revision 1.7 2001/05/27 13:19:06 oes
514 * Patched Joergs solution for the content-length in.
516 * Revision 1.6 2001/05/26 13:39:32 jongfoster
517 * Only crunches Content-Length header if applying RE filtering.
518 * Without this fix, Microsoft Windows Update wouldn't work.
520 * Revision 1.5 2001/05/26 00:28:36 jongfoster
521 * Automatic reloading of config file.
522 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
523 * Most of the global variables have been moved to a new
524 * struct configuration_spec, accessed through csp->config->globalname
525 * Most of the globals remaining are used by the Win32 GUI.
527 * Revision 1.4 2001/05/22 18:46:04 oes
529 * - Enabled filtering banners by size rather than URL
530 * by adding patterns that replace all standard banner
531 * sizes with the "Junkbuster" gif to the re_filterfile
533 * - Enabled filtering WebBugs by providing a pattern
534 * which kills all 1x1 images
536 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
537 * which is selected by the (nonstandard and therefore
538 * capital) letter 'U' in the option string.
539 * It causes the quantifiers to be ungreedy by default.
540 * Appending a ? turns back to greedy (!).
542 * - Added a new interceptor ijb-send-banner, which
543 * sends back the "Junkbuster" gif. Without imagelist or
544 * MSIE detection support, or if tinygif = 1, or the
545 * URL isn't recognized as an imageurl, a lame HTML
546 * explanation is sent instead.
548 * - Added new feature, which permits blocking remote
549 * script redirects and firing back a local redirect
551 * The feature is conditionally compiled, i.e. it
552 * can be disabled with --disable-fast-redirects,
553 * plus it must be activated by a "fast-redirects"
554 * line in the config file, has its own log level
555 * and of course wants to be displayed by show-proxy-args
556 * Note: Boy, all the #ifdefs in 1001 locations and
557 * all the fumbling with configure.in and acconfig.h
558 * were *way* more work than the feature itself :-(
560 * - Because a generic redirect template was needed for
561 * this, tinygif = 3 now uses the same.
563 * - Moved GIFs, and other static HTTP response templates
568 * - Removed some >400 CRs again (Jon, you really worked
571 * Revision 1.3 2001/05/20 01:21:20 jongfoster
572 * Version 2.9.4 checkin.
573 * - Merged popupfile and cookiefile, and added control over PCRS
574 * filtering, in new "permissionsfile".
575 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
576 * file error you now get a message box (in the Win32 GUI) rather
577 * than the program exiting with no explanation.
578 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
580 * - Removed tabs from "config"
581 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
582 * - Bumped up version number.
584 * Revision 1.2 2001/05/17 23:02:36 oes
585 * - Made referrer option accept 'L' as a substitute for '§'
587 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
588 * Initial import of version 2.9.3 source tree
591 *********************************************************************/
598 #include <sys/types.h>
611 #if !defined(_WIN32) && !defined(__OS2__)
617 #ifdef FEATURE_PTHREAD
619 /* jcc.h is for mutex semapores only */
620 #endif /* def FEATURE_PTHREAD */
626 #include "jbsockets.h"
627 #include "miscutil.h"
630 #ifndef HAVE_STRPTIME
631 #include "strptime.h"
634 const char parsers_h_rcs[] = PARSERS_H_VERSION;
636 /* Fix a problem with Solaris. There should be no effect on other
638 * Solaris's isspace() is a macro which uses it's argument directly
639 * as an array index. Therefore we need to make sure that high-bit
640 * characters generate +ve values, and ideally we also want to make
641 * the argument match the declared parameter type of "int".
643 * Why did they write a character function that can't take a simple
644 * "char" argument? Doh!
646 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
647 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
650 const struct parsers client_patterns[] = {
651 { "referer:", 8, client_referrer },
652 { "user-agent:", 11, client_uagent },
653 { "ua-", 3, client_ua },
654 { "from:", 5, client_from },
655 { "cookie:", 7, client_send_cookie },
656 { "x-forwarded-for:", 16, client_x_forwarded },
657 { "Accept-Encoding:", 16, client_accept_encoding },
658 { "TE:", 3, client_te },
659 { "Host:", 5, client_host },
660 { "if-modified-since:", 18, client_if_modified_since },
661 { "Keep-Alive:", 11, crumble },
662 { "connection:", 11, crumble },
663 { "proxy-connection:", 17, crumble },
664 { "max-forwards:", 13, client_max_forwards },
665 { "Accept-Language:", 16, client_accept_language },
666 { "if-none-match:", 14, client_if_none_match },
667 { "X-Filter:", 9, client_x_filter },
668 { "*", 0, crunch_client_header },
669 { "*", 0, filter_client_header },
673 const struct parsers server_patterns[] = {
674 { "HTTP", 4, server_http },
675 { "set-cookie:", 11, server_set_cookie },
676 { "connection:", 11, crumble },
677 { "Content-Type:", 13, server_content_type },
678 { "Content-Length:", 15, server_content_length },
679 { "Content-MD5:", 12, server_content_md5 },
680 { "Content-Encoding:", 17, server_content_encoding },
681 { "Transfer-Encoding:", 18, server_transfer_coding },
682 { "Keep-Alive:", 11, crumble },
683 { "content-disposition:", 20, server_content_disposition },
684 { "Last-Modified:", 14, server_last_modified },
685 { "*", 0, crunch_server_header },
686 { "*", 0, filter_server_header },
690 const struct parsers server_patterns_light[] = {
691 { "Content-Length:", 15, server_content_length },
692 { "Transfer-Encoding:", 18, server_transfer_coding },
694 { "Content-Encoding:", 17, server_content_encoding },
695 #endif /* def FEATURE_ZLIB */
699 const add_header_func_ptr add_client_headers[] = {
702 client_x_forwarded_adder,
704 /* Temporarily disabled: client_accept_encoding_adder, */
705 connection_close_adder,
710 const add_header_func_ptr add_server_headers[] = {
711 connection_close_adder,
715 /*********************************************************************
717 * Function : flush_socket
719 * Description : Write any pending "buffered" content.
722 * 1 : fd = file descriptor of the socket to read
723 * 2 : csp = Current client state (buffers, headers, etc...)
725 * Returns : On success, the number of bytes written are returned (zero
726 * indicates nothing was written). On error, -1 is returned,
727 * and errno is set appropriately. If count is zero and the
728 * file descriptor refers to a regular file, 0 will be
729 * returned without causing any other effect. For a special
730 * file, the results are not portable.
732 *********************************************************************/
733 int flush_socket(jb_socket fd, struct client_state *csp)
735 struct iob *iob = csp->iob;
736 int len = iob->eod - iob->cur;
743 if (write_socket(fd, iob->cur, (size_t)len))
747 iob->eod = iob->cur = iob->buf;
753 /*********************************************************************
755 * Function : add_to_iob
757 * Description : Add content to the buffered page, expanding the
758 * buffer if necessary.
761 * 1 : csp = Current client state (buffers, headers, etc...)
762 * 2 : buf = holds the content to be added to the page
763 * 3 : n = number of bytes to be added
765 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
766 * or buffer limit reached.
768 *********************************************************************/
769 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
771 struct iob *iob = csp->iob;
772 size_t used, offset, need, want;
775 if (n <= 0) return JB_ERR_OK;
777 used = (size_t)(iob->eod - iob->buf);
778 offset = (size_t)(iob->cur - iob->buf);
779 need = used + (size_t)n + 1;
782 * If the buffer can't hold the new data, extend it first.
783 * Use the next power of two if possible, else use the actual need.
785 if (need > csp->config->buffer_limit)
787 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
788 return JB_ERR_MEMORY;
791 if (need > iob->size)
793 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
795 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
799 else if (NULL != (p = (char *)realloc(iob->buf, need)))
805 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
806 return JB_ERR_MEMORY;
809 /* Update the iob pointers */
810 iob->cur = p + offset;
815 /* copy the new data into the iob buffer */
816 memcpy(iob->eod, buf, (size_t)n);
818 /* point to the end of the data */
821 /* null terminate == cheap insurance */
830 /*********************************************************************
832 * Function : decompress_iob
834 * Description : Decompress buffered page, expanding the
835 * buffer as necessary. csp->iob->cur
836 * should point to the the beginning of the
837 * compressed data block.
840 * 1 : csp = Current client state (buffers, headers, etc...)
842 * Returns : JB_ERR_OK on success,
843 * JB_ERR_MEMORY if out-of-memory limit reached, and
844 * JB_ERR_COMPRESS if error decompressing buffer.
846 *********************************************************************/
847 jb_err decompress_iob(struct client_state *csp)
849 char *buf; /* new, uncompressed buffer */
850 size_t bufsize; /* allocated size of the new buffer */
851 size_t skip_size; /* Number of bytes at the beginning of the iob
852 that we should NOT decompress. */
853 int status; /* return status of the inflate() call */
854 z_stream zstr; /* used by calls to zlib */
856 bufsize = csp->iob->size;
857 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
862 * This is to protect the parsing of gzipped data,
863 * but it should(?) be valid for deflated data also.
865 log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
866 return JB_ERR_COMPRESS;
869 if (csp->content_type & CT_GZIP)
872 * Our task is slightly complicated by the facts that data
873 * compressed by gzip does not include a zlib header, and
874 * that there is no easily accessible interface in zlib to
875 * handle a gzip header. We strip off the gzip header by
876 * hand, and later inform zlib not to expect a header.
880 * Strip off the gzip header. Please see RFC 1952 for more
881 * explanation of the appropriate fields.
883 if ((*csp->iob->cur++ != (char)0x1f)
884 || (*csp->iob->cur++ != (char)0x8b)
885 || (*csp->iob->cur++ != Z_DEFLATED))
887 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
888 return JB_ERR_COMPRESS;
892 int flags = *csp->iob->cur++;
894 * XXX: These magic numbers should be replaced
895 * with macros to give a better idea what they do.
899 /* The gzip header has reserved bits set; bail out. */
900 log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
901 return JB_ERR_COMPRESS;
905 /* Skip extra fields if necessary. */
909 * Skip a given number of bytes, specified
910 * as a 16-bit little-endian value.
912 csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
915 /* Skip the filename if necessary. */
918 /* A null-terminated string follows. */
919 while (*csp->iob->cur++);
922 /* Skip the comment if necessary. */
925 while (*csp->iob->cur++);
928 /* Skip the CRC if necessary. */
935 else if (csp->content_type & CT_DEFLATE)
938 * XXX: The debug level should be lowered
939 * before the next stable release.
941 log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *csp->iob->cur);
943 * In theory (that is, according to RFC 1950), deflate-compressed
944 * data should begin with a two-byte zlib header and have an
945 * adler32 checksum at the end. It seems that in practice only
946 * the raw compressed data is sent. Note that this means that
947 * we are not RFC 1950-compliant here, but the advantage is that
948 * this actually works. :)
950 * We add a dummy null byte to tell zlib where the data ends,
951 * and later inform it not to expect a header.
953 * Fortunately, add_to_iob() has thoughtfully null-terminated
954 * the buffer; we can just increment the end pointer to include
961 log_error (LOG_LEVEL_ERROR,
962 "Unable to determine compression format for decompression");
963 return JB_ERR_COMPRESS;
966 /* Set up the fields required by zlib. */
967 zstr.next_in = (Bytef *)csp->iob->cur;
968 zstr.avail_in = (unsigned int)(csp->iob->eod - csp->iob->cur);
969 zstr.zalloc = Z_NULL;
971 zstr.opaque = Z_NULL;
974 * Passing -MAX_WBITS to inflateInit2 tells the library
975 * that there is no zlib header.
977 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
979 log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
980 return JB_ERR_COMPRESS;
984 * Next, we allocate new storage for the inflated data.
985 * We don't modify the existing iob yet, so in case there
986 * is error in decompression we can recover gracefully.
988 buf = zalloc (bufsize);
991 log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
992 return JB_ERR_MEMORY;
995 assert(bufsize >= skip_size);
996 memcpy(buf, csp->iob->buf, skip_size);
997 zstr.avail_out = bufsize - skip_size;
998 zstr.next_out = (Bytef *)buf + skip_size;
1000 /* Try to decompress the whole stream in one shot. */
1001 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1003 /* We need to allocate more memory for the output buffer. */
1005 char *tmpbuf; /* used for realloc'ing the buffer */
1006 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1009 * If zlib wants more data then there's a problem, because
1010 * the complete compressed file should have been buffered.
1012 if (0 == zstr.avail_in)
1014 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1015 return JB_ERR_COMPRESS;
1019 * If we tried the limit and still didn't have enough
1020 * memory, just give up.
1022 if (bufsize == csp->config->buffer_limit)
1024 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1025 return JB_ERR_MEMORY;
1028 /* Try doubling the buffer size each time. */
1031 /* Don't exceed the buffer limit. */
1032 if (bufsize > csp->config->buffer_limit)
1034 bufsize = csp->config->buffer_limit;
1037 /* Try to allocate the new buffer. */
1038 tmpbuf = realloc(buf, bufsize);
1041 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1043 return JB_ERR_MEMORY;
1047 char *oldnext_out = (char *)zstr.next_out;
1050 * Update the fields for inflate() to use the new
1051 * buffer, which may be in a location different from
1054 zstr.avail_out += bufsize - oldbufsize;
1055 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1058 * Compare with an uglier method of calculating these values
1059 * that doesn't require the extra oldbufsize variable.
1061 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1062 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1063 assert(zstr.avail_out > 0);
1069 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1071 log_error(LOG_LEVEL_ERROR,
1072 "Inconsistent stream state after decompression: %s", zstr.msg);
1074 * XXX: Intentionally no return.
1076 * According to zlib.h, Z_STREAM_ERROR is returned
1077 * "if the stream state was inconsistent".
1079 * I assume in this case inflate()'s status
1080 * would also be something different than Z_STREAM_END
1081 * so this check should be redundant, but lets see.
1085 if (status != Z_STREAM_END)
1087 /* We failed to decompress the stream. */
1088 log_error(LOG_LEVEL_ERROR,
1089 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1090 return JB_ERR_COMPRESS;
1094 * Finally, we can actually update the iob, since the
1095 * decompression was successful. First, free the old
1098 freez(csp->iob->buf);
1100 /* Now, update the iob to use the new buffer. */
1101 csp->iob->buf = buf;
1102 csp->iob->cur = csp->iob->buf + skip_size;
1103 csp->iob->eod = (char *)zstr.next_out;
1104 csp->iob->size = bufsize;
1107 * Make sure the new uncompressed iob obeys some minimal
1108 * consistency conditions.
1110 if ((csp->iob->buf < csp->iob->cur)
1111 && (csp->iob->cur <= csp->iob->eod)
1112 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1114 char t = csp->iob->cur[100];
1115 csp->iob->cur[100] = '\0';
1117 * XXX: The debug level should be lowered
1118 * before the next stable release.
1120 log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1121 csp->iob->cur[100] = t;
1126 /* It seems that zlib did something weird. */
1127 log_error(LOG_LEVEL_ERROR,
1128 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1129 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1130 csp->iob->eod, csp->iob->buf + csp->iob->size);
1131 return JB_ERR_COMPRESS;
1135 #endif /* defined(FEATURE_ZLIB) */
1138 /*********************************************************************
1140 * Function : get_header
1142 * Description : This (odd) routine will parse the csp->iob
1145 * 1 : csp = Current client state (buffers, headers, etc...)
1147 * Returns : Any one of the following:
1149 * 1) a pointer to a dynamically allocated string that contains a header line
1150 * 2) NULL indicating that the end of the header was reached
1151 * 3) "" indicating that the end of the iob was reached before finding
1152 * a complete header line.
1154 *********************************************************************/
1155 char *get_header(struct client_state *csp)
1161 if ((iob->cur == NULL)
1162 || ((p = strchr(iob->cur, '\n')) == NULL))
1164 return(""); /* couldn't find a complete header */
1169 ret = strdup(iob->cur);
1172 /* FIXME No way to handle error properly */
1173 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1178 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1180 /* is this a blank line (i.e. the end of the header) ? */
1192 /*********************************************************************
1194 * Function : get_header_value
1196 * Description : Get the value of a given header from a chained list
1197 * of header lines or return NULL if no such header is
1198 * present in the list.
1201 * 1 : header_list = pointer to list
1202 * 2 : header_name = string with name of header to look for.
1203 * Trailing colon required, capitalization
1206 * Returns : NULL if not found, else value of header
1208 *********************************************************************/
1209 char *get_header_value(const struct list *header_list, const char *header_name)
1211 struct list_entry *cur_entry;
1215 assert(header_list);
1216 assert(header_name);
1217 length = strlen(header_name);
1219 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1223 if (!strncmpic(cur_entry->str, header_name, length))
1226 * Found: return pointer to start of value
1228 ret = (char *) (cur_entry->str + length);
1229 while (*ret && ijb_isspace(*ret)) ret++;
1242 /*********************************************************************
1246 * Description : add, delete or modify lines in the HTTP header streams.
1247 * On entry, it receives a linked list of headers space
1248 * that was allocated dynamically (both the list nodes
1249 * and the header contents).
1251 * As a side effect it frees the space used by the original
1255 * 1 : pats = list of patterns to match against headers
1256 * 2 : more_headers = list of functions to add more
1257 * headers (client or server)
1258 * 3 : csp = Current client state (buffers, headers, etc...)
1260 * Returns : Single pointer to a fully formed header, or NULL
1261 * on out-of-memory error.
1263 *********************************************************************/
1264 char *sed(const struct parsers pats[],
1265 const add_header_func_ptr more_headers[],
1266 struct client_state *csp)
1268 struct list_entry *p;
1269 const struct parsers *v;
1270 const add_header_func_ptr *f;
1271 jb_err err = JB_ERR_OK;
1275 * If filtering is enabled, sed is run twice,
1276 * but most of the work needs to be done only once.
1278 first_run = (more_headers != NULL ) ? 1 : 0;
1280 if (first_run) /* Parse and print */
1282 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1283 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1285 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1287 /* Header crunch()ed in previous run? -> ignore */
1288 if (p->str == NULL) continue;
1290 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1292 /* Does the current parser handle this header? */
1293 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1295 err = v->parser(csp, (char **)&(p->str));
1299 /* place any additional headers on the csp->headers list */
1300 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1305 else /* Parse only */
1308 * The second run is only needed if the body was modified
1309 * and the content-lenght has changed.
1311 if (strncmpic(csp->http->cmd, "HEAD", 4))
1313 /*XXX: Code duplication */
1314 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1316 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1318 /* Header crunch()ed in previous run? -> ignore */
1319 if (p->str == NULL) continue;
1321 /* Does the current parser handle this header? */
1322 if (strncmpic(p->str, v->str, v->len) == 0)
1324 err = v->parser(csp, (char **)&(p->str));
1331 if (err != JB_ERR_OK)
1336 return list_to_text(csp->headers);
1340 /* here begins the family of parser functions that reformat header lines */
1342 /*********************************************************************
1344 * Function : filter_server_header
1346 * Description : Checks if server header filtering is enabled.
1347 * If it is, filter_header is called to do the work.
1350 * 1 : csp = Current client state (buffers, headers, etc...)
1351 * 2 : header = On input, pointer to header to modify.
1352 * On output, pointer to the modified header, or NULL
1353 * to remove the header. This function frees the
1354 * original string if necessary.
1356 * Returns : JB_ERR_OK on success and always succeeds
1358 *********************************************************************/
1359 jb_err filter_server_header(struct client_state *csp, char **header)
1361 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1363 filter_header(csp, header);
1368 /*********************************************************************
1370 * Function : filter_client_header
1372 * Description : Checks if client header filtering is enabled.
1373 * If it is, filter_header is called to do the work.
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 and always succeeds
1384 *********************************************************************/
1385 jb_err filter_client_header(struct client_state *csp, char **header)
1387 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1389 filter_header(csp, header);
1394 /*********************************************************************
1396 * Function : filter_header
1398 * Description : Executes all text substitutions from all applying
1399 * +filter actions on the header.
1400 * Most of the code was copied from pcrs_filter_response,
1401 * including the rather short variable names
1404 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * 2 : header = On input, pointer to header to modify.
1406 * On output, pointer to the modified header, or NULL
1407 * to remove the header. This function frees the
1408 * original string if necessary.
1410 * Returns : JB_ERR_OK on success and always succeeds
1412 *********************************************************************/
1413 jb_err filter_header(struct client_state *csp, char **header)
1417 size_t size = strlen(*header);
1419 char *newheader = NULL;
1422 struct file_list *fl;
1423 struct re_filterfile_spec *b;
1424 struct list_entry *filtername;
1426 int i, found_filters = 0;
1429 * Need to check the set of re_filterfiles...
1431 for (i = 0; i < MAX_AF_FILES; i++)
1444 if (0 == found_filters)
1446 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1450 for (i = 0; i < MAX_AF_FILES; i++)
1453 if ((NULL == fl) || (NULL == fl->f))
1456 * Either there are no filter files
1457 * left, or this filter file just
1458 * contains no valid filters.
1460 * Continue to be sure we don't miss
1461 * valid filter files that are chained
1462 * after empty or invalid ones.
1467 * For all applying +filter actions, look if a filter by that
1468 * name exists and if yes, execute its pcrs_joblist on the
1471 for (b = fl->f; b; b = b->next)
1473 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1474 filtername ; filtername = filtername->next)
1476 if (strcmp(b->name, filtername->str) == 0)
1478 int current_hits = 0;
1480 if ( NULL == b->joblist )
1482 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1486 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1487 *header, size, b->name);
1489 /* Apply all jobs from the joblist */
1490 for (job = b->joblist; NULL != job; job = job->next)
1492 matches = pcrs_execute(job, *header, size, &newheader, &size);
1495 current_hits += matches;
1496 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1498 *header = newheader;
1500 else if ( 0 == matches )
1502 /* Filter doesn't change header */
1508 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1509 *header, b->name, pcrs_strerror(matches));
1510 if( newheader != NULL)
1512 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1517 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1518 hits += current_hits;
1525 * Additionally checking for hits is important because if
1526 * the continue hack is triggered, server headers can
1527 * arrive empty to separate multiple heads from each other.
1529 if ((0 == size) && hits)
1531 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1539 /*********************************************************************
1541 * Function : crumble
1543 * Description : This is called if a header matches a pattern to "crunch"
1546 * 1 : csp = Current client state (buffers, headers, etc...)
1547 * 2 : header = On input, pointer to header to modify.
1548 * On output, pointer to the modified header, or NULL
1549 * to remove the header. This function frees the
1550 * original string if necessary.
1552 * Returns : JB_ERR_OK on success, or
1553 * JB_ERR_MEMORY on out-of-memory error.
1555 *********************************************************************/
1556 jb_err crumble(struct client_state *csp, char **header)
1558 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1563 /*********************************************************************
1565 * Function : crunch_server_header
1567 * Description : Crunch server header if it matches a string supplied by the
1568 * user. Called from `sed'.
1571 * 1 : csp = Current client state (buffers, headers, etc...)
1572 * 2 : header = On input, pointer to header to modify.
1573 * On output, pointer to the modified header, or NULL
1574 * to remove the header. This function frees the
1575 * original string if necessary.
1577 * Returns : JB_ERR_OK on success and always succeeds
1579 *********************************************************************/
1580 jb_err crunch_server_header(struct client_state *csp, char **header)
1582 const char *crunch_pattern;
1583 /*Is there a header to crunch*/
1585 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1587 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1589 /*Is the current header the lucky one?*/
1590 if (strstr(*header, crunch_pattern))
1592 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1601 /*********************************************************************
1603 * Function : server_content_type
1605 * Description : Set the content-type for filterable types (text/.*,
1606 * .*xml.*, javascript and image/gif) unless filtering has been
1607 * forbidden (CT_TABOO) while parsing earlier headers.
1608 * NOTE: Since text/plain is commonly used by web servers
1609 * for files whose correct type is unknown, we don't
1610 * set CT_TEXT for it.
1613 * 1 : csp = Current client state (buffers, headers, etc...)
1614 * 2 : header = On input, pointer to header to modify.
1615 * On output, pointer to the modified header, or NULL
1616 * to remove the header. This function frees the
1617 * original string if necessary.
1619 * Returns : JB_ERR_OK on success, or
1620 * JB_ERR_MEMORY on out-of-memory error.
1622 *********************************************************************/
1623 jb_err server_content_type(struct client_state *csp, char **header)
1625 /* Remove header if it isn't the first Content-Type header */
1626 if(csp->content_type && (csp->content_type != CT_TABOO))
1629 * Another, slightly slower, way to see if
1630 * we already parsed another Content-Type header.
1632 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1634 log_error(LOG_LEVEL_ERROR,
1635 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1642 if (!(csp->content_type & CT_TABOO))
1644 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1645 || strstr(*header, "xml")
1646 || strstr(*header, "application/x-javascript"))
1648 csp->content_type |= CT_TEXT;
1650 else if (strstr(*header, " image/gif"))
1652 csp->content_type |= CT_GIF;
1654 else if (strstr(*header, " image/jpeg"))
1656 csp->content_type |= CT_JPEG;
1660 csp->content_type = 0;
1664 * Are we enabling text mode by force?
1666 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1669 * Do we really have to?
1671 if (csp->content_type & CT_TEXT)
1673 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1677 csp->content_type |= CT_TEXT;
1678 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1682 * Are we messing with the content type?
1684 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1687 * Make sure the user doesn't accidently
1688 * change the content type of binary documents.
1690 if (csp->content_type & CT_TEXT)
1693 *header = strdup("Content-Type: ");
1694 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1698 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1699 return JB_ERR_MEMORY;
1701 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1705 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1706 "Enable force-text-mode if you know what you're doing.", *header);
1713 /*********************************************************************
1715 * Function : server_transfer_coding
1717 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1718 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1719 * - Remove header if body was chunked but has been
1720 * de-chunked for filtering.
1723 * 1 : csp = Current client state (buffers, headers, etc...)
1724 * 2 : header = On input, pointer to header to modify.
1725 * On output, pointer to the modified header, or NULL
1726 * to remove the header. This function frees the
1727 * original string if necessary.
1729 * Returns : JB_ERR_OK on success, or
1730 * JB_ERR_MEMORY on out-of-memory error.
1732 *********************************************************************/
1733 jb_err server_transfer_coding(struct client_state *csp, char **header)
1736 * Turn off pcrs and gif filtering if body compressed
1738 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1742 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1744 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1745 csp->http->cmd, *header);
1746 #endif /* def FEATURE_ZLIB */
1747 csp->content_type = CT_TABOO;
1751 * Raise flag if body chunked
1753 if (strstr(*header, "chunked"))
1755 csp->flags |= CSP_FLAG_CHUNKED;
1758 * If the body was modified, it has been de-chunked first
1759 * and the header must be removed.
1761 * FIXME: If there is more than one transfer encoding,
1762 * only the "chunked" part should be removed here.
1764 if (csp->flags & CSP_FLAG_MODIFIED)
1766 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1775 /*********************************************************************
1777 * Function : server_content_encoding
1779 * Description : This function is run twice for each request,
1780 * unless FEATURE_ZLIB and filtering are disabled.
1782 * The first run is used to check if the content
1783 * is compressed, if FEATURE_ZLIB is disabled
1784 * filtering is then disabled as well, if FEATURE_ZLIB
1785 * is enabled the content is marked for decompression.
1787 * The second run is used to remove the Content-Encoding
1788 * header if the decompression was successful.
1791 * 1 : csp = Current client state (buffers, headers, etc...)
1792 * 2 : header = On input, pointer to header to modify.
1793 * On output, pointer to the modified header, or NULL
1794 * to remove the header. This function frees the
1795 * original string if necessary.
1797 * Returns : JB_ERR_OK on success, or
1798 * JB_ERR_MEMORY on out-of-memory error.
1800 *********************************************************************/
1801 jb_err server_content_encoding(struct client_state *csp, char **header)
1804 /* XXX: Why would we modify the content if it was taboo? */
1805 if ((csp->flags & CSP_FLAG_MODIFIED) && !(csp->content_type & CT_TABOO))
1808 * We successfully decompressed the content,
1809 * and have to clean the header now, so the
1810 * client no longer expects compressed data..
1812 * XXX: There is a difference between cleaning
1813 * and removing it completely.
1815 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1818 else if (strstr(*header, "gzip"))
1820 /* Mark for gzip decompression */
1821 csp->content_type |= CT_GZIP;
1823 else if (strstr(*header, "deflate"))
1825 /* Mark for zlib decompression */
1826 csp->content_type |= CT_DEFLATE;
1828 else if (strstr(*header, "compress"))
1831 * We can't decompress this; therefore we can't filter
1834 csp->content_type |= CT_TABOO;
1836 #else /* !defined(FEATURE_ZLIB) */
1837 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1840 * Body is compressed, turn off pcrs and gif filtering.
1842 csp->content_type |= CT_TABOO;
1844 #endif /* !defined(FEATURE_ZLIB) */
1851 /*********************************************************************
1853 * Function : server_content_length
1855 * Description : Adjust Content-Length header if we modified
1859 * 1 : csp = Current client state (buffers, headers, etc...)
1860 * 2 : header = On input, pointer to header to modify.
1861 * On output, pointer to the modified header, or NULL
1862 * to remove the header. This function frees the
1863 * original string if necessary.
1865 * Returns : JB_ERR_OK on success, or
1866 * JB_ERR_MEMORY on out-of-memory error.
1868 *********************************************************************/
1869 jb_err server_content_length(struct client_state *csp, char **header)
1871 const size_t max_header_length = 80;
1872 if (csp->content_length != 0) /* Content length could have been modified */
1875 * XXX: Shouldn't we check if csp->content_length
1876 * is different than the original value?
1879 *header = (char *) zalloc(max_header_length);
1880 if (*header == NULL)
1882 return JB_ERR_MEMORY;
1885 snprintf(*header, max_header_length, "Content-Length: %d",
1886 (int)csp->content_length);
1887 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
1888 (int)csp->content_length);
1895 /*********************************************************************
1897 * Function : server_content_md5
1899 * Description : Crumble any Content-MD5 headers if the document was
1900 * modified. FIXME: Should we re-compute instead?
1903 * 1 : csp = Current client state (buffers, headers, etc...)
1904 * 2 : header = On input, pointer to header to modify.
1905 * On output, pointer to the modified header, or NULL
1906 * to remove the header. This function frees the
1907 * original string if necessary.
1909 * Returns : JB_ERR_OK on success, or
1910 * JB_ERR_MEMORY on out-of-memory error.
1912 *********************************************************************/
1913 jb_err server_content_md5(struct client_state *csp, char **header)
1915 if (csp->flags & CSP_FLAG_MODIFIED)
1917 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1924 /*********************************************************************
1926 * Function : server_content_disposition
1928 * Description : If enabled, blocks or modifies the "content-disposition" header.
1929 * Called from `sed'.
1932 * 1 : csp = Current client state (buffers, headers, etc...)
1933 * 2 : header = On input, pointer to header to modify.
1934 * On output, pointer to the modified header, or NULL
1935 * to remove the header. This function frees the
1936 * original string if necessary.
1938 * Returns : JB_ERR_OK on success, or
1939 * JB_ERR_MEMORY on out-of-memory error.
1941 *********************************************************************/
1942 jb_err server_content_disposition(struct client_state *csp, char **header)
1947 * Are we messing with the content-disposition header?
1949 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1955 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1957 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1960 * Blocking content-disposition header
1962 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1969 * Replacing content-disposition header
1972 *header = strdup("content-disposition: ");
1973 string_append(header, newval);
1975 if (*header == NULL)
1977 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1981 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1984 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1987 /*********************************************************************
1989 * Function : server_last_modified
1991 * Description : Changes Last-Modified header to the actual date
1992 * to help hide-if-modified-since.
1993 * Called from `sed'.
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * 2 : header = On input, pointer to header to modify.
1998 * On output, pointer to the modified header, or NULL
1999 * to remove the header. This function frees the
2000 * original string if necessary.
2002 * Returns : JB_ERR_OK on success, or
2003 * JB_ERR_MEMORY on out-of-memory error.
2005 *********************************************************************/
2006 jb_err server_last_modified(struct client_state *csp, char **header)
2009 char buf[BUFFER_SIZE];
2012 #ifdef HAVE_GMTIME_R
2015 struct tm *timeptr = NULL;
2016 time_t now, last_modified;
2018 long int days, hours, minutes, seconds;
2021 * Are we messing with the Last-Modified header?
2023 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2029 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2031 if (0 == strcmpic(newval, "block") )
2034 * Blocking Last-Modified header. Useless but why not.
2036 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2040 else if (0 == strcmpic(newval, "reset-to-request-time"))
2043 * Setting Last-Modified Header to now.
2045 get_http_time(0, buf);
2047 *header = strdup("Last-Modified: ");
2048 string_append(header, buf);
2050 if (*header == NULL)
2052 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2056 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2059 else if (0 == strcmpic(newval, "randomize"))
2061 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2063 #ifdef HAVE_GMTIME_R
2064 timeptr = gmtime_r(&now, &gmt);
2065 #elif FEATURE_PTHREAD
2066 pthread_mutex_lock(&gmtime_mutex);
2067 timeptr = gmtime(&now);
2068 pthread_mutex_unlock(&gmtime_mutex);
2070 timeptr = gmtime(&now);
2072 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2074 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2079 rtime = (long int)difftime(now, last_modified);
2082 rtime = pick_from_range(rtime);
2083 last_modified += rtime;
2084 #ifdef HAVE_GMTIME_R
2085 timeptr = gmtime_r(&last_modified, &gmt);
2086 #elif FEATURE_PTHREAD
2087 pthread_mutex_lock(&gmtime_mutex);
2088 timeptr = gmtime(&last_modified);
2089 pthread_mutex_unlock(&gmtime_mutex);
2091 timeptr = gmtime(&last_modified);
2093 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2095 *header = strdup("Last-Modified: ");
2096 string_append(header, newheader);
2098 if (*header == NULL)
2100 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2101 return JB_ERR_MEMORY;
2104 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2106 days = rtime / (3600 * 24);
2107 hours = rtime / 3600 % 24;
2108 minutes = rtime / 60 % 60;
2109 seconds = rtime % 60;
2111 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2112 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2113 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2118 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2126 /*********************************************************************
2128 * Function : client_accept_encoding
2130 * Description : Rewrite the client's Accept-Encoding header so that
2131 * if doesn't allow compression, if the action applies.
2132 * Note: For HTTP/1.0 the absence of the header is enough.
2135 * 1 : csp = Current client state (buffers, headers, etc...)
2136 * 2 : header = On input, pointer to header to modify.
2137 * On output, pointer to the modified header, or NULL
2138 * to remove the header. This function frees the
2139 * original string if necessary.
2141 * Returns : JB_ERR_OK on success, or
2142 * JB_ERR_MEMORY on out-of-memory error.
2144 *********************************************************************/
2145 jb_err client_accept_encoding(struct client_state *csp, char **header)
2147 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2149 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2153 /* Temporarily disable the correct behaviour to
2154 * work around a PHP bug.
2156 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2158 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2159 * if (*header == NULL)
2161 * return JB_ERR_MEMORY;
2172 /*********************************************************************
2174 * Function : client_te
2176 * Description : Rewrite the client's TE header so that
2177 * if doesn't allow compression, if the action applies.
2180 * 1 : csp = Current client state (buffers, headers, etc...)
2181 * 2 : header = On input, pointer to header to modify.
2182 * On output, pointer to the modified header, or NULL
2183 * to remove the header. This function frees the
2184 * original string if necessary.
2186 * Returns : JB_ERR_OK on success, or
2187 * JB_ERR_MEMORY on out-of-memory error.
2189 *********************************************************************/
2190 jb_err client_te(struct client_state *csp, char **header)
2192 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2195 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2201 /*********************************************************************
2203 * Function : client_referrer
2205 * Description : Handle the "referer" config setting properly.
2206 * Called from `sed'.
2209 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * 2 : header = On input, pointer to header to modify.
2211 * On output, pointer to the modified header, or NULL
2212 * to remove the header. This function frees the
2213 * original string if necessary.
2215 * Returns : JB_ERR_OK on success, or
2216 * JB_ERR_MEMORY on out-of-memory error.
2218 *********************************************************************/
2219 jb_err client_referrer(struct client_state *csp, char **header)
2226 #ifdef FEATURE_FORCE_LOAD
2227 /* Since the referrer can include the prefix even
2228 * if the request itself is non-forced, we must
2229 * clean it unconditionally
2231 strclean(*header, FORCE_PREFIX);
2232 #endif /* def FEATURE_FORCE_LOAD */
2235 * Are we sending referer?
2237 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2242 newval = csp->action->string[ACTION_STRING_REFERER];
2244 if ((0 != strcmpic(newval, "conditional-block")))
2248 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2253 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2256 else if (0 == strcmpic(newval, "conditional-block"))
2259 * Block referer if host has changed.
2262 if (NULL == (host = strdup(csp->http->hostport)))
2265 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2266 return JB_ERR_MEMORY;
2268 if (NULL == (referer = strdup(*header)))
2272 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2273 return JB_ERR_MEMORY;
2275 hostlenght = strlen(host);
2276 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2278 /*Shorten referer to make sure the referer is blocked
2279 *if www.example.org/www.example.com-shall-see-the-referer/
2280 *links to www.example.com/
2282 referer[hostlenght+17] = '\0';
2284 if ( 0 == strstr(referer, host)) /*Host has changed*/
2286 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2291 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2297 else if (0 != strcmpic(newval, "forge"))
2300 * We have a specific (fixed) referer we want to send.
2302 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2304 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2306 *header = strdup("Referer: ");
2307 string_append(header, newval);
2308 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2310 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2315 * Forge a referer as http://[hostname:port of REQUEST]/
2316 * to fool stupid checks for in-site links
2319 *header = strdup("Referer: http://");
2320 string_append(header, csp->http->hostport);
2321 string_append(header, "/");
2322 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2324 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2328 /*********************************************************************
2330 * Function : client_accept_language
2332 * Description : Handle the "Accept-Language" config setting properly.
2333 * Called from `sed'.
2336 * 1 : csp = Current client state (buffers, headers, etc...)
2337 * 2 : header = On input, pointer to header to modify.
2338 * On output, pointer to the modified header, or NULL
2339 * to remove the header. This function frees the
2340 * original string if necessary.
2342 * Returns : JB_ERR_OK on success, or
2343 * JB_ERR_MEMORY on out-of-memory error.
2345 *********************************************************************/
2346 jb_err client_accept_language(struct client_state *csp, char **header)
2351 * Are we messing with the Accept-Language?
2353 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2355 /*I don't think so*/
2359 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2361 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2364 * Blocking Accept-Language header
2366 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2373 * Replacing Accept-Language header
2376 *header = strdup("Accept-Language: ");
2377 string_append(header, newval);
2379 if (*header == NULL)
2381 log_error(LOG_LEVEL_ERROR,
2382 "Insufficent memory. Accept-Language header crunched without replacement.");
2386 log_error(LOG_LEVEL_HEADER,
2387 "Accept-Language header crunched and replaced with: %s", *header);
2390 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2393 /*********************************************************************
2395 * Function : crunch_client_header
2397 * Description : Crunch client header if it matches a string supplied by the
2398 * user. Called from `sed'.
2401 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * 2 : header = On input, pointer to header to modify.
2403 * On output, pointer to the modified header, or NULL
2404 * to remove the header. This function frees the
2405 * original string if necessary.
2407 * Returns : JB_ERR_OK on success and always succeeds
2409 *********************************************************************/
2410 jb_err crunch_client_header(struct client_state *csp, char **header)
2412 const char *crunch_pattern;
2413 /*Is there a header to crunch*/
2415 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2417 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2419 /*Is the current header the lucky one?*/
2420 if (strstr(*header, crunch_pattern))
2422 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2430 /*********************************************************************
2432 * Function : client_uagent
2434 * Description : Handle the "user-agent" config setting properly
2435 * and remember its original value to enable browser
2436 * bug workarounds. Called from `sed'.
2439 * 1 : csp = Current client state (buffers, headers, etc...)
2440 * 2 : header = On input, pointer to header to modify.
2441 * On output, pointer to the modified header, or NULL
2442 * to remove the header. This function frees the
2443 * original string if necessary.
2445 * Returns : JB_ERR_OK on success, or
2446 * JB_ERR_MEMORY on out-of-memory error.
2448 *********************************************************************/
2449 jb_err client_uagent(struct client_state *csp, char **header)
2453 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2458 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2465 *header = strdup("User-Agent: ");
2466 string_append(header, newval);
2468 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2470 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2473 /*********************************************************************
2475 * Function : client_ua
2477 * Description : Handle "ua-" headers properly. Called from `sed'.
2480 * 1 : csp = Current client state (buffers, headers, etc...)
2481 * 2 : header = On input, pointer to header to modify.
2482 * On output, pointer to the modified header, or NULL
2483 * to remove the header. This function frees the
2484 * original string if necessary.
2486 * Returns : JB_ERR_OK on success, or
2487 * JB_ERR_MEMORY on out-of-memory error.
2489 *********************************************************************/
2490 jb_err client_ua(struct client_state *csp, char **header)
2492 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2494 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2502 /*********************************************************************
2504 * Function : client_from
2506 * Description : Handle the "from" config setting properly.
2507 * Called from `sed'.
2510 * 1 : csp = Current client state (buffers, headers, etc...)
2511 * 2 : header = On input, pointer to header to modify.
2512 * On output, pointer to the modified header, or NULL
2513 * to remove the header. This function frees the
2514 * original string if necessary.
2516 * Returns : JB_ERR_OK on success, or
2517 * JB_ERR_MEMORY on out-of-memory error.
2519 *********************************************************************/
2520 jb_err client_from(struct client_state *csp, char **header)
2524 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2531 newval = csp->action->string[ACTION_STRING_FROM];
2534 * Are we blocking the e-mail address?
2536 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2538 log_error(LOG_LEVEL_HEADER, "crunched From!");
2542 log_error(LOG_LEVEL_HEADER, " modified");
2544 *header = strdup("From: ");
2545 string_append(header, newval);
2547 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2551 /*********************************************************************
2553 * Function : client_send_cookie
2555 * Description : Handle the "cookie" header properly. Called from `sed'.
2556 * If cookie is accepted, add it to the cookie_list,
2557 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2561 * 2 : header = On input, pointer to header to modify.
2562 * On output, pointer to the modified header, or NULL
2563 * to remove the header. This function frees the
2564 * original string if necessary.
2566 * Returns : JB_ERR_OK on success, or
2567 * JB_ERR_MEMORY on out-of-memory error.
2569 *********************************************************************/
2570 jb_err client_send_cookie(struct client_state *csp, char **header)
2572 jb_err result = JB_ERR_OK;
2574 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2576 /* strlen("cookie: ") == 8 */
2577 result = enlist(csp->cookie_list, *header + 8);
2581 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2585 * Always remove the cookie here. The cookie header
2586 * will be sent at the end of the header.
2594 /*********************************************************************
2596 * Function : client_x_forwarded
2598 * Description : Handle the "x-forwarded-for" config setting properly,
2599 * also used in the add_client_headers list. Called from `sed'.
2602 * 1 : csp = Current client state (buffers, headers, etc...)
2603 * 2 : header = On input, pointer to header to modify.
2604 * On output, pointer to the modified header, or NULL
2605 * to remove the header. This function frees the
2606 * original string if necessary.
2608 * Returns : JB_ERR_OK on success, or
2609 * JB_ERR_MEMORY on out-of-memory error.
2611 *********************************************************************/
2612 jb_err client_x_forwarded(struct client_state *csp, char **header)
2614 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2616 /* Save it so we can re-add it later */
2617 freez(csp->x_forwarded);
2618 csp->x_forwarded = *header;
2621 * Always set *header = NULL, since this information
2622 * will be sent at the end of the header.
2629 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2636 /*********************************************************************
2638 * Function : client_max_forwards
2640 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2641 * from the value of the Max-Forwards header field.
2644 * 1 : csp = Current client state (buffers, headers, etc...)
2645 * 2 : header = On input, pointer to header to modify.
2646 * On output, pointer to the modified header, or NULL
2647 * to remove the header. This function frees the
2648 * original string if necessary.
2650 * Returns : JB_ERR_OK on success, or
2651 * JB_ERR_MEMORY on out-of-memory error.
2653 *********************************************************************/
2654 jb_err client_max_forwards(struct client_state *csp, char **header)
2658 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2659 (0 == strcmpic(csp->http->gpc, "options")))
2661 assert(*(*header+12) == ':');
2662 if (1 == sscanf(*header+12, ": %u", &max_forwards))
2664 if (max_forwards > 0)
2666 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2667 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2668 csp->http->gpc, max_forwards);
2670 else if (max_forwards < 0)
2672 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2678 * Not supposed to be reached. direct_response() which
2679 * was already called earlier in chat() should have
2680 * intercepted the request.
2682 log_error(LOG_LEVEL_ERROR,
2683 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2684 assert(max_forwards != 0);
2689 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2698 /*********************************************************************
2700 * Function : client_host
2702 * Description : If the request URI did not contain host and
2703 * port information, parse and evaluate the Host
2706 * Also, kill ill-formed HOST: headers as sent by
2707 * Apple's iTunes software when used with a proxy.
2710 * 1 : csp = Current client state (buffers, headers, etc...)
2711 * 2 : header = On input, pointer to header to modify.
2712 * On output, pointer to the modified header, or NULL
2713 * to remove the header. This function frees the
2714 * original string if necessary.
2716 * Returns : JB_ERR_OK on success, or
2717 * JB_ERR_MEMORY on out-of-memory error.
2719 *********************************************************************/
2720 jb_err client_host(struct client_state *csp, char **header)
2725 * If the header field name is all upper-case, chances are that it's
2726 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2727 * not a problem -- they are regenerated later.
2729 if ((*header)[1] == 'O')
2731 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2736 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2737 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2740 if (NULL == (p = strdup((*header)+6)))
2742 return JB_ERR_MEMORY;
2745 if (NULL == (q = strdup(p)))
2748 return JB_ERR_MEMORY;
2751 freez(csp->http->hostport);
2752 csp->http->hostport = p;
2753 freez(csp->http->host);
2754 csp->http->host = q;
2755 q = strchr(csp->http->host, ':');
2758 /* Terminate hostname and evaluate port string */
2760 csp->http->port = atoi(q);
2764 csp->http->port = csp->http->ssl ? 443 : 80;
2767 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2768 csp->http->hostport, csp->http->host, csp->http->port);
2774 /*********************************************************************
2776 * Function : client_if_modified_since
2778 * Description : Remove or modify the If-Modified-Since header.
2781 * 1 : csp = Current client state (buffers, headers, etc...)
2782 * 2 : header = On input, pointer to header to modify.
2783 * On output, pointer to the modified header, or NULL
2784 * to remove the header. This function frees the
2785 * original string if necessary.
2787 * Returns : JB_ERR_OK on success, or
2788 * JB_ERR_MEMORY on out-of-memory error.
2790 *********************************************************************/
2791 jb_err client_if_modified_since(struct client_state *csp, char **header)
2794 #ifdef HAVE_GMTIME_R
2797 struct tm *timeptr = NULL;
2801 long int hours, minutes, seconds;
2805 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2808 * The client got an error message because of a temporary problem,
2809 * the problem is gone and the client now tries to revalidate our
2810 * error message on the real server. The revalidation would always
2811 * end with the transmission of the whole document and there is
2812 * no need to expose the bogus If-Modified-Since header.
2814 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2817 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2819 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2821 if ((0 == strcmpic(newval, "block")))
2823 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2826 else /* add random value */
2828 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2830 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2835 rtime = strtol(newval, &endptr, 0);
2838 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2839 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2846 rtime = pick_from_range(rtime);
2850 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2853 tm += rtime * (negative ? -1 : 1);
2854 #ifdef HAVE_GMTIME_R
2855 timeptr = gmtime_r(&tm, &gmt);
2856 #elif FEATURE_PTHREAD
2857 pthread_mutex_lock(&gmtime_mutex);
2858 timeptr = gmtime(&tm);
2859 pthread_mutex_unlock(&gmtime_mutex);
2861 timeptr = gmtime(&tm);
2863 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2866 *header = strdup("If-Modified-Since: ");
2867 string_append(header, newheader);
2869 if (*header == NULL)
2871 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2872 return JB_ERR_MEMORY;
2875 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2877 hours = rtime / 3600;
2878 minutes = rtime / 60 % 60;
2879 seconds = rtime % 60;
2881 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2882 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2883 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2892 /*********************************************************************
2894 * Function : client_if_none_match
2896 * Description : Remove the If-None-Match header.
2899 * 1 : csp = Current client state (buffers, headers, etc...)
2900 * 2 : header = On input, pointer to header to modify.
2901 * On output, pointer to the modified header, or NULL
2902 * to remove the header. This function frees the
2903 * original string if necessary.
2905 * Returns : JB_ERR_OK on success, or
2906 * JB_ERR_MEMORY on out-of-memory error.
2908 *********************************************************************/
2909 jb_err client_if_none_match(struct client_state *csp, char **header)
2911 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2913 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2920 /*********************************************************************
2922 * Function : client_x_filter
2924 * Description : Disables filtering if the client set "X-Filter: No".
2925 * Called from `sed'.
2928 * 1 : csp = Current client state (buffers, headers, etc...)
2929 * 2 : header = On input, pointer to header to modify.
2930 * On output, pointer to the modified header, or NULL
2931 * to remove the header. This function frees the
2932 * original string if necessary.
2934 * Returns : JB_ERR_OK on success
2936 *********************************************************************/
2937 jb_err client_x_filter(struct client_state *csp, char **header)
2939 if ( 0 == strcmpic(*header, "X-Filter: No"))
2941 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2943 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2947 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2949 log_error(LOG_LEVEL_HEADER,
2950 "force-text-mode overruled the client's request to fetch without filtering!");
2954 csp->content_type = CT_TABOO;
2955 csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
2956 csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
2957 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2959 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2966 /* the following functions add headers directly to the header list */
2968 /*********************************************************************
2970 * Function : client_host_adder
2972 * Description : Adds the Host: header field if it is missing.
2973 * Called from `sed'.
2976 * 1 : csp = Current client state (buffers, headers, etc...)
2978 * Returns : JB_ERR_OK on success, or
2979 * JB_ERR_MEMORY on out-of-memory error.
2981 *********************************************************************/
2982 jb_err client_host_adder(struct client_state *csp)
2987 if ( !csp->http->hostport || !*(csp->http->hostport))
2993 * remove 'user:pass@' from 'proto://user:pass@host'
2995 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3001 p = csp->http->hostport;
3004 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3005 err = enlist_unique_header(csp->headers, "Host", p);
3011 /*********************************************************************
3013 * Function : client_cookie_adder
3015 * Description : Used in the add_client_headers list. Called from `sed'.
3018 * 1 : csp = Current client state (buffers, headers, etc...)
3020 * Returns : JB_ERR_OK on success, or
3021 * JB_ERR_MEMORY on out-of-memory error.
3023 *********************************************************************/
3024 jb_err client_cookie_adder(struct client_state *csp)
3026 struct list_entry *lst;
3028 struct list_entry *list1 = csp->cookie_list->first;
3029 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3030 int first_cookie = 1;
3033 if ((list1 == NULL) && (list2 == NULL))
3039 tmp = strdup("Cookie: ");
3041 for (lst = list1; lst ; lst = lst->next)
3049 string_append(&tmp, "; ");
3051 string_append(&tmp, lst->str);
3054 for (lst = list2; lst ; lst = lst->next)
3062 string_append(&tmp, "; ");
3064 string_join(&tmp, cookie_encode(lst->str));
3069 return JB_ERR_MEMORY;
3072 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3073 err = enlist(csp->headers, tmp);
3079 /*********************************************************************
3081 * Function : client_accept_encoding_adder
3083 * Description : Add an Accept-Encoding header to the client's request
3084 * that disables compression if the action applies, and
3085 * the header is not already there. Called from `sed'.
3086 * Note: For HTTP/1.0, the absence of the header is enough.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3091 * Returns : JB_ERR_OK on success, or
3092 * JB_ERR_MEMORY on out-of-memory error.
3094 *********************************************************************/
3095 jb_err client_accept_encoding_adder(struct client_state *csp)
3097 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3098 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3100 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3107 /*********************************************************************
3109 * Function : client_xtra_adder
3111 * Description : Used in the add_client_headers list. Called from `sed'.
3114 * 1 : csp = Current client state (buffers, headers, etc...)
3116 * Returns : JB_ERR_OK on success, or
3117 * JB_ERR_MEMORY on out-of-memory error.
3119 *********************************************************************/
3120 jb_err client_xtra_adder(struct client_state *csp)
3122 struct list_entry *lst;
3125 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3126 lst ; lst = lst->next)
3128 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3129 err = enlist(csp->headers, lst->str);
3141 /*********************************************************************
3143 * Function : client_x_forwarded_adder
3145 * Description : Used in the add_client_headers list. Called from `sed'.
3148 * 1 : csp = Current client state (buffers, headers, etc...)
3150 * Returns : JB_ERR_OK on success, or
3151 * JB_ERR_MEMORY on out-of-memory error.
3153 *********************************************************************/
3154 jb_err client_x_forwarded_adder(struct client_state *csp)
3159 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3164 if (csp->x_forwarded)
3166 p = strdup(csp->x_forwarded);
3167 string_append(&p, ", ");
3171 p = strdup("X-Forwarded-For: ");
3173 string_append(&p, csp->ip_addr_str);
3177 return JB_ERR_MEMORY;
3180 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3181 err = enlist(csp->headers, p);
3188 /*********************************************************************
3190 * Function : connection_close_adder
3192 * Description : Adds a "Connection: close" header to csp->headers
3193 * as a temporary fix for the needed but missing HTTP/1.1
3194 * support. Called from `sed'.
3195 * FIXME: This whole function shouldn't be neccessary!
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3200 * Returns : JB_ERR_OK on success, or
3201 * JB_ERR_MEMORY on out-of-memory error.
3203 *********************************************************************/
3204 jb_err connection_close_adder(struct client_state *csp)
3206 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3207 return enlist(csp->headers, "Connection: close");
3211 /*********************************************************************
3213 * Function : server_http
3215 * Description : - Save the HTTP Status into csp->http->status
3216 * - Set CT_TABOO to prevent filtering if the answer
3217 * is a partial range (HTTP status 206)
3218 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3222 * 1 : csp = Current client state (buffers, headers, etc...)
3223 * 2 : header = On input, pointer to header to modify.
3224 * On output, pointer to the modified header, or NULL
3225 * to remove the header. This function frees the
3226 * original string if necessary.
3228 * Returns : JB_ERR_OK on success, or
3229 * JB_ERR_MEMORY on out-of-memory error.
3231 *********************************************************************/
3232 jb_err server_http(struct client_state *csp, char **header)
3234 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3235 if (csp->http->status == 206)
3237 csp->content_type = CT_TABOO;
3240 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3243 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3250 /*********************************************************************
3252 * Function : server_set_cookie
3254 * Description : Handle the server "cookie" header properly.
3255 * Log cookie to the jar file. Then "crunch",
3256 * accept or rewrite it to a session cookie.
3257 * Called from `sed'.
3259 * TODO: Allow the user to specify a new expiration
3260 * time to cause the cookie to expire even before the
3261 * browser is closed.
3264 * 1 : csp = Current client state (buffers, headers, etc...)
3265 * 2 : header = On input, pointer to header to modify.
3266 * On output, pointer to the modified header, or NULL
3267 * to remove the header. This function frees the
3268 * original string if necessary.
3270 * Returns : JB_ERR_OK on success, or
3271 * JB_ERR_MEMORY on out-of-memory error.
3273 *********************************************************************/
3274 jb_err server_set_cookie(struct client_state *csp, char **header)
3279 struct tm tm_cookie;
3282 #ifdef FEATURE_COOKIE_JAR
3283 if (csp->config->jar)
3286 * Write timestamp into outbuf.
3288 * Complex because not all OSs have tm_gmtoff or
3289 * the %z field in strftime()
3291 char tempbuf[ BUFFER_SIZE ];
3293 #ifdef HAVE_LOCALTIME_R
3294 tm_now = *localtime_r(&now, &tm_now);
3295 #elif FEATURE_PTHREAD
3296 pthread_mutex_lock(&localtime_mutex);
3297 tm_now = *localtime (&now);
3298 pthread_mutex_unlock(&localtime_mutex);
3300 tm_now = *localtime (&now);
3302 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3304 /* strlen("set-cookie: ") = 12 */
3305 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3307 #endif /* def FEATURE_COOKIE_JAR */
3309 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3311 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3312 return crumble(csp, header);
3314 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3316 /* Flag whether or not to log a message */
3319 /* A variable to store the tag we're working on */
3322 /* Skip "Set-Cookie:" (11 characters) in header */
3323 cur_tag = *header + 11;
3325 /* skip whitespace between "Set-Cookie:" and value */
3326 while (*cur_tag && ijb_isspace(*cur_tag))
3331 /* Loop through each tag in the cookie */
3335 char *next_tag = strchr(cur_tag, ';');
3336 if (next_tag != NULL)
3338 /* Skip the ';' character itself */
3341 /* skip whitespace ";" and start of tag */
3342 while (*next_tag && ijb_isspace(*next_tag))
3349 /* "Next tag" is the end of the string */
3350 next_tag = cur_tag + strlen(cur_tag);
3354 * Check the expiration date to see
3355 * if the cookie is still valid, if yes,
3356 * rewrite it to a session cookie.
3358 if (strncmpic(cur_tag, "expires=", 8) == 0)
3362 * Try the valid time formats we know about.
3364 * XXX: Maybe the log messages should be removed
3365 * for the next stable release. They just exist to
3366 * see which time format gets the most hits and
3367 * should be checked for first.
3369 if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3371 log_error(LOG_LEVEL_HEADER,
3372 "cookie \'%s\' send by %s appears to be using time format 1.",
3373 csp->http->url, *header);
3375 else if (NULL != (match = strptime(cur_tag, "expires=%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3377 log_error(LOG_LEVEL_HEADER,
3378 "cookie \'%s\' send by %s appears to be using time format 2.",
3379 csp->http->url, *header);
3382 else if (NULL != (match = strptime(cur_tag, "expires=%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3384 log_error(LOG_LEVEL_HEADER,
3385 "cookie \'%s\' send by %s appears to be using time format 3.",
3386 csp->http->url, *header);
3389 /* Did any of them match? */
3393 * Nope, treat it as if it was still valid.
3395 * XXX: Should we remove the whole cookie instead?
3397 log_error(LOG_LEVEL_ERROR,
3398 "Can't parse %s. Unsupported time format?", cur_tag);
3399 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3405 * Yes. Check if the cookie is still valid.
3407 * If the cookie is already expired it's probably
3408 * a delete cookie and even if it isn't, the browser
3409 * will discard it anyway.
3413 * XXX: timegm() isn't available on some AmigaOS
3414 * versions and our replacement doesn't work.
3416 * Our options are to either:
3418 * - disable session-cookies-only completely if timegm
3421 * - to simply remove all expired tags, like it has
3422 * been done until Privoxy 3.0.6 and to live with
3423 * the consequence that it can cause login/logout
3424 * problems on servers that don't validate their
3425 * input properly, or
3427 * - to replace it with mktime in which
3428 * case there is a slight chance of valid cookies
3429 * passing as already expired.
3431 * This is the way it's currently done and it's not
3432 * as bad as it sounds. If the missing GMT offset is
3433 * enough to change the result of the expiration check
3434 * the cookie will be only valid for a few hours
3435 * anyway, which in many cases will be shorter
3436 * than a browser session.
3438 cookie_time = timegm(&tm_cookie);
3439 if (cookie_time - now < 0)
3441 log_error(LOG_LEVEL_HEADER,
3442 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3443 /* Just in case some clown sets more then one expiration date */
3448 log_error(LOG_LEVEL_HEADER,
3449 "Cookie \'%s\' is still valid and has to be rewritten.", *header);
3452 * Delete the tag by copying the rest of the string over it.
3453 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3454 * since the behaviour of strcpy is undefined for overlapping
3457 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3459 /* That changed the header, need to issue a log message */
3463 * Note that the next tag has now been moved to *cur_tag,
3464 * so we do not need to update the cur_tag pointer.
3472 /* Move on to next cookie tag */
3479 assert(NULL != *header);
3480 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3489 #ifdef FEATURE_FORCE_LOAD
3490 /*********************************************************************
3492 * Function : strclean
3494 * Description : In-Situ-Eliminate all occurances of substring in
3498 * 1 : string = string to clean
3499 * 2 : substring = substring to eliminate
3501 * Returns : Number of eliminations
3503 *********************************************************************/
3504 int strclean(const char *string, const char *substring)
3510 len = strlen(substring);
3512 while((pos = strstr(string, substring)) != NULL)
3519 while (*p++ != '\0');
3526 #endif /* def FEATURE_FORCE_LOAD */
3528 /*********************************************************************
3530 * Function : parse_header_time
3532 * Description : Transforms time inside a HTTP header into
3533 * the usual time format.
3536 * 1 : header = header to parse
3537 * 2 : tm = storage for the resulting time in seconds
3539 * Returns : Time struct containing the header time, or
3540 * NULL in case of a parsing problems.
3542 *********************************************************************/
3543 struct tm *parse_header_time(char *header, time_t *tm) {
3547 struct tm * timeptr;
3550 * Initializing gmt to prevent time zone offsets.
3552 * While this is only necessary on some platforms
3553 * (mingw32 for example), I don't know how to
3554 * detect these automatically and doing it everywhere
3558 #ifdef HAVE_LOCALTIME_R
3559 gmt = *localtime_r(tm, &gmt);
3560 #elif FEATURE_PTHREAD
3561 pthread_mutex_lock(&localtime_mutex);
3562 gmt = *localtime(tm);
3563 pthread_mutex_unlock(&localtime_mutex);
3565 gmt = *localtime(tm);
3568 /* Skipping header name */
3569 timestring = strstr(header, ": ");
3570 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3583 /*********************************************************************
3585 * Function : get_destination_from_headers
3587 * Description : Parse the "Host:" header to get the request's destination.
3588 * Only needed if the client's request was forcefully
3589 * redirected into Privoxy.
3591 * Code mainly copied from client_host() which is currently
3592 * run too late for this purpose.
3595 * 1 : headers = List of headers (one of them hopefully being
3596 * the "Host:" header)
3597 * 2 : http = storage for the result (host, port and hostport).
3599 * Returns : JB_ERR_MEMORY in case of memory problems,
3600 * JB_ERR_PARSE if the host header couldn't be found,
3601 * JB_ERR_OK otherwise.
3603 *********************************************************************/
3604 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3610 host = get_header_value(headers, "Host:");
3614 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3615 return JB_ERR_PARSE;
3618 if (NULL == (p = strdup((host))))
3620 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3621 return JB_ERR_MEMORY;
3624 if (NULL == (q = strdup(p)))
3627 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3628 return JB_ERR_MEMORY;
3631 freez(http->hostport);
3635 q = strchr(http->host, ':');
3638 /* Terminate hostname and evaluate port string */
3640 http->port = atoi(q);
3644 http->port = http->ssl ? 443 : 80;
3647 /* Rebuild request URL */
3649 http->url = strdup(http->ssl ? "https://" : "http://");
3650 string_append(&http->url, http->hostport);
3651 string_append(&http->url, http->path);
3652 if (http->url == NULL)
3654 return JB_ERR_MEMORY;
3657 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",