1 const char parsers_rcs[] = "$Id: parsers.c,v 1.143 2008/09/21 13:36:52 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_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2008 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
48 * If change-x-forwarded-for{add} is used and the client
49 * sends multiple X-Forwarded-For headers, append the client's
50 * IP address to each one of them. "Traditionally" we would
51 * lose all but the last one.
53 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
54 * Remove hide-forwarded-for-headers action which has
55 * been obsoleted by change-x-forwarded-for{block}.
57 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
58 * Add change-x-forwarded-for{} action to block or add
59 * X-Forwarded-For headers. Mostly based on code removed
62 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
63 * - A few style fixes.
64 * - Remove a pointless cast.
66 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
67 * Prepare for critical sections on Windows by adding a
68 * layer of indirection before the pthread mutex functions.
70 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
71 * Remove FEATURE_COOKIE_JAR.
73 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
74 * Remove questionable micro-optimizations
75 * whose usefulness has never been measured.
77 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
78 * s@Insufficent@Insufficient@
80 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
81 * The whole point of strclean() is to modify the
82 * first parameter, so don't mark it immutable,
83 * even though the compiler lets us get away with it.
85 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
86 * As the wafer actions are gone, we can stop including encode.h.
88 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
89 * Ditch cast from (char **) to (char **).
91 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
92 * Streamline sed()'s prototype and declare
93 * the header parse and add structures static.
95 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
96 * Factor update_server_headers() out of sed(), ditch the
97 * first_run hack and make server_patterns_light static.
99 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
100 * Wrap memmove() calls in string_move()
101 * to document the purpose in one place.
103 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
104 * Normalize linear header white space.
106 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
107 * If a header is split across multiple lines,
108 * merge them to a single line before parsing them.
110 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
111 * Don't provide get_header() with the whole client state
112 * structure when it only needs access to csp->iob.
114 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
115 * Change content_filters_enabled()'s parameter from
116 * csp->action to action so it can be also used in the
117 * CGI code. Don't bother checking if there are filters
118 * loaded, as that's somewhat besides the point.
120 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
121 * Provide get_http_time() with the buffer size so it doesn't
122 * have to blindly assume that the buffer is big enough.
124 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
125 * Don't pass the whole csp structure to flush_socket()
126 * when it only needs a file descriptor and a buffer.
128 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
129 * Remove send-wafer and send-vanilla-wafer actions.
131 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
132 * Remove inspect-jpegs action.
134 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
135 * Let client_range() also handle Request-Range headers
136 * which apparently are still supported by many servers.
138 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
139 * Improve the warning messages that get logged if the action files
140 * "enable" filters but no filters of that type have been loaded.
142 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
143 * In server_content_type():
144 * - Don't require leading white space when detecting image content types.
145 * - Change '... not replaced ...' message to sound less crazy if the text
146 * type actually is 'text/plain'.
147 * - Mark the 'text/plain == binary data' assumption for removal.
148 * - Remove a bunch of trailing white space.
150 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
151 * Minor server_content_disposition() changes:
152 * - Don't regenerate the header name all lower-case.
153 * - Some white space fixes.
154 * - Remove useless log message in case of ENOMEM.
156 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
157 * Garbage-collect the code to add a X-Forwarded-For
158 * header as it seems to be mostly used by accident.
160 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
161 * Fix a crash on mingw32 with some Last Modified times in the future.
163 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
164 * Remove a "can't happen" error block which, over
165 * time, mutated into a "guaranteed to happen" block.
167 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
168 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
169 * - Use shiny new content_filters_enabled() in client_range().
171 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
172 * I forgot about Poland.
174 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
175 * Remove Range and If-Range headers if content filtering is enabled.
177 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
178 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
179 * client_cookie_adder() to make sure send-vanilla-wafer can be
180 * controlled through tags (and thus regression-tested).
182 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
183 * - Remove "scanning headers for" log message again.
184 * - Some more whitespace fixes.
186 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
187 * Refactor client_referrer() and add conditional-forge parameter.
189 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
190 * A bunch of whitespace fixes, pointy hat to me.
192 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
193 * Fix possible memory corruption in server_http, make sure it's not
194 * executed for ordinary server headers and mark some problems for later.
196 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
197 * Let content-type-overwrite{} honour force-text-mode again.
199 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
200 * - Add prototpyes for the header parsers and make them static.
201 * - Comment out client_accept_encoding_adder() which isn't used right now.
203 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
204 * Move the ACTION_FORCE_TEXT_MODE check out of
205 * server_content_type(). Signal other functions
206 * whether or not a content type has been declared.
207 * Part of the fix for BR#1750917.
209 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
210 * Change sed() to return a jb_err in preparation for forward-override{}.
212 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
213 * Adjust "X-Filter: No" to disable dedicated header filters.
215 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
216 * Streamline client_cookie_adder().
218 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
219 * Make sure filters with dynamic jobs actually use them.
221 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
222 * - Introduce dynamic pcrs jobs that can resolve variables.
223 * - Remove unnecessary update_action_bits_for_all_tags() call.
225 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
226 * - Make tagging based on tags set by earlier taggers
227 * of the same kind possible.
228 * - Log whether or not new tags cause action bits updates
229 * (in which case a matching tag-pattern section exists).
230 * - Log if the user tries to set a tag that is already set.
232 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
233 * Introduce tags as alternative way to specify which
234 * actions apply to a request. At the moment tags can be
235 * created based on client and server headers.
237 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
238 * Log a warning if the content is compressed, filtering is
239 * enabled and Privoxy was compiled without zlib support.
242 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
243 * - Fix warnings when compiled with glibc.
244 * - Don't use crumble() for cookie crunching.
245 * - Move cookie time parsing into parse_header_time().
246 * - Let parse_header_time() return a jb_err code
247 * instead of a pointer that can only be used to
248 * check for NULL anyway.
250 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
251 * - Add better protection against malicious gzip headers.
252 * - Stop logging the first hundred bytes of decompressed content.
253 * It looks like it's working and there is always debug 16.
254 * - Log the content size after decompression in decompress_iob()
255 * instead of pcrs_filter_response().
257 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
258 * - Use dedicated header filter actions instead of abusing "filter".
259 * Replace "filter-client-headers" and "filter-client-headers"
260 * with "server-header-filter" and "client-header-filter".
261 * - Remove filter_client_header() and filter_client_header(),
262 * filter_header() now checks the shiny new
263 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
265 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
266 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
267 * - Handle "Cookie:" and "Connection:" headers a bit smarter
268 * (don't crunch them just to recreate them later on).
269 * - Add another non-standard time format for the cookie
270 * expiration date detection.
271 * - Fix a valgrind warning.
273 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
274 * Improve cookie expiration date detection.
276 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
277 * Don't run server_content_length() the first time
278 * sed() parses server headers; only adjust the
279 * Content-Length header if the page was modified.
281 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
282 * Fix log messages regarding the cookie time format
283 * (cookie and request URL were mixed up).
285 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
286 * - Let decompress_iob()
287 * - not corrupt the content if decompression fails
288 * early. (the first byte(s) were lost).
289 * - use pointer arithmetics with defined outcome for
291 * - Use a different kludge to remember a failed decompression.
293 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
294 * Search for Max-Forwards headers case-insensitive,
295 * don't generate the "501 unsupported" message for invalid
296 * Max-Forwards values and don't increase negative ones.
298 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
299 * - Let server_set_cookie() check the expiration date
300 * of cookies and don't touch the ones that are already
301 * expired. Fixes problems with low quality web applications
302 * as described in BR 932612.
304 * - Adjust comment in client_max_forwards to reality;
305 * remove invalid Max-Forwards headers.
307 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
308 * Stop filter_header() from unintentionally removing
309 * empty header lines that were enlisted by the continue
312 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
313 * - Repeat the request URL before logging any headers.
314 * Makes reading the log easier in case of simultaneous requests.
315 * - If there are more than one Content-Type headers in one request,
316 * use the first one and remove the others.
317 * - Remove "newval" variable in server_content_type().
318 * It's only used once.
320 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
321 * Correct a cast, check inflateEnd() exit code
322 * to see if we have to, replace sprintf calls
325 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
326 * Integrate a modified version of Wil Mahan's
327 * zlib patch (PR #895531).
329 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
330 * Skip empty filter files in filter_header()
331 * but don't ignore the ones that come afterwards.
332 * Fixes BR 1619208, this time for real.
334 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
335 * Reverted parts of my last commit
336 * to keep error handling working.
338 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
339 * Fixed gcc43 conversion warnings.
341 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
342 * Bringing back the "useless" localtime() call
343 * I removed in revision 1.67. On some platforms
344 * it's necessary to prevent time zone offsets.
346 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
347 * Rebuild request URL in get_destination_from_headers()
348 * to make sure redirect{pcrs command} works as expected
349 * for intercepted requests.
351 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
352 * Added get_destination_from_headers().
354 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
355 * Make pthread mutex locking more generic. Instead of
356 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
357 * and use mutex locking unless there is an _r function
358 * available. Better safe than sorry.
360 * Fixes "./configure --disable-pthread" and should result
361 * in less threading-related problems on pthread-using platforms,
362 * but it still doesn't fix BR#1122404.
364 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
365 * The special header "X-Filter: No" now disables
366 * header filtering as well.
368 * Revision 1.73 2006/09/23 13:26:38 roro
369 * Replace TABs by spaces in source code.
371 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
372 * Don't print a log message every time filter_headers is
373 * entered or left. It only creates noise without any real
376 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
377 * Fix +hide-if-modified-since{-n}.
379 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
380 * Have hide-if-modified-since interpret the random
381 * range value as minutes instead of hours. Allows
382 * more fine-grained configuration.
384 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
385 * Always have parse_header_time return a pointer
386 * that actual makes sense, even though we currently
387 * only need it to detect problems.
389 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
390 * Added config option enable-remote-http-toggle
391 * to specify if Privoxy should recognize special
392 * headers (currently only X-Filter) to change its
393 * behaviour. Disabled by default.
395 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
396 * After filtering de-chunked instances, remove
397 * "Transfer-Encoding" header entirely instead of changing
398 * it to "Transfer-Encoding: identity", which is invalid.
399 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
401 * Don't use localtime in parse_header_time. An empty time struct
402 * is good enough, it gets overwritten by strptime anyway.
404 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
405 * Use gmtime_r if available, fallback to gmtime with mutex
406 * protection for MacOSX and use vanilla gmtime for the rest.
408 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
409 * Changed client_referrer to use the right type (size_t) for
410 * hostlenght and to shorten the temporary referrer string with
411 * '\0' instead of adding a useless line break.
413 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
414 * - Back to timegm() using GnuPG's replacement if necessary.
415 * Using mktime() and localtime() could add a on hour offset if
416 * the randomize factor was big enough to lead to a summer/wintertime
419 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
421 * - Moved randomization code into pick_from_range().
423 * - Changed parse_header_time definition.
424 * time_t isn't guaranteed to be signed and
425 * if it isn't, -1 isn't available as error code.
426 * Changed some variable types in client_if_modified_since()
427 * because of the same reason.
429 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
430 * OS/2 compilation compatibility fixups
432 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
433 * Changed include from strptime.c to strptime.h
435 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
436 * Split filter-headers{} into filter-client-headers{}
437 * and filter-server-headers{}.
438 * Added parse_header_time() to share some code.
439 * Replaced timegm() with mktime().
441 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
442 * Windows service integration
444 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
445 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
447 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
448 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
449 * with what was really the latest development (the v_3_0_branch branch)
451 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
452 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
454 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
455 * Add the ability to check jpeg images for invalid
456 * lengths of comment blocks. Defensive strategy
457 * against the exploit:
458 * Microsoft Security Bulletin MS04-028
459 * Buffer Overrun in JPEG Processing (GDI+) Could
460 * Allow Code Execution (833987)
461 * Enabled with +inspect-jpegs in actions files.
463 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
464 * Excluded text/plain objects from filtering. This fixes a
465 * couple of client-crashing, download corruption and
466 * Privoxy performance issues, whose root cause lies in
467 * web servers labelling content of unknown type as text/plain.
469 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
470 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
472 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
473 * Completing the previous change
475 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
476 * Added temporary workaround for bug in PHP < 4.2.3
478 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
479 * 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.
481 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
482 * Fix typo: supressed -> suppressed
484 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
485 * Improved cookie logging
487 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
488 * Added basic support for OPTIONS and TRACE HTTP methods:
489 * - New parser function client_max_forwards which decrements
490 * the Max-Forwards HTTP header field of OPTIONS and TRACE
491 * requests by one before forwarding
492 * - New parser function client_host which extracts the host
493 * and port information from the HTTP header field if the
494 * request URI was not absolute
495 * - Don't crumble and re-add the Host: header, but only generate
496 * and append if missing
498 * Revision 1.56 2002/05/12 15:34:22 jongfoster
499 * Fixing typo in a comment
501 * Revision 1.55 2002/05/08 16:01:07 oes
502 * Optimized add_to_iob:
503 * - Use realloc instead of malloc(), memcpy(), free()
504 * - Expand to powers of two if possible, to get
505 * O(log n) reallocs instead of O(n).
506 * - Moved check for buffer limit here from chat
507 * - Report failure via returncode
509 * Revision 1.54 2002/04/02 15:03:16 oes
510 * Tiny code cosmetics
512 * Revision 1.53 2002/03/26 22:29:55 swa
513 * we have a new homepage!
515 * Revision 1.52 2002/03/24 13:25:43 swa
516 * name change related issues
518 * Revision 1.51 2002/03/13 00:27:05 jongfoster
521 * Revision 1.50 2002/03/12 01:45:35 oes
522 * More verbose logging
524 * Revision 1.49 2002/03/09 20:03:52 jongfoster
525 * - Making various functions return int rather than size_t.
526 * (Undoing a recent change). Since size_t is unsigned on
527 * Windows, functions like read_socket that return -1 on
528 * error cannot return a size_t.
530 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
531 * crashes, and also frequently caused JB to jump to 100%
532 * CPU and stay there. (Because it thought it had just
533 * read ((unsigned)-1) == 4Gb of data...)
535 * - The signature of write_socket has changed, it now simply
536 * returns success=0/failure=nonzero.
538 * - Trying to get rid of a few warnings --with-debug on
539 * Windows, I've introduced a new type "jb_socket". This is
540 * used for the socket file descriptors. On Windows, this
541 * is SOCKET (a typedef for unsigned). Everywhere else, it's
542 * an int. The error value can't be -1 any more, so it's
543 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
544 * Windows it maps to the #define INVALID_SOCKET.)
546 * - The signature of bind_port has changed.
548 * Revision 1.48 2002/03/07 03:46:53 oes
549 * Fixed compiler warnings etc
551 * Revision 1.47 2002/02/20 23:15:13 jongfoster
552 * Parsing functions now handle out-of-memory gracefully by returning
555 * Revision 1.46 2002/01/17 21:03:47 jongfoster
556 * Moving all our URL and URL pattern parsing code to urlmatch.c.
558 * Revision 1.45 2002/01/09 14:33:03 oes
559 * Added support for localtime_r.
561 * Revision 1.44 2001/12/14 01:22:54 steudten
562 * Remove 'user:pass@' from 'proto://user:pass@host' for the
563 * new added header 'Host: ..'. (See Req ID 491818)
565 * Revision 1.43 2001/11/23 00:26:38 jongfoster
566 * Fixing two really stupid errors in my previous commit
568 * Revision 1.42 2001/11/22 21:59:30 jongfoster
569 * Adding code to handle +no-cookies-keep
571 * Revision 1.41 2001/11/05 23:43:05 steudten
572 * Add time+date to log files.
574 * Revision 1.40 2001/10/26 20:13:09 jongfoster
575 * ctype.h is needed in Windows, too.
577 * Revision 1.39 2001/10/26 17:40:04 oes
578 * Introduced get_header_value()
579 * Removed http->user_agent, csp->referrer and csp->accept_types
580 * Removed client_accept()
582 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
583 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
584 * threads to call select() simultaneously. So, it's time to do a real, live,
585 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
586 * (native). Both versions will work, but using __OS2__ offers multi-threading.
588 * Revision 1.37 2001/10/23 21:36:02 jongfoster
589 * Documenting sed()'s error behaviou (doc change only)
591 * Revision 1.36 2001/10/13 12:51:51 joergs
592 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
593 * force-load), instead crumble Host: and add it (again) in client_host_adder
594 * (in case we get a HTTP/1.0 request without Host: header and forward it to
595 * a HTTP/1.1 server/proxy).
597 * Revision 1.35 2001/10/09 22:39:21 jongfoster
598 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
601 * Revision 1.34 2001/10/07 18:50:55 oes
602 * Added server_content_encoding, renamed server_transfer_encoding
604 * Revision 1.33 2001/10/07 18:04:49 oes
605 * Changed server_http11 to server_http and its pattern to "HTTP".
606 * Additional functionality: it now saves the HTTP status into
607 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
609 * Revision 1.32 2001/10/07 15:43:28 oes
610 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
611 * client_te and client_accept_encoding_adder, triggered by the new
612 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
613 * changed to allow only identity and chunked, and the TE header is
614 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
616 * parse_http_request no longer does anything than parsing. The rewriting
617 * of http->cmd and version mangling are gone. It now also recognizes
618 * the put and delete methods and saves the url in http->url. Removed
621 * renamed content_type and content_length to have the server_ prefix
623 * server_content_type now only works if csp->content_type != CT_TABOO
625 * added server_transfer_encoding, which
626 * - Sets CT_TABOO to prohibit filtering if encoding compresses
627 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
628 * - Change from "chunked" to "identity" if body was chunked
629 * but has been de-chunked for filtering.
631 * added server_content_md5 which crunches any Content-MD5 headers
632 * if the body was modified.
634 * made server_http11 conditional on +downgrade action
636 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
638 * Revision 1.31 2001/10/05 14:25:02 oes
639 * Crumble Keep-Alive from Server
641 * Revision 1.30 2001/09/29 12:56:03 joergs
642 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
644 * Revision 1.29 2001/09/24 21:09:24 jongfoster
645 * Fixing 2 memory leaks that Guy spotted, where the paramater to
646 * enlist() was not being free()d.
648 * Revision 1.28 2001/09/22 16:32:28 jongfoster
649 * Removing unused #includes.
651 * Revision 1.27 2001/09/20 15:45:25 steudten
653 * add casting from size_t to int for printf()
654 * remove local variable shadow s2
656 * Revision 1.26 2001/09/16 17:05:14 jongfoster
657 * Removing unused #include showarg.h
659 * Revision 1.25 2001/09/16 13:21:27 jongfoster
660 * Changes to use new list functions.
662 * Revision 1.24 2001/09/13 23:05:50 jongfoster
663 * Changing the string paramater to the header parsers a "const".
665 * Revision 1.23 2001/09/12 18:08:19 steudten
667 * In parse_http_request() header rewriting miss the host value, so
668 * from http://www.mydomain.com the result was just " / " not
669 * http://www.mydomain.com/ in case we forward.
671 * Revision 1.22 2001/09/10 10:58:53 oes
672 * Silenced compiler warnings
674 * Revision 1.21 2001/07/31 14:46:00 oes
675 * - Persistant connections now suppressed
676 * - sed() no longer appends empty header to csp->headers
678 * Revision 1.20 2001/07/30 22:08:36 jongfoster
679 * Tidying up #defines:
680 * - All feature #defines are now of the form FEATURE_xxx
681 * - Permanently turned off WIN_GUI_EDIT
682 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
684 * Revision 1.19 2001/07/25 17:21:54 oes
685 * client_uagent now saves copy of User-Agent: header value
687 * Revision 1.18 2001/07/13 14:02:46 oes
688 * - Included fix to repair broken HTTP requests that
689 * don't contain a path, not even '/'.
690 * - Removed all #ifdef PCRS
691 * - content_type now always inspected and classified as
692 * text, gif or other.
693 * - formatting / comments
695 * Revision 1.17 2001/06/29 21:45:41 oes
696 * Indentation, CRLF->LF, Tab-> Space
698 * Revision 1.16 2001/06/29 13:32:42 oes
700 * - Adapted free_http_request
701 * - Removed logentry from cancelled commit
703 * Revision 1.15 2001/06/03 19:12:38 oes
704 * deleted const struct interceptors
706 * Revision 1.14 2001/06/01 18:49:17 jongfoster
707 * Replaced "list_share" with "list" - the tiny memory gain was not
708 * worth the extra complexity.
710 * Revision 1.13 2001/05/31 21:30:33 jongfoster
711 * Removed list code - it's now in list.[ch]
712 * Renamed "permission" to "action", and changed many features
713 * to use the actions file rather than the global config.
715 * Revision 1.12 2001/05/31 17:33:13 oes
719 * Revision 1.11 2001/05/29 20:11:19 joergs
720 * '/ * inside comment' warning removed.
722 * Revision 1.10 2001/05/29 09:50:24 jongfoster
723 * Unified blocklist/imagelist/permissionslist.
724 * File format is still under discussion, but the internal changes
727 * Also modified interceptor behaviour:
728 * - We now intercept all URLs beginning with one of the following
729 * prefixes (and *only* these prefixes):
731 * * http://ijbswa.sf.net/config/
732 * * http://ijbswa.sourceforge.net/config/
733 * - New interceptors "home page" - go to http://i.j.b/ to see it.
734 * - Internal changes so that intercepted and fast redirect pages
735 * are not replaced with an image.
736 * - Interceptors now have the option to send a binary page direct
737 * to the client. (i.e. ijb-send-banner uses this)
738 * - Implemented show-url-info interceptor. (Which is why I needed
739 * the above interceptors changes - a typical URL is
740 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
741 * The previous mechanism would not have intercepted that, and
742 * if it had been intercepted then it then it would have replaced
745 * Revision 1.9 2001/05/28 17:26:33 jongfoster
746 * Fixing segfault if last header was crunched.
747 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
748 * can use the cross-platform sprintf() instead.)
750 * Revision 1.8 2001/05/27 22:17:04 oes
752 * - re_process_buffer no longer writes the modified buffer
753 * to the client, which was very ugly. It now returns the
754 * buffer, which it is then written by chat.
756 * - content_length now adjusts the Content-Length: header
757 * for modified documents rather than crunch()ing it.
758 * (Length info in csp->content_length, which is 0 for
759 * unmodified documents)
761 * - For this to work, sed() is called twice when filtering.
763 * Revision 1.7 2001/05/27 13:19:06 oes
764 * Patched Joergs solution for the content-length in.
766 * Revision 1.6 2001/05/26 13:39:32 jongfoster
767 * Only crunches Content-Length header if applying RE filtering.
768 * Without this fix, Microsoft Windows Update wouldn't work.
770 * Revision 1.5 2001/05/26 00:28:36 jongfoster
771 * Automatic reloading of config file.
772 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
773 * Most of the global variables have been moved to a new
774 * struct configuration_spec, accessed through csp->config->globalname
775 * Most of the globals remaining are used by the Win32 GUI.
777 * Revision 1.4 2001/05/22 18:46:04 oes
779 * - Enabled filtering banners by size rather than URL
780 * by adding patterns that replace all standard banner
781 * sizes with the "Junkbuster" gif to the re_filterfile
783 * - Enabled filtering WebBugs by providing a pattern
784 * which kills all 1x1 images
786 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
787 * which is selected by the (nonstandard and therefore
788 * capital) letter 'U' in the option string.
789 * It causes the quantifiers to be ungreedy by default.
790 * Appending a ? turns back to greedy (!).
792 * - Added a new interceptor ijb-send-banner, which
793 * sends back the "Junkbuster" gif. Without imagelist or
794 * MSIE detection support, or if tinygif = 1, or the
795 * URL isn't recognized as an imageurl, a lame HTML
796 * explanation is sent instead.
798 * - Added new feature, which permits blocking remote
799 * script redirects and firing back a local redirect
801 * The feature is conditionally compiled, i.e. it
802 * can be disabled with --disable-fast-redirects,
803 * plus it must be activated by a "fast-redirects"
804 * line in the config file, has its own log level
805 * and of course wants to be displayed by show-proxy-args
806 * Note: Boy, all the #ifdefs in 1001 locations and
807 * all the fumbling with configure.in and acconfig.h
808 * were *way* more work than the feature itself :-(
810 * - Because a generic redirect template was needed for
811 * this, tinygif = 3 now uses the same.
813 * - Moved GIFs, and other static HTTP response templates
818 * - Removed some >400 CRs again (Jon, you really worked
821 * Revision 1.3 2001/05/20 01:21:20 jongfoster
822 * Version 2.9.4 checkin.
823 * - Merged popupfile and cookiefile, and added control over PCRS
824 * filtering, in new "permissionsfile".
825 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
826 * file error you now get a message box (in the Win32 GUI) rather
827 * than the program exiting with no explanation.
828 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
830 * - Removed tabs from "config"
831 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
832 * - Bumped up version number.
834 * Revision 1.2 2001/05/17 23:02:36 oes
835 * - Made referrer option accept 'L' as a substitute for '§'
837 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
838 * Initial import of version 2.9.3 source tree
841 *********************************************************************/
848 #include <sys/types.h>
858 * Convince GNU's libc to provide a strptime prototype.
861 #endif /*__GLIBC__ */
868 #if !defined(_WIN32) && !defined(__OS2__)
874 #ifdef FEATURE_PTHREAD
876 /* jcc.h is for mutex semapores only */
877 #endif /* def FEATURE_PTHREAD */
882 #include "jbsockets.h"
883 #include "miscutil.h"
888 #ifndef HAVE_STRPTIME
889 #include "strptime.h"
892 const char parsers_h_rcs[] = PARSERS_H_VERSION;
894 /* Fix a problem with Solaris. There should be no effect on other
896 * Solaris's isspace() is a macro which uses its argument directly
897 * as an array index. Therefore we need to make sure that high-bit
898 * characters generate +ve values, and ideally we also want to make
899 * the argument match the declared parameter type of "int".
901 * Why did they write a character function that can't take a simple
902 * "char" argument? Doh!
904 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
905 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
907 static char *get_header_line(struct iob *iob);
908 static jb_err scan_headers(struct client_state *csp);
909 static jb_err header_tagger(struct client_state *csp, char *header);
910 static jb_err parse_header_time(const char *header_time, time_t *result);
912 static jb_err crumble (struct client_state *csp, char **header);
913 static jb_err connection (struct client_state *csp, char **header);
914 static jb_err filter_header (struct client_state *csp, char **header);
915 static jb_err client_referrer (struct client_state *csp, char **header);
916 static jb_err client_uagent (struct client_state *csp, char **header);
917 static jb_err client_ua (struct client_state *csp, char **header);
918 static jb_err client_from (struct client_state *csp, char **header);
919 static jb_err client_send_cookie (struct client_state *csp, char **header);
920 static jb_err client_x_forwarded (struct client_state *csp, char **header);
921 static jb_err client_accept_encoding (struct client_state *csp, char **header);
922 static jb_err client_te (struct client_state *csp, char **header);
923 static jb_err client_max_forwards (struct client_state *csp, char **header);
924 static jb_err client_host (struct client_state *csp, char **header);
925 static jb_err client_if_modified_since (struct client_state *csp, char **header);
926 static jb_err client_accept_language (struct client_state *csp, char **header);
927 static jb_err client_if_none_match (struct client_state *csp, char **header);
928 static jb_err crunch_client_header (struct client_state *csp, char **header);
929 static jb_err client_x_filter (struct client_state *csp, char **header);
930 static jb_err client_range (struct client_state *csp, char **header);
931 static jb_err server_set_cookie (struct client_state *csp, char **header);
932 static jb_err server_content_type (struct client_state *csp, char **header);
933 static jb_err server_content_length (struct client_state *csp, char **header);
934 static jb_err server_content_md5 (struct client_state *csp, char **header);
935 static jb_err server_content_encoding (struct client_state *csp, char **header);
936 static jb_err server_transfer_coding (struct client_state *csp, char **header);
937 static jb_err server_http (struct client_state *csp, char **header);
938 static jb_err crunch_server_header (struct client_state *csp, char **header);
939 static jb_err server_last_modified (struct client_state *csp, char **header);
940 static jb_err server_content_disposition(struct client_state *csp, char **header);
942 static jb_err client_host_adder (struct client_state *csp);
943 static jb_err client_xtra_adder (struct client_state *csp);
944 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
945 static jb_err connection_close_adder (struct client_state *csp);
947 static jb_err create_forged_referrer(char **header, const char *hostport);
948 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
949 static jb_err handle_conditional_hide_referrer_parameter(char **header,
950 const char *host, const int parameter_conditional_block);
953 * List of functions to run on a list of headers.
957 /** The header prefix to match */
960 /** The length of the prefix to match */
963 /** The function to apply to this line */
964 const parser_func_ptr parser;
967 static const struct parsers client_patterns[] = {
968 { "referer:", 8, client_referrer },
969 { "user-agent:", 11, client_uagent },
970 { "ua-", 3, client_ua },
971 { "from:", 5, client_from },
972 { "cookie:", 7, client_send_cookie },
973 { "x-forwarded-for:", 16, client_x_forwarded },
974 { "Accept-Encoding:", 16, client_accept_encoding },
975 { "TE:", 3, client_te },
976 { "Host:", 5, client_host },
977 { "if-modified-since:", 18, client_if_modified_since },
978 { "Keep-Alive:", 11, crumble },
979 { "connection:", 11, connection },
980 { "proxy-connection:", 17, crumble },
981 { "max-forwards:", 13, client_max_forwards },
982 { "Accept-Language:", 16, client_accept_language },
983 { "if-none-match:", 14, client_if_none_match },
984 { "Range:", 6, client_range },
985 { "Request-Range:", 14, client_range },
986 { "If-Range:", 9, client_range },
987 { "X-Filter:", 9, client_x_filter },
988 { "*", 0, crunch_client_header },
989 { "*", 0, filter_header },
993 static const struct parsers server_patterns[] = {
994 { "HTTP/", 5, server_http },
995 { "set-cookie:", 11, server_set_cookie },
996 { "connection:", 11, connection },
997 { "Content-Type:", 13, server_content_type },
998 { "Content-MD5:", 12, server_content_md5 },
999 { "Content-Encoding:", 17, server_content_encoding },
1000 { "Transfer-Encoding:", 18, server_transfer_coding },
1001 { "Keep-Alive:", 11, crumble },
1002 { "content-disposition:", 20, server_content_disposition },
1003 { "Last-Modified:", 14, server_last_modified },
1004 { "*", 0, crunch_server_header },
1005 { "*", 0, filter_header },
1009 static const add_header_func_ptr add_client_headers[] = {
1011 client_x_forwarded_for_adder,
1013 /* Temporarily disabled: client_accept_encoding_adder, */
1014 connection_close_adder,
1018 static const add_header_func_ptr add_server_headers[] = {
1019 connection_close_adder,
1023 /*********************************************************************
1025 * Function : flush_socket
1027 * Description : Write any pending "buffered" content.
1030 * 1 : fd = file descriptor of the socket to read
1031 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1033 * Returns : On success, the number of bytes written are returned (zero
1034 * indicates nothing was written). On error, -1 is returned,
1035 * and errno is set appropriately. If count is zero and the
1036 * file descriptor refers to a regular file, 0 will be
1037 * returned without causing any other effect. For a special
1038 * file, the results are not portable.
1040 *********************************************************************/
1041 int flush_socket(jb_socket fd, struct iob *iob)
1043 int len = iob->eod - iob->cur;
1050 if (write_socket(fd, iob->cur, (size_t)len))
1054 iob->eod = iob->cur = iob->buf;
1060 /*********************************************************************
1062 * Function : add_to_iob
1064 * Description : Add content to the buffered page, expanding the
1065 * buffer if necessary.
1068 * 1 : csp = Current client state (buffers, headers, etc...)
1069 * 2 : buf = holds the content to be added to the page
1070 * 3 : n = number of bytes to be added
1072 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1073 * or buffer limit reached.
1075 *********************************************************************/
1076 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1078 struct iob *iob = csp->iob;
1079 size_t used, offset, need, want;
1082 if (n <= 0) return JB_ERR_OK;
1084 used = (size_t)(iob->eod - iob->buf);
1085 offset = (size_t)(iob->cur - iob->buf);
1086 need = used + (size_t)n + 1;
1089 * If the buffer can't hold the new data, extend it first.
1090 * Use the next power of two if possible, else use the actual need.
1092 if (need > csp->config->buffer_limit)
1094 log_error(LOG_LEVEL_INFO, "Buffer limit reached while extending the buffer (iob)");
1095 return JB_ERR_MEMORY;
1098 if (need > iob->size)
1100 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1102 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1106 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1112 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1113 return JB_ERR_MEMORY;
1116 /* Update the iob pointers */
1117 iob->cur = p + offset;
1118 iob->eod = p + used;
1122 /* copy the new data into the iob buffer */
1123 memcpy(iob->eod, buf, (size_t)n);
1125 /* point to the end of the data */
1128 /* null terminate == cheap insurance */
1137 /*********************************************************************
1139 * Function : decompress_iob
1141 * Description : Decompress buffered page, expanding the
1142 * buffer as necessary. csp->iob->cur
1143 * should point to the the beginning of the
1144 * compressed data block.
1147 * 1 : csp = Current client state (buffers, headers, etc...)
1149 * Returns : JB_ERR_OK on success,
1150 * JB_ERR_MEMORY if out-of-memory limit reached, and
1151 * JB_ERR_COMPRESS if error decompressing buffer.
1153 *********************************************************************/
1154 jb_err decompress_iob(struct client_state *csp)
1156 char *buf; /* new, uncompressed buffer */
1157 char *cur; /* Current iob position (to keep the original
1158 * iob->cur unmodified if we return early) */
1159 size_t bufsize; /* allocated size of the new buffer */
1160 size_t old_size; /* Content size before decompression */
1161 size_t skip_size; /* Number of bytes at the beginning of the iob
1162 that we should NOT decompress. */
1163 int status; /* return status of the inflate() call */
1164 z_stream zstr; /* used by calls to zlib */
1166 assert(csp->iob->cur - csp->iob->buf > 0);
1167 assert(csp->iob->eod - csp->iob->cur > 0);
1169 bufsize = csp->iob->size;
1170 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1171 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1173 cur = csp->iob->cur;
1178 * This is to protect the parsing of gzipped data,
1179 * but it should(?) be valid for deflated data also.
1181 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1182 return JB_ERR_COMPRESS;
1185 if (csp->content_type & CT_GZIP)
1188 * Our task is slightly complicated by the facts that data
1189 * compressed by gzip does not include a zlib header, and
1190 * that there is no easily accessible interface in zlib to
1191 * handle a gzip header. We strip off the gzip header by
1192 * hand, and later inform zlib not to expect a header.
1196 * Strip off the gzip header. Please see RFC 1952 for more
1197 * explanation of the appropriate fields.
1199 if ((*cur++ != (char)0x1f)
1200 || (*cur++ != (char)0x8b)
1201 || (*cur++ != Z_DEFLATED))
1203 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1204 return JB_ERR_COMPRESS;
1210 * XXX: These magic numbers should be replaced
1211 * with macros to give a better idea what they do.
1215 /* The gzip header has reserved bits set; bail out. */
1216 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1217 return JB_ERR_COMPRESS;
1221 /* Skip extra fields if necessary. */
1225 * Skip a given number of bytes, specified
1226 * as a 16-bit little-endian value.
1229 * XXX: This code used to be:
1231 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1233 * which I had to change into:
1235 * cur += *cur++ + (*cur++ << 8);
1237 * at which point gcc43 finally noticed that the value
1238 * of cur is undefined (it depends on which of the
1239 * summands is evaluated first).
1241 * I haven't come across a site where this
1242 * code is actually executed yet, but I hope
1246 skip_bytes = *cur++;
1247 skip_bytes = *cur++ << 8;
1249 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1252 * The number of bytes to skip should be positive
1253 * and we'd like to stay in the buffer.
1255 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1257 log_error(LOG_LEVEL_ERROR,
1258 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1260 return JB_ERR_COMPRESS;
1262 log_error(LOG_LEVEL_INFO,
1263 "Skipping %d bytes for gzip compression. Does this sound right?",
1268 /* Skip the filename if necessary. */
1271 /* A null-terminated string is supposed to follow. */
1272 while (*cur++ && (cur < csp->iob->eod));
1276 /* Skip the comment if necessary. */
1279 /* A null-terminated string is supposed to follow. */
1280 while (*cur++ && (cur < csp->iob->eod));
1283 /* Skip the CRC if necessary. */
1289 if (cur >= csp->iob->eod)
1292 * If the current position pointer reached or passed
1293 * the buffer end, we were obviously tricked to skip
1296 log_error(LOG_LEVEL_ERROR,
1297 "Malformed gzip header detected. Aborting decompression.");
1298 return JB_ERR_COMPRESS;
1302 else if (csp->content_type & CT_DEFLATE)
1305 * XXX: The debug level should be lowered
1306 * before the next stable release.
1308 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1310 * In theory (that is, according to RFC 1950), deflate-compressed
1311 * data should begin with a two-byte zlib header and have an
1312 * adler32 checksum at the end. It seems that in practice only
1313 * the raw compressed data is sent. Note that this means that
1314 * we are not RFC 1950-compliant here, but the advantage is that
1315 * this actually works. :)
1317 * We add a dummy null byte to tell zlib where the data ends,
1318 * and later inform it not to expect a header.
1320 * Fortunately, add_to_iob() has thoughtfully null-terminated
1321 * the buffer; we can just increment the end pointer to include
1328 log_error(LOG_LEVEL_ERROR,
1329 "Unable to determine compression format for decompression");
1330 return JB_ERR_COMPRESS;
1333 /* Set up the fields required by zlib. */
1334 zstr.next_in = (Bytef *)cur;
1335 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1336 zstr.zalloc = Z_NULL;
1337 zstr.zfree = Z_NULL;
1338 zstr.opaque = Z_NULL;
1341 * Passing -MAX_WBITS to inflateInit2 tells the library
1342 * that there is no zlib header.
1344 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1346 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1347 return JB_ERR_COMPRESS;
1351 * Next, we allocate new storage for the inflated data.
1352 * We don't modify the existing iob yet, so in case there
1353 * is error in decompression we can recover gracefully.
1355 buf = zalloc(bufsize);
1358 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1359 return JB_ERR_MEMORY;
1362 assert(bufsize >= skip_size);
1363 memcpy(buf, csp->iob->buf, skip_size);
1364 zstr.avail_out = bufsize - skip_size;
1365 zstr.next_out = (Bytef *)buf + skip_size;
1367 /* Try to decompress the whole stream in one shot. */
1368 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1370 /* We need to allocate more memory for the output buffer. */
1372 char *tmpbuf; /* used for realloc'ing the buffer */
1373 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1376 * If zlib wants more data then there's a problem, because
1377 * the complete compressed file should have been buffered.
1379 if (0 == zstr.avail_in)
1381 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1382 return JB_ERR_COMPRESS;
1386 * If we tried the limit and still didn't have enough
1387 * memory, just give up.
1389 if (bufsize == csp->config->buffer_limit)
1391 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1392 return JB_ERR_MEMORY;
1395 /* Try doubling the buffer size each time. */
1398 /* Don't exceed the buffer limit. */
1399 if (bufsize > csp->config->buffer_limit)
1401 bufsize = csp->config->buffer_limit;
1404 /* Try to allocate the new buffer. */
1405 tmpbuf = realloc(buf, bufsize);
1408 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1410 return JB_ERR_MEMORY;
1414 char *oldnext_out = (char *)zstr.next_out;
1417 * Update the fields for inflate() to use the new
1418 * buffer, which may be in a location different from
1421 zstr.avail_out += bufsize - oldbufsize;
1422 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1425 * Compare with an uglier method of calculating these values
1426 * that doesn't require the extra oldbufsize variable.
1428 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1429 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1430 assert(zstr.avail_out > 0);
1436 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1438 log_error(LOG_LEVEL_ERROR,
1439 "Inconsistent stream state after decompression: %s", zstr.msg);
1441 * XXX: Intentionally no return.
1443 * According to zlib.h, Z_STREAM_ERROR is returned
1444 * "if the stream state was inconsistent".
1446 * I assume in this case inflate()'s status
1447 * would also be something different than Z_STREAM_END
1448 * so this check should be redundant, but lets see.
1452 if (status != Z_STREAM_END)
1454 /* We failed to decompress the stream. */
1455 log_error(LOG_LEVEL_ERROR,
1456 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1457 return JB_ERR_COMPRESS;
1461 * Finally, we can actually update the iob, since the
1462 * decompression was successful. First, free the old
1465 freez(csp->iob->buf);
1467 /* Now, update the iob to use the new buffer. */
1468 csp->iob->buf = buf;
1469 csp->iob->cur = csp->iob->buf + skip_size;
1470 csp->iob->eod = (char *)zstr.next_out;
1471 csp->iob->size = bufsize;
1474 * Make sure the new uncompressed iob obeys some minimal
1475 * consistency conditions.
1477 if ((csp->iob->buf < csp->iob->cur)
1478 && (csp->iob->cur <= csp->iob->eod)
1479 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1481 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1484 log_error(LOG_LEVEL_RE_FILTER,
1485 "Decompression successful. Old size: %d, new size: %d.",
1486 old_size, new_size);
1490 /* zlib thinks this is OK, so lets do the same. */
1491 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1496 /* It seems that zlib did something weird. */
1497 log_error(LOG_LEVEL_ERROR,
1498 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1499 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1500 csp->iob->eod, csp->iob->buf + csp->iob->size);
1501 return JB_ERR_COMPRESS;
1507 #endif /* defined(FEATURE_ZLIB) */
1510 /*********************************************************************
1512 * Function : string_move
1514 * Description : memmove wrapper to move the last part of a string
1515 * towards the beginning, overwriting the part in
1516 * the middle. strlcpy() can't be used here as the
1520 * 1 : dst = Destination to overwrite
1521 * 2 : src = Source to move.
1525 *********************************************************************/
1526 static void string_move(char *dst, char *src)
1530 /* +1 to copy the terminating nul as well. */
1531 memmove(dst, src, strlen(src)+1);
1535 /*********************************************************************
1537 * Function : normalize_lws
1539 * Description : Reduces unquoted linear white space in headers
1540 * to a single space in accordance with RFC 2616 2.2.
1541 * This simplifies parsing and filtering later on.
1543 * XXX: Remove log messages before
1544 * the next stable release?
1547 * 1 : header = A header with linear white space to reduce.
1551 *********************************************************************/
1552 static void normalize_lws(char *header)
1558 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1562 while (ijb_isspace(*q))
1566 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1567 string_move(p+1, q);
1572 log_error(LOG_LEVEL_HEADER,
1573 "Converting tab to space in '%s'", header);
1578 char *end_of_token = strstr(p+1, "\"");
1580 if (NULL != end_of_token)
1582 /* Don't mess with quoted text. */
1587 log_error(LOG_LEVEL_HEADER,
1588 "Ignoring single quote in '%s'", header);
1594 p = strchr(header, ':');
1595 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1598 * There's still space before the colon.
1601 string_move(p-1, p);
1606 /*********************************************************************
1608 * Function : get_header
1610 * Description : This (odd) routine will parse the csp->iob
1611 * to get the next complete header.
1614 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1616 * Returns : Any one of the following:
1618 * 1) a pointer to a dynamically allocated string that contains a header line
1619 * 2) NULL indicating that the end of the header was reached
1620 * 3) "" indicating that the end of the iob was reached before finding
1621 * a complete header line.
1623 *********************************************************************/
1624 char *get_header(struct iob *iob)
1628 header = get_header_line(iob);
1630 if ((header == NULL) || (*header == '\0'))
1633 * No complete header read yet, tell the client.
1638 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1641 * Header spans multiple lines, append the next one.
1643 char *continued_header;
1645 continued_header = get_header_line(iob);
1646 if ((continued_header == NULL) || (*continued_header == '\0'))
1649 * No complete header read yet, return what we got.
1650 * XXX: Should "unread" header instead.
1652 log_error(LOG_LEVEL_INFO,
1653 "Failed to read a multi-line header properly: '%s'",
1658 if (JB_ERR_OK != string_join(&header, continued_header))
1660 log_error(LOG_LEVEL_FATAL,
1661 "Out of memory while appending multiple headers.");
1665 /* XXX: remove before next stable release. */
1666 log_error(LOG_LEVEL_HEADER,
1667 "Merged multiple header lines to: '%s'",
1672 normalize_lws(header);
1679 /*********************************************************************
1681 * Function : get_header_line
1683 * Description : This (odd) routine will parse the csp->iob
1684 * to get the next header line.
1687 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1689 * Returns : Any one of the following:
1691 * 1) a pointer to a dynamically allocated string that contains a header line
1692 * 2) NULL indicating that the end of the header was reached
1693 * 3) "" indicating that the end of the iob was reached before finding
1694 * a complete header line.
1696 *********************************************************************/
1697 static char *get_header_line(struct iob *iob)
1701 if ((iob->cur == NULL)
1702 || ((p = strchr(iob->cur, '\n')) == NULL))
1704 return(""); /* couldn't find a complete header */
1709 ret = strdup(iob->cur);
1712 /* FIXME No way to handle error properly */
1713 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1718 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1720 /* is this a blank line (i.e. the end of the header) ? */
1732 /*********************************************************************
1734 * Function : get_header_value
1736 * Description : Get the value of a given header from a chained list
1737 * of header lines or return NULL if no such header is
1738 * present in the list.
1741 * 1 : header_list = pointer to list
1742 * 2 : header_name = string with name of header to look for.
1743 * Trailing colon required, capitalization
1746 * Returns : NULL if not found, else value of header
1748 *********************************************************************/
1749 char *get_header_value(const struct list *header_list, const char *header_name)
1751 struct list_entry *cur_entry;
1755 assert(header_list);
1756 assert(header_name);
1757 length = strlen(header_name);
1759 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1763 if (!strncmpic(cur_entry->str, header_name, length))
1766 * Found: return pointer to start of value
1768 ret = cur_entry->str + length;
1769 while (*ret && ijb_isspace(*ret)) ret++;
1783 /*********************************************************************
1785 * Function : scan_headers
1787 * Description : Scans headers, applies tags and updates action bits.
1790 * 1 : csp = Current client state (buffers, headers, etc...)
1792 * Returns : JB_ERR_OK
1794 *********************************************************************/
1795 static jb_err scan_headers(struct client_state *csp)
1797 struct list_entry *h; /* Header */
1798 jb_err err = JB_ERR_OK;
1800 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1802 /* Header crunch()ed in previous run? -> ignore */
1803 if (h->str == NULL) continue;
1804 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1805 err = header_tagger(csp, h->str);
1812 /*********************************************************************
1816 * Description : add, delete or modify lines in the HTTP header streams.
1817 * On entry, it receives a linked list of headers space
1818 * that was allocated dynamically (both the list nodes
1819 * and the header contents).
1821 * As a side effect it frees the space used by the original
1825 * 1 : csp = Current client state (buffers, headers, etc...)
1826 * 2 : filter_server_headers = Boolean to switch between
1827 * server and header filtering.
1829 * Returns : JB_ERR_OK in case off success, or
1830 * JB_ERR_MEMORY on out-of-memory error.
1832 *********************************************************************/
1833 jb_err sed(struct client_state *csp, int filter_server_headers)
1835 /* XXX: use more descriptive names. */
1836 struct list_entry *p;
1837 const struct parsers *v;
1838 const add_header_func_ptr *f;
1839 jb_err err = JB_ERR_OK;
1841 if (filter_server_headers)
1843 v = server_patterns;
1844 f = add_server_headers;
1848 v = client_patterns;
1849 f = add_client_headers;
1854 while ((err == JB_ERR_OK) && (v->str != NULL))
1856 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1858 /* Header crunch()ed in previous run? -> ignore */
1859 if (p->str == NULL) continue;
1861 /* Does the current parser handle this header? */
1862 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1863 (v->len == CHECK_EVERY_HEADER_REMAINING))
1865 err = v->parser(csp, &(p->str));
1871 /* place additional headers on the csp->headers list */
1872 while ((err == JB_ERR_OK) && (*f))
1882 /*********************************************************************
1884 * Function : update_server_headers
1886 * Description : Updates server headers after the body has been modified.
1889 * 1 : csp = Current client state (buffers, headers, etc...)
1891 * Returns : JB_ERR_OK in case off success, or
1892 * JB_ERR_MEMORY on out-of-memory error.
1894 *********************************************************************/
1895 jb_err update_server_headers(struct client_state *csp)
1897 jb_err err = JB_ERR_OK;
1899 static const struct parsers server_patterns_light[] = {
1900 { "Content-Length:", 15, server_content_length },
1901 { "Transfer-Encoding:", 18, server_transfer_coding },
1903 { "Content-Encoding:", 17, server_content_encoding },
1904 #endif /* def FEATURE_ZLIB */
1908 if (strncmpic(csp->http->cmd, "HEAD", 4))
1910 const struct parsers *v;
1911 struct list_entry *p;
1913 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1915 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1917 /* Header crunch()ed in previous run? -> ignore */
1918 if (p->str == NULL) continue;
1920 /* Does the current parser handle this header? */
1921 if (strncmpic(p->str, v->str, v->len) == 0)
1923 err = v->parser(csp, (char **)&(p->str));
1933 /*********************************************************************
1935 * Function : header_tagger
1937 * Description : Executes all text substitutions from applying
1938 * tag actions and saves the result as tag.
1940 * XXX: Shares enough code with filter_header() and
1941 * pcrs_filter_response() to warrant some helper functions.
1944 * 1 : csp = Current client state (buffers, headers, etc...)
1945 * 2 : header = Header that is used as tagger input
1947 * Returns : JB_ERR_OK on success and always succeeds
1949 *********************************************************************/
1950 static jb_err header_tagger(struct client_state *csp, char *header)
1952 int wanted_filter_type;
1953 int multi_action_index;
1957 struct file_list *fl;
1958 struct re_filterfile_spec *b;
1959 struct list_entry *tag_name;
1961 int found_filters = 0;
1962 const size_t header_length = strlen(header);
1964 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1966 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1967 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1971 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1972 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1975 /* Check if there are any filters */
1976 for (i = 0; i < MAX_AF_FILES; i++)
1989 if (0 == found_filters)
1991 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1992 "tagging enabled, but no taggers available.");
1996 for (i = 0; i < MAX_AF_FILES; i++)
1999 if ((NULL == fl) || (NULL == fl->f))
2002 * Either there are no filter files
2003 * left, or this filter file just
2004 * contains no valid filters.
2006 * Continue to be sure we don't miss
2007 * valid filter files that are chained
2008 * after empty or invalid ones.
2013 /* For all filters, */
2014 for (b = fl->f; b; b = b->next)
2016 if (b->type != wanted_filter_type)
2018 /* skip the ones we don't care about, */
2021 /* leaving only taggers that could apply, of which we use the ones, */
2022 for (tag_name = csp->action->multi[multi_action_index]->first;
2023 NULL != tag_name; tag_name = tag_name->next)
2025 /* that do apply, and */
2026 if (strcmp(b->name, tag_name->str) == 0)
2028 char *modified_tag = NULL;
2030 size_t size = header_length;
2031 pcrs_job *joblist = b->joblist;
2033 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2035 if (NULL == joblist)
2037 log_error(LOG_LEVEL_RE_FILTER,
2038 "Tagger %s has empty joblist. Nothing to do.", b->name);
2042 /* execute their pcrs_joblist on the header. */
2043 for (job = joblist; NULL != job; job = job->next)
2045 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2049 /* Success, continue with the modified version. */
2058 /* Tagger doesn't match */
2061 /* Regex failure, log it but continue anyway. */
2062 log_error(LOG_LEVEL_ERROR,
2063 "Problems with tagger \'%s\' and header \'%s\': %s",
2064 b->name, *header, pcrs_strerror(hits));
2066 freez(modified_tag);
2070 if (b->dynamic) pcrs_free_joblist(joblist);
2072 /* If this tagger matched */
2078 * There is to technical limitation which makes
2079 * it impossible to use empty tags, but I assume
2080 * no one would do it intentionally.
2083 log_error(LOG_LEVEL_INFO,
2084 "Tagger \'%s\' created an empty tag. Ignored.",
2089 if (!list_contains_item(csp->tags, tag))
2091 if (JB_ERR_OK != enlist(csp->tags, tag))
2093 log_error(LOG_LEVEL_ERROR,
2094 "Insufficient memory to add tag \'%s\', "
2095 "based on tagger \'%s\' and header \'%s\'",
2096 tag, b->name, *header);
2100 char *action_message;
2102 * update the action bits right away, to make
2103 * tagging based on tags set by earlier taggers
2104 * of the same kind possible.
2106 if (update_action_bits_for_tag(csp, tag))
2108 action_message = "Action bits updated accordingly.";
2112 action_message = "No action bits update necessary.";
2115 log_error(LOG_LEVEL_HEADER,
2116 "Tagger \'%s\' added tag \'%s\'. %s",
2117 b->name, tag, action_message);
2122 /* XXX: Is this log-worthy? */
2123 log_error(LOG_LEVEL_HEADER,
2124 "Tagger \'%s\' didn't add tag \'%s\'. "
2125 "Tag already present", b->name, tag);
2128 } /* if the tagger matched */
2129 } /* if the tagger applies */
2130 } /* for every tagger that could apply */
2131 } /* for all filters */
2132 } /* for all filter files */
2137 /* here begins the family of parser functions that reformat header lines */
2139 /*********************************************************************
2141 * Function : filter_header
2143 * Description : Executes all text substitutions from all applying
2144 * +(server|client)-header-filter actions on the header.
2145 * Most of the code was copied from pcrs_filter_response,
2146 * including the rather short variable names
2149 * 1 : csp = Current client state (buffers, headers, etc...)
2150 * 2 : header = On input, pointer to header to modify.
2151 * On output, pointer to the modified header, or NULL
2152 * to remove the header. This function frees the
2153 * original string if necessary.
2155 * Returns : JB_ERR_OK on success and always succeeds
2157 *********************************************************************/
2158 static jb_err filter_header(struct client_state *csp, char **header)
2162 size_t size = strlen(*header);
2164 char *newheader = NULL;
2167 struct file_list *fl;
2168 struct re_filterfile_spec *b;
2169 struct list_entry *filtername;
2171 int i, found_filters = 0;
2172 int wanted_filter_type;
2173 int multi_action_index;
2175 if (csp->flags & CSP_FLAG_NO_FILTERING)
2180 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2182 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2183 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2187 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2188 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2192 * Need to check the set of re_filterfiles...
2194 for (i = 0; i < MAX_AF_FILES; i++)
2207 if (0 == found_filters)
2209 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2210 "header filtering enabled, but no matching filters available.");
2214 for (i = 0; i < MAX_AF_FILES; i++)
2217 if ((NULL == fl) || (NULL == fl->f))
2220 * Either there are no filter files
2221 * left, or this filter file just
2222 * contains no valid filters.
2224 * Continue to be sure we don't miss
2225 * valid filter files that are chained
2226 * after empty or invalid ones.
2231 * For all applying +filter actions, look if a filter by that
2232 * name exists and if yes, execute its pcrs_joblist on the
2235 for (b = fl->f; b; b = b->next)
2237 if (b->type != wanted_filter_type)
2239 /* Skip other filter types */
2243 for (filtername = csp->action->multi[multi_action_index]->first;
2244 filtername ; filtername = filtername->next)
2246 if (strcmp(b->name, filtername->str) == 0)
2248 int current_hits = 0;
2249 pcrs_job *joblist = b->joblist;
2251 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2253 if (NULL == joblist)
2255 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2259 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2260 *header, size, b->name);
2262 /* Apply all jobs from the joblist */
2263 for (job = joblist; NULL != job; job = job->next)
2265 matches = pcrs_execute(job, *header, size, &newheader, &size);
2268 current_hits += matches;
2269 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2271 *header = newheader;
2273 else if ( 0 == matches )
2275 /* Filter doesn't change header */
2281 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2282 *header, b->name, pcrs_strerror(matches));
2283 if (newheader != NULL)
2285 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2291 if (b->dynamic) pcrs_free_joblist(joblist);
2293 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2294 hits += current_hits;
2301 * Additionally checking for hits is important because if
2302 * the continue hack is triggered, server headers can
2303 * arrive empty to separate multiple heads from each other.
2305 if ((0 == size) && hits)
2307 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2315 /*********************************************************************
2317 * Function : connection
2319 * Description : Makes sure that the value of the Connection: header
2320 * is "close" and signals connection_close_adder
2324 * 1 : csp = Current client state (buffers, headers, etc...)
2325 * 2 : header = On input, pointer to header to modify.
2326 * On output, pointer to the modified header, or NULL
2327 * to remove the header. This function frees the
2328 * original string if necessary.
2330 * Returns : JB_ERR_OK on success, or
2331 * JB_ERR_MEMORY on out-of-memory error.
2333 *********************************************************************/
2334 static jb_err connection(struct client_state *csp, char **header)
2336 char *old_header = *header;
2338 /* Do we have a 'Connection: close' header? */
2339 if (strcmpic(*header, "Connection: close"))
2341 /* No, create one */
2342 *header = strdup("Connection: close");
2345 return JB_ERR_MEMORY;
2347 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2351 /* Signal connection_close_adder() to return early. */
2352 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2354 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2358 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2365 /*********************************************************************
2367 * Function : crumble
2369 * Description : This is called if a header matches a pattern to "crunch"
2372 * 1 : csp = Current client state (buffers, headers, etc...)
2373 * 2 : header = On input, pointer to header to modify.
2374 * On output, pointer to the modified header, or NULL
2375 * to remove the header. This function frees the
2376 * original string if necessary.
2378 * Returns : JB_ERR_OK on success, or
2379 * JB_ERR_MEMORY on out-of-memory error.
2381 *********************************************************************/
2382 static jb_err crumble(struct client_state *csp, char **header)
2384 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2390 /*********************************************************************
2392 * Function : crunch_server_header
2394 * Description : Crunch server header if it matches a string supplied by the
2395 * user. Called from `sed'.
2398 * 1 : csp = Current client state (buffers, headers, etc...)
2399 * 2 : header = On input, pointer to header to modify.
2400 * On output, pointer to the modified header, or NULL
2401 * to remove the header. This function frees the
2402 * original string if necessary.
2404 * Returns : JB_ERR_OK on success and always succeeds
2406 *********************************************************************/
2407 static jb_err crunch_server_header(struct client_state *csp, char **header)
2409 const char *crunch_pattern;
2411 /* Do we feel like crunching? */
2412 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2414 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2416 /* Is the current header the lucky one? */
2417 if (strstr(*header, crunch_pattern))
2419 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2428 /*********************************************************************
2430 * Function : server_content_type
2432 * Description : Set the content-type for filterable types (text/.*,
2433 * .*xml.*, javascript and image/gif) unless filtering has been
2434 * forbidden (CT_TABOO) while parsing earlier headers.
2435 * NOTE: Since text/plain is commonly used by web servers
2436 * for files whose correct type is unknown, we don't
2437 * set CT_TEXT for it.
2440 * 1 : csp = Current client state (buffers, headers, etc...)
2441 * 2 : header = On input, pointer to header to modify.
2442 * On output, pointer to the modified header, or NULL
2443 * to remove the header. This function frees the
2444 * original string if necessary.
2446 * Returns : JB_ERR_OK on success, or
2447 * JB_ERR_MEMORY on out-of-memory error.
2449 *********************************************************************/
2450 static jb_err server_content_type(struct client_state *csp, char **header)
2452 /* Remove header if it isn't the first Content-Type header */
2453 if ((csp->content_type & CT_DECLARED))
2456 * Another, slightly slower, way to see if
2457 * we already parsed another Content-Type header.
2459 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2461 log_error(LOG_LEVEL_ERROR,
2462 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2470 * Signal that the Content-Type has been set.
2472 csp->content_type |= CT_DECLARED;
2474 if (!(csp->content_type & CT_TABOO))
2477 * XXX: The assumption that text/plain is a sign of
2478 * binary data seems to be somewhat unreasonable nowadays
2479 * and should be dropped after 3.0.8 is out.
2481 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2482 || strstr(*header, "xml")
2483 || strstr(*header, "application/x-javascript"))
2485 csp->content_type |= CT_TEXT;
2487 else if (strstr(*header, "image/gif"))
2489 csp->content_type |= CT_GIF;
2494 * Are we messing with the content type?
2496 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2499 * Make sure the user doesn't accidently
2500 * change the content type of binary documents.
2502 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2505 *header = strdup("Content-Type: ");
2506 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2510 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2511 return JB_ERR_MEMORY;
2513 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2517 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2518 "It doesn't look like a content type that should be filtered. "
2519 "Enable force-text-mode if you know what you're doing.", *header);
2527 /*********************************************************************
2529 * Function : server_transfer_coding
2531 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2532 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2533 * - Remove header if body was chunked but has been
2534 * de-chunked for filtering.
2537 * 1 : csp = Current client state (buffers, headers, etc...)
2538 * 2 : header = On input, pointer to header to modify.
2539 * On output, pointer to the modified header, or NULL
2540 * to remove the header. This function frees the
2541 * original string if necessary.
2543 * Returns : JB_ERR_OK on success, or
2544 * JB_ERR_MEMORY on out-of-memory error.
2546 *********************************************************************/
2547 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2550 * Turn off pcrs and gif filtering if body compressed
2552 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2556 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2558 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2559 csp->http->cmd, *header);
2560 #endif /* def FEATURE_ZLIB */
2561 csp->content_type = CT_TABOO;
2565 * Raise flag if body chunked
2567 if (strstr(*header, "chunked"))
2569 csp->flags |= CSP_FLAG_CHUNKED;
2572 * If the body was modified, it has been de-chunked first
2573 * and the header must be removed.
2575 * FIXME: If there is more than one transfer encoding,
2576 * only the "chunked" part should be removed here.
2578 if (csp->flags & CSP_FLAG_MODIFIED)
2580 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2589 /*********************************************************************
2591 * Function : server_content_encoding
2593 * Description : This function is run twice for each request,
2594 * unless FEATURE_ZLIB and filtering are disabled.
2596 * The first run is used to check if the content
2597 * is compressed, if FEATURE_ZLIB is disabled
2598 * filtering is then disabled as well, if FEATURE_ZLIB
2599 * is enabled the content is marked for decompression.
2601 * The second run is used to remove the Content-Encoding
2602 * header if the decompression was successful.
2605 * 1 : csp = Current client state (buffers, headers, etc...)
2606 * 2 : header = On input, pointer to header to modify.
2607 * On output, pointer to the modified header, or NULL
2608 * to remove the header. This function frees the
2609 * original string if necessary.
2611 * Returns : JB_ERR_OK on success, or
2612 * JB_ERR_MEMORY on out-of-memory error.
2614 *********************************************************************/
2615 static jb_err server_content_encoding(struct client_state *csp, char **header)
2618 if ((csp->flags & CSP_FLAG_MODIFIED)
2619 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2622 * We successfully decompressed the content,
2623 * and have to clean the header now, so the
2624 * client no longer expects compressed data..
2626 * XXX: There is a difference between cleaning
2627 * and removing it completely.
2629 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2632 else if (strstr(*header, "gzip"))
2634 /* Mark for gzip decompression */
2635 csp->content_type |= CT_GZIP;
2637 else if (strstr(*header, "deflate"))
2639 /* Mark for zlib decompression */
2640 csp->content_type |= CT_DEFLATE;
2642 else if (strstr(*header, "compress"))
2645 * We can't decompress this; therefore we can't filter
2648 csp->content_type |= CT_TABOO;
2650 #else /* !defined(FEATURE_ZLIB) */
2651 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2654 * Body is compressed, turn off pcrs and gif filtering.
2656 csp->content_type |= CT_TABOO;
2659 * Log a warning if the user expects the content to be filtered.
2661 if ((csp->rlist != NULL) &&
2662 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2664 log_error(LOG_LEVEL_INFO,
2665 "Compressed content detected, content filtering disabled. "
2666 "Consider recompiling Privoxy with zlib support or "
2667 "enable the prevent-compression action.");
2670 #endif /* defined(FEATURE_ZLIB) */
2677 /*********************************************************************
2679 * Function : server_content_length
2681 * Description : Adjust Content-Length header if we modified
2685 * 1 : csp = Current client state (buffers, headers, etc...)
2686 * 2 : header = On input, pointer to header to modify.
2687 * On output, pointer to the modified header, or NULL
2688 * to remove the header. This function frees the
2689 * original string if necessary.
2691 * Returns : JB_ERR_OK on success, or
2692 * JB_ERR_MEMORY on out-of-memory error.
2694 *********************************************************************/
2695 static jb_err server_content_length(struct client_state *csp, char **header)
2697 const size_t max_header_length = 80;
2699 /* Regenerate header if the content was modified. */
2700 if (csp->flags & CSP_FLAG_MODIFIED)
2703 *header = (char *) zalloc(max_header_length);
2704 if (*header == NULL)
2706 return JB_ERR_MEMORY;
2709 snprintf(*header, max_header_length, "Content-Length: %d",
2710 (int)csp->content_length);
2711 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2712 (int)csp->content_length);
2719 /*********************************************************************
2721 * Function : server_content_md5
2723 * Description : Crumble any Content-MD5 headers if the document was
2724 * modified. FIXME: Should we re-compute instead?
2727 * 1 : csp = Current client state (buffers, headers, etc...)
2728 * 2 : header = On input, pointer to header to modify.
2729 * On output, pointer to the modified header, or NULL
2730 * to remove the header. This function frees the
2731 * original string if necessary.
2733 * Returns : JB_ERR_OK on success, or
2734 * JB_ERR_MEMORY on out-of-memory error.
2736 *********************************************************************/
2737 static jb_err server_content_md5(struct client_state *csp, char **header)
2739 if (csp->flags & CSP_FLAG_MODIFIED)
2741 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2749 /*********************************************************************
2751 * Function : server_content_disposition
2753 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2754 * Called from `sed'.
2757 * 1 : csp = Current client state (buffers, headers, etc...)
2758 * 2 : header = On input, pointer to header to modify.
2759 * On output, pointer to the modified header, or NULL
2760 * to remove the header. This function frees the
2761 * original string if necessary.
2763 * Returns : JB_ERR_OK on success, or
2764 * JB_ERR_MEMORY on out-of-memory error.
2766 *********************************************************************/
2767 static jb_err server_content_disposition(struct client_state *csp, char **header)
2772 * Are we messing with the Content-Disposition header?
2774 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2780 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2782 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2785 * Blocking content-disposition header
2787 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2794 * Replacing Content-Disposition header
2797 *header = strdup("Content-Disposition: ");
2798 string_append(header, newval);
2800 if (*header != NULL)
2802 log_error(LOG_LEVEL_HEADER,
2803 "Content-Disposition header crunched and replaced with: %s", *header);
2806 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2810 /*********************************************************************
2812 * Function : server_last_modified
2814 * Description : Changes Last-Modified header to the actual date
2815 * to help hide-if-modified-since.
2816 * Called from `sed'.
2819 * 1 : csp = Current client state (buffers, headers, etc...)
2820 * 2 : header = On input, pointer to header to modify.
2821 * On output, pointer to the modified header, or NULL
2822 * to remove the header. This function frees the
2823 * original string if necessary.
2825 * Returns : JB_ERR_OK on success, or
2826 * JB_ERR_MEMORY on out-of-memory error.
2828 *********************************************************************/
2829 static jb_err server_last_modified(struct client_state *csp, char **header)
2832 char buf[BUFFER_SIZE];
2835 #ifdef HAVE_GMTIME_R
2838 struct tm *timeptr = NULL;
2839 time_t now, last_modified;
2841 long int days, hours, minutes, seconds;
2844 * Are we messing with the Last-Modified header?
2846 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2852 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2854 if (0 == strcmpic(newval, "block") )
2857 * Blocking Last-Modified header. Useless but why not.
2859 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2863 else if (0 == strcmpic(newval, "reset-to-request-time"))
2866 * Setting Last-Modified Header to now.
2868 get_http_time(0, buf, sizeof(buf));
2870 *header = strdup("Last-Modified: ");
2871 string_append(header, buf);
2873 if (*header == NULL)
2875 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2879 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2882 else if (0 == strcmpic(newval, "randomize"))
2884 const char *header_time = *header + sizeof("Last-Modified:");
2886 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2888 #ifdef HAVE_GMTIME_R
2889 timeptr = gmtime_r(&now, &gmt);
2890 #elif FEATURE_PTHREAD
2891 privoxy_mutex_lock(&gmtime_mutex);
2892 timeptr = gmtime(&now);
2893 privoxy_mutex_unlock(&gmtime_mutex);
2895 timeptr = gmtime(&now);
2897 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2899 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2904 rtime = (long int)difftime(now, last_modified);
2913 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2915 rtime = pick_from_range(rtime);
2916 if (negative) rtime *= -1;
2917 last_modified += rtime;
2918 #ifdef HAVE_GMTIME_R
2919 timeptr = gmtime_r(&last_modified, &gmt);
2920 #elif FEATURE_PTHREAD
2921 privoxy_mutex_lock(&gmtime_mutex);
2922 timeptr = gmtime(&last_modified);
2923 privoxy_mutex_unlock(&gmtime_mutex);
2925 timeptr = gmtime(&last_modified);
2927 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2929 *header = strdup("Last-Modified: ");
2930 string_append(header, newheader);
2932 if (*header == NULL)
2934 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2935 return JB_ERR_MEMORY;
2938 days = rtime / (3600 * 24);
2939 hours = rtime / 3600 % 24;
2940 minutes = rtime / 60 % 60;
2941 seconds = rtime % 60;
2943 log_error(LOG_LEVEL_HEADER,
2944 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2945 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2946 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2950 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2959 /*********************************************************************
2961 * Function : client_accept_encoding
2963 * Description : Rewrite the client's Accept-Encoding header so that
2964 * if doesn't allow compression, if the action applies.
2965 * Note: For HTTP/1.0 the absence of the header is enough.
2968 * 1 : csp = Current client state (buffers, headers, etc...)
2969 * 2 : header = On input, pointer to header to modify.
2970 * On output, pointer to the modified header, or NULL
2971 * to remove the header. This function frees the
2972 * original string if necessary.
2974 * Returns : JB_ERR_OK on success, or
2975 * JB_ERR_MEMORY on out-of-memory error.
2977 *********************************************************************/
2978 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2980 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2982 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2986 /* Temporarily disable the correct behaviour to
2987 * work around a PHP bug.
2989 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2991 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2992 * if (*header == NULL)
2994 * return JB_ERR_MEMORY;
3005 /*********************************************************************
3007 * Function : client_te
3009 * Description : Rewrite the client's TE header so that
3010 * if doesn't allow compression, if the action applies.
3013 * 1 : csp = Current client state (buffers, headers, etc...)
3014 * 2 : header = On input, pointer to header to modify.
3015 * On output, pointer to the modified header, or NULL
3016 * to remove the header. This function frees the
3017 * original string if necessary.
3019 * Returns : JB_ERR_OK on success, or
3020 * JB_ERR_MEMORY on out-of-memory error.
3022 *********************************************************************/
3023 static jb_err client_te(struct client_state *csp, char **header)
3025 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3028 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3035 /*********************************************************************
3037 * Function : client_referrer
3039 * Description : Handle the "referer" config setting properly.
3040 * Called from `sed'.
3043 * 1 : csp = Current client state (buffers, headers, etc...)
3044 * 2 : header = On input, pointer to header to modify.
3045 * On output, pointer to the modified header, or NULL
3046 * to remove the header. This function frees the
3047 * original string if necessary.
3049 * Returns : JB_ERR_OK on success, or
3050 * JB_ERR_MEMORY on out-of-memory error.
3052 *********************************************************************/
3053 static jb_err client_referrer(struct client_state *csp, char **header)
3055 const char *parameter;
3056 /* booleans for parameters we have to check multiple times */
3057 int parameter_conditional_block;
3058 int parameter_conditional_forge;
3060 #ifdef FEATURE_FORCE_LOAD
3062 * Since the referrer can include the prefix even
3063 * if the request itself is non-forced, we must
3064 * clean it unconditionally.
3066 * XXX: strclean is too broad
3068 strclean(*header, FORCE_PREFIX);
3069 #endif /* def FEATURE_FORCE_LOAD */
3071 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3073 /* Nothing left to do */
3077 parameter = csp->action->string[ACTION_STRING_REFERER];
3078 assert(parameter != NULL);
3079 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3080 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3082 if (!parameter_conditional_block && !parameter_conditional_forge)
3085 * As conditional-block and conditional-forge are the only
3086 * parameters that rely on the original referrer, we can
3087 * remove it now for all the others.
3092 if (0 == strcmpic(parameter, "block"))
3094 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3097 else if (parameter_conditional_block || parameter_conditional_forge)
3099 return handle_conditional_hide_referrer_parameter(header,
3100 csp->http->hostport, parameter_conditional_block);
3102 else if (0 == strcmpic(parameter, "forge"))
3104 return create_forged_referrer(header, csp->http->hostport);
3108 /* interpret parameter as user-supplied referer to fake */
3109 return create_fake_referrer(header, parameter);
3114 /*********************************************************************
3116 * Function : client_accept_language
3118 * Description : Handle the "Accept-Language" config setting properly.
3119 * Called from `sed'.
3122 * 1 : csp = Current client state (buffers, headers, etc...)
3123 * 2 : header = On input, pointer to header to modify.
3124 * On output, pointer to the modified header, or NULL
3125 * to remove the header. This function frees the
3126 * original string if necessary.
3128 * Returns : JB_ERR_OK on success, or
3129 * JB_ERR_MEMORY on out-of-memory error.
3131 *********************************************************************/
3132 static jb_err client_accept_language(struct client_state *csp, char **header)
3137 * Are we messing with the Accept-Language?
3139 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3141 /*I don't think so*/
3145 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3147 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3150 * Blocking Accept-Language header
3152 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3159 * Replacing Accept-Language header
3162 *header = strdup("Accept-Language: ");
3163 string_append(header, newval);
3165 if (*header == NULL)
3167 log_error(LOG_LEVEL_ERROR,
3168 "Insufficient memory. Accept-Language header crunched without replacement.");
3172 log_error(LOG_LEVEL_HEADER,
3173 "Accept-Language header crunched and replaced with: %s", *header);
3176 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3180 /*********************************************************************
3182 * Function : crunch_client_header
3184 * Description : Crunch client header if it matches a string supplied by the
3185 * user. Called from `sed'.
3188 * 1 : csp = Current client state (buffers, headers, etc...)
3189 * 2 : header = On input, pointer to header to modify.
3190 * On output, pointer to the modified header, or NULL
3191 * to remove the header. This function frees the
3192 * original string if necessary.
3194 * Returns : JB_ERR_OK on success and always succeeds
3196 *********************************************************************/
3197 static jb_err crunch_client_header(struct client_state *csp, char **header)
3199 const char *crunch_pattern;
3201 /* Do we feel like crunching? */
3202 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3204 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3206 /* Is the current header the lucky one? */
3207 if (strstr(*header, crunch_pattern))
3209 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3217 /*********************************************************************
3219 * Function : client_uagent
3221 * Description : Handle the "user-agent" config setting properly
3222 * and remember its original value to enable browser
3223 * bug workarounds. Called from `sed'.
3226 * 1 : csp = Current client state (buffers, headers, etc...)
3227 * 2 : header = On input, pointer to header to modify.
3228 * On output, pointer to the modified header, or NULL
3229 * to remove the header. This function frees the
3230 * original string if necessary.
3232 * Returns : JB_ERR_OK on success, or
3233 * JB_ERR_MEMORY on out-of-memory error.
3235 *********************************************************************/
3236 static jb_err client_uagent(struct client_state *csp, char **header)
3240 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3245 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3252 *header = strdup("User-Agent: ");
3253 string_append(header, newval);
3255 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3257 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3261 /*********************************************************************
3263 * Function : client_ua
3265 * Description : Handle "ua-" headers properly. Called from `sed'.
3268 * 1 : csp = Current client state (buffers, headers, etc...)
3269 * 2 : header = On input, pointer to header to modify.
3270 * On output, pointer to the modified header, or NULL
3271 * to remove the header. This function frees the
3272 * original string if necessary.
3274 * Returns : JB_ERR_OK on success, or
3275 * JB_ERR_MEMORY on out-of-memory error.
3277 *********************************************************************/
3278 static jb_err client_ua(struct client_state *csp, char **header)
3280 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3282 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3290 /*********************************************************************
3292 * Function : client_from
3294 * Description : Handle the "from" config setting properly.
3295 * Called from `sed'.
3298 * 1 : csp = Current client state (buffers, headers, etc...)
3299 * 2 : header = On input, pointer to header to modify.
3300 * On output, pointer to the modified header, or NULL
3301 * to remove the header. This function frees the
3302 * original string if necessary.
3304 * Returns : JB_ERR_OK on success, or
3305 * JB_ERR_MEMORY on out-of-memory error.
3307 *********************************************************************/
3308 static jb_err client_from(struct client_state *csp, char **header)
3312 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3319 newval = csp->action->string[ACTION_STRING_FROM];
3322 * Are we blocking the e-mail address?
3324 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3326 log_error(LOG_LEVEL_HEADER, "crunched From!");
3330 log_error(LOG_LEVEL_HEADER, " modified");
3332 *header = strdup("From: ");
3333 string_append(header, newval);
3335 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3339 /*********************************************************************
3341 * Function : client_send_cookie
3343 * Description : Crunches the "cookie" header if necessary.
3344 * Called from `sed'.
3346 * XXX: Stupid name, doesn't send squat.
3349 * 1 : csp = Current client state (buffers, headers, etc...)
3350 * 2 : header = On input, pointer to header to modify.
3351 * On output, pointer to the modified header, or NULL
3352 * to remove the header. This function frees the
3353 * original string if necessary.
3355 * Returns : JB_ERR_OK on success, or
3356 * JB_ERR_MEMORY on out-of-memory error.
3358 *********************************************************************/
3359 static jb_err client_send_cookie(struct client_state *csp, char **header)
3361 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3363 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3371 /*********************************************************************
3373 * Function : client_x_forwarded
3375 * Description : Handle the "x-forwarded-for" config setting properly,
3376 * also used in the add_client_headers list. Called from `sed'.
3379 * 1 : csp = Current client state (buffers, headers, etc...)
3380 * 2 : header = On input, pointer to header to modify.
3381 * On output, pointer to the modified header, or NULL
3382 * to remove the header. This function frees the
3383 * original string if necessary.
3385 * Returns : JB_ERR_OK on success, or
3386 * JB_ERR_MEMORY on out-of-memory error.
3388 *********************************************************************/
3389 jb_err client_x_forwarded(struct client_state *csp, char **header)
3391 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3393 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3395 if (0 == strcmpic(parameter, "block"))
3398 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3400 else if (0 == strcmpic(parameter, "add"))
3402 string_append(header, ", ");
3403 string_append(header, csp->ip_addr_str);
3405 if (*header == NULL)
3407 return JB_ERR_MEMORY;
3409 log_error(LOG_LEVEL_HEADER,
3410 "Appended client IP address to %s", *header);
3411 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3415 log_error(LOG_LEVEL_FATAL,
3416 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3424 /*********************************************************************
3426 * Function : client_max_forwards
3428 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3429 * from the value of the Max-Forwards header field.
3432 * 1 : csp = Current client state (buffers, headers, etc...)
3433 * 2 : header = On input, pointer to header to modify.
3434 * On output, pointer to the modified header, or NULL
3435 * to remove the header. This function frees the
3436 * original string if necessary.
3438 * Returns : JB_ERR_OK on success, or
3439 * JB_ERR_MEMORY on out-of-memory error.
3441 *********************************************************************/
3442 static jb_err client_max_forwards(struct client_state *csp, char **header)
3446 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3447 (0 == strcmpic(csp->http->gpc, "options")))
3449 assert(*(*header+12) == ':');
3450 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3452 if (max_forwards > 0)
3454 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3455 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3456 csp->http->gpc, max_forwards);
3458 else if (max_forwards < 0)
3460 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3466 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3475 /*********************************************************************
3477 * Function : client_host
3479 * Description : If the request URI did not contain host and
3480 * port information, parse and evaluate the Host
3483 * Also, kill ill-formed HOST: headers as sent by
3484 * Apple's iTunes software when used with a proxy.
3487 * 1 : csp = Current client state (buffers, headers, etc...)
3488 * 2 : header = On input, pointer to header to modify.
3489 * On output, pointer to the modified header, or NULL
3490 * to remove the header. This function frees the
3491 * original string if necessary.
3493 * Returns : JB_ERR_OK on success, or
3494 * JB_ERR_MEMORY on out-of-memory error.
3496 *********************************************************************/
3497 static jb_err client_host(struct client_state *csp, char **header)
3502 * If the header field name is all upper-case, chances are that it's
3503 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3504 * not a problem -- they are regenerated later.
3506 if ((*header)[1] == 'O')
3508 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3513 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3514 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3517 if (NULL == (p = strdup((*header)+6)))
3519 return JB_ERR_MEMORY;
3522 if (NULL == (q = strdup(p)))
3525 return JB_ERR_MEMORY;
3528 freez(csp->http->hostport);
3529 csp->http->hostport = p;
3530 freez(csp->http->host);
3531 csp->http->host = q;
3532 q = strchr(csp->http->host, ':');
3535 /* Terminate hostname and evaluate port string */
3537 csp->http->port = atoi(q);
3541 csp->http->port = csp->http->ssl ? 443 : 80;
3544 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3545 csp->http->hostport, csp->http->host, csp->http->port);
3548 /* Signal client_host_adder() to return right away */
3549 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3555 /*********************************************************************
3557 * Function : client_if_modified_since
3559 * Description : Remove or modify the If-Modified-Since header.
3562 * 1 : csp = Current client state (buffers, headers, etc...)
3563 * 2 : header = On input, pointer to header to modify.
3564 * On output, pointer to the modified header, or NULL
3565 * to remove the header. This function frees the
3566 * original string if necessary.
3568 * Returns : JB_ERR_OK on success, or
3569 * JB_ERR_MEMORY on out-of-memory error.
3571 *********************************************************************/
3572 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3575 #ifdef HAVE_GMTIME_R
3578 struct tm *timeptr = NULL;
3582 long int hours, minutes, seconds;
3586 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3589 * The client got an error message because of a temporary problem,
3590 * the problem is gone and the client now tries to revalidate our
3591 * error message on the real server. The revalidation would always
3592 * end with the transmission of the whole document and there is
3593 * no need to expose the bogus If-Modified-Since header.
3595 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3598 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3600 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3602 if ((0 == strcmpic(newval, "block")))
3604 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3607 else /* add random value */
3609 const char *header_time = *header + sizeof("If-Modified-Since:");
3611 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3613 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3618 rtime = strtol(newval, &endptr, 0);
3621 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3622 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3629 rtime = pick_from_range(rtime);
3633 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3636 tm += rtime * (negative ? -1 : 1);
3637 #ifdef HAVE_GMTIME_R
3638 timeptr = gmtime_r(&tm, &gmt);
3639 #elif FEATURE_PTHREAD
3640 privoxy_mutex_lock(&gmtime_mutex);
3641 timeptr = gmtime(&tm);
3642 privoxy_mutex_unlock(&gmtime_mutex);
3644 timeptr = gmtime(&tm);
3646 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3649 *header = strdup("If-Modified-Since: ");
3650 string_append(header, newheader);
3652 if (*header == NULL)
3654 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3655 return JB_ERR_MEMORY;
3658 hours = rtime / 3600;
3659 minutes = rtime / 60 % 60;
3660 seconds = rtime % 60;
3662 log_error(LOG_LEVEL_HEADER,
3663 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3664 *header, (negative) ? "subtracted" : "added", hours,
3665 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3666 seconds, (seconds == 1) ? ")" : "s)");
3675 /*********************************************************************
3677 * Function : client_if_none_match
3679 * Description : Remove the If-None-Match header.
3682 * 1 : csp = Current client state (buffers, headers, etc...)
3683 * 2 : header = On input, pointer to header to modify.
3684 * On output, pointer to the modified header, or NULL
3685 * to remove the header. This function frees the
3686 * original string if necessary.
3688 * Returns : JB_ERR_OK on success, or
3689 * JB_ERR_MEMORY on out-of-memory error.
3691 *********************************************************************/
3692 static jb_err client_if_none_match(struct client_state *csp, char **header)
3694 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3696 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3704 /*********************************************************************
3706 * Function : client_x_filter
3708 * Description : Disables filtering if the client set "X-Filter: No".
3709 * Called from `sed'.
3712 * 1 : csp = Current client state (buffers, headers, etc...)
3713 * 2 : header = On input, pointer to header to modify.
3714 * On output, pointer to the modified header, or NULL
3715 * to remove the header. This function frees the
3716 * original string if necessary.
3718 * Returns : JB_ERR_OK on success
3720 *********************************************************************/
3721 jb_err client_x_filter(struct client_state *csp, char **header)
3723 if ( 0 == strcmpic(*header, "X-Filter: No"))
3725 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3727 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3731 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3733 log_error(LOG_LEVEL_HEADER,
3734 "force-text-mode overruled the client's request to fetch without filtering!");
3738 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3739 csp->flags |= CSP_FLAG_NO_FILTERING;
3740 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3742 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3750 /*********************************************************************
3752 * Function : client_range
3754 * Description : Removes Range, Request-Range and If-Range headers if
3755 * content filtering is enabled. If the client's version
3756 * of the document has been altered by Privoxy, the server
3757 * could interpret the range differently than the client
3758 * intended in which case the user could end up with
3759 * corrupted content.
3762 * 1 : csp = Current client state (buffers, headers, etc...)
3763 * 2 : header = On input, pointer to header to modify.
3764 * On output, pointer to the modified header, or NULL
3765 * to remove the header. This function frees the
3766 * original string if necessary.
3768 * Returns : JB_ERR_OK
3770 *********************************************************************/
3771 static jb_err client_range(struct client_state *csp, char **header)
3773 if (content_filters_enabled(csp->action))
3775 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3776 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3783 /* the following functions add headers directly to the header list */
3785 /*********************************************************************
3787 * Function : client_host_adder
3789 * Description : Adds the Host: header field if it is missing.
3790 * Called from `sed'.
3793 * 1 : csp = Current client state (buffers, headers, etc...)
3795 * Returns : JB_ERR_OK on success, or
3796 * JB_ERR_MEMORY on out-of-memory error.
3798 *********************************************************************/
3799 static jb_err client_host_adder(struct client_state *csp)
3804 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3806 /* Header already set by the client, nothing to do. */
3810 if ( !csp->http->hostport || !*(csp->http->hostport))
3812 /* XXX: When does this happen and why is it OK? */
3813 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3818 * remove 'user:pass@' from 'proto://user:pass@host'
3820 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3826 p = csp->http->hostport;
3829 /* XXX: Just add it, we already made sure that it will be unique */
3830 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3831 err = enlist_unique_header(csp->headers, "Host", p);
3838 /*********************************************************************
3840 * Function : client_accept_encoding_adder
3842 * Description : Add an Accept-Encoding header to the client's request
3843 * that disables compression if the action applies, and
3844 * the header is not already there. Called from `sed'.
3845 * Note: For HTTP/1.0, the absence of the header is enough.
3848 * 1 : csp = Current client state (buffers, headers, etc...)
3850 * Returns : JB_ERR_OK on success, or
3851 * JB_ERR_MEMORY on out-of-memory error.
3853 *********************************************************************/
3854 static jb_err client_accept_encoding_adder(struct client_state *csp)
3856 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3857 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3859 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3867 /*********************************************************************
3869 * Function : client_xtra_adder
3871 * Description : Used in the add_client_headers list. Called from `sed'.
3874 * 1 : csp = Current client state (buffers, headers, etc...)
3876 * Returns : JB_ERR_OK on success, or
3877 * JB_ERR_MEMORY on out-of-memory error.
3879 *********************************************************************/
3880 static jb_err client_xtra_adder(struct client_state *csp)
3882 struct list_entry *lst;
3885 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3886 lst ; lst = lst->next)
3888 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3889 err = enlist(csp->headers, lst->str);
3901 /*********************************************************************
3903 * Function : client_x_forwarded_for_adder
3905 * Description : Used in the add_client_headers list. Called from `sed'.
3908 * 1 : csp = Current client state (buffers, headers, etc...)
3910 * Returns : JB_ERR_OK on success, or
3911 * JB_ERR_MEMORY on out-of-memory error.
3913 *********************************************************************/
3914 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3916 char *header = NULL;
3919 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3920 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3921 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3924 * If we aren't adding X-Forwarded-For headers,
3925 * or we already appended an existing X-Forwarded-For
3926 * header, there's nothing left to do here.
3931 header = strdup("X-Forwarded-For: ");
3932 string_append(&header, csp->ip_addr_str);
3936 return JB_ERR_MEMORY;
3939 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3940 err = enlist(csp->headers, header);
3947 /*********************************************************************
3949 * Function : connection_close_adder
3951 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3952 * support. Adds a "Connection: close" header to csp->headers
3953 * unless the header was already present. Called from `sed'.
3955 * FIXME: This whole function shouldn't be neccessary!
3958 * 1 : csp = Current client state (buffers, headers, etc...)
3960 * Returns : JB_ERR_OK on success, or
3961 * JB_ERR_MEMORY on out-of-memory error.
3963 *********************************************************************/
3964 static jb_err connection_close_adder(struct client_state *csp)
3966 const unsigned int flags = csp->flags;
3969 * Return right away if
3971 * - we're parsing server headers and the server header
3972 * "Connection: close" is already set, or if
3974 * - we're parsing client headers and the client header
3975 * "Connection: close" is already set.
3977 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3978 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3979 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3980 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3985 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3987 return enlist(csp->headers, "Connection: close");
3991 /*********************************************************************
3993 * Function : server_http
3995 * Description : - Save the HTTP Status into csp->http->status
3996 * - Set CT_TABOO to prevent filtering if the answer
3997 * is a partial range (HTTP status 206)
3998 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4002 * 1 : csp = Current client state (buffers, headers, etc...)
4003 * 2 : header = On input, pointer to header to modify.
4004 * On output, pointer to the modified header, or NULL
4005 * to remove the header. This function frees the
4006 * original string if necessary.
4008 * Returns : JB_ERR_OK on success, or
4009 * JB_ERR_MEMORY on out-of-memory error.
4011 *********************************************************************/
4012 static jb_err server_http(struct client_state *csp, char **header)
4014 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
4015 if (csp->http->status == 206)
4017 csp->content_type = CT_TABOO;
4020 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
4022 /* XXX: Should we do a real validity check here? */
4023 if (strlen(*header) > 8)
4026 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
4031 * XXX: Should we block the request or
4032 * enlist a valid status code line here?
4034 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
4035 "Downgrading to HTTP/1.0 impossible.");
4043 /*********************************************************************
4045 * Function : server_set_cookie
4047 * Description : Handle the server "cookie" header properly.
4048 * Log cookie to the jar file. Then "crunch",
4049 * accept or rewrite it to a session cookie.
4050 * Called from `sed'.
4052 * TODO: Allow the user to specify a new expiration
4053 * time to cause the cookie to expire even before the
4054 * browser is closed.
4057 * 1 : csp = Current client state (buffers, headers, etc...)
4058 * 2 : header = On input, pointer to header to modify.
4059 * On output, pointer to the modified header, or NULL
4060 * to remove the header. This function frees the
4061 * original string if necessary.
4063 * Returns : JB_ERR_OK on success, or
4064 * JB_ERR_MEMORY on out-of-memory error.
4066 *********************************************************************/
4067 static jb_err server_set_cookie(struct client_state *csp, char **header)
4074 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
4076 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4079 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
4081 /* Flag whether or not to log a message */
4084 /* A variable to store the tag we're working on */
4087 /* Skip "Set-Cookie:" (11 characters) in header */
4088 cur_tag = *header + 11;
4090 /* skip whitespace between "Set-Cookie:" and value */
4091 while (*cur_tag && ijb_isspace(*cur_tag))
4096 /* Loop through each tag in the cookie */
4100 char *next_tag = strchr(cur_tag, ';');
4101 if (next_tag != NULL)
4103 /* Skip the ';' character itself */
4106 /* skip whitespace ";" and start of tag */
4107 while (*next_tag && ijb_isspace(*next_tag))
4114 /* "Next tag" is the end of the string */
4115 next_tag = cur_tag + strlen(cur_tag);
4119 * Check the expiration date to see
4120 * if the cookie is still valid, if yes,
4121 * rewrite it to a session cookie.
4123 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4125 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4127 /* Did we detect the date properly? */
4128 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4131 * Nope, treat it as if it was still valid.
4133 * XXX: Should we remove the whole cookie instead?
4135 log_error(LOG_LEVEL_ERROR,
4136 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4137 string_move(cur_tag, next_tag);
4143 * Yes. Check if the cookie is still valid.
4145 * If the cookie is already expired it's probably
4146 * a delete cookie and even if it isn't, the browser
4147 * will discard it anyway.
4151 * XXX: timegm() isn't available on some AmigaOS
4152 * versions and our replacement doesn't work.
4154 * Our options are to either:
4156 * - disable session-cookies-only completely if timegm
4159 * - to simply remove all expired tags, like it has
4160 * been done until Privoxy 3.0.6 and to live with
4161 * the consequence that it can cause login/logout
4162 * problems on servers that don't validate their
4163 * input properly, or
4165 * - to replace it with mktime in which
4166 * case there is a slight chance of valid cookies
4167 * passing as already expired.
4169 * This is the way it's currently done and it's not
4170 * as bad as it sounds. If the missing GMT offset is
4171 * enough to change the result of the expiration check
4172 * the cookie will be only valid for a few hours
4173 * anyway, which in many cases will be shorter
4174 * than a browser session.
4176 if (cookie_time - now < 0)
4178 log_error(LOG_LEVEL_HEADER,
4179 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4180 /* Just in case some clown sets more then one expiration date */
4186 * Still valid, delete expiration date by copying
4187 * the rest of the string over it.
4189 string_move(cur_tag, next_tag);
4191 /* That changed the header, need to issue a log message */
4195 * Note that the next tag has now been moved to *cur_tag,
4196 * so we do not need to update the cur_tag pointer.
4204 /* Move on to next cookie tag */
4211 assert(NULL != *header);
4212 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4221 #ifdef FEATURE_FORCE_LOAD
4222 /*********************************************************************
4224 * Function : strclean
4226 * Description : In-Situ-Eliminate all occurances of substring in
4230 * 1 : string = string to clean
4231 * 2 : substring = substring to eliminate
4233 * Returns : Number of eliminations
4235 *********************************************************************/
4236 int strclean(char *string, const char *substring)
4242 len = strlen(substring);
4244 while((pos = strstr(string, substring)) != NULL)
4251 while (*p++ != '\0');
4258 #endif /* def FEATURE_FORCE_LOAD */
4261 /*********************************************************************
4263 * Function : parse_header_time
4265 * Description : Parses time formats used in HTTP header strings
4266 * to get the numerical respresentation.
4269 * 1 : header_time = HTTP header time as string.
4270 * 2 : result = storage for header_time in seconds
4272 * Returns : JB_ERR_OK if the time format was recognized, or
4273 * JB_ERR_PARSE otherwise.
4275 *********************************************************************/
4276 static jb_err parse_header_time(const char *header_time, time_t *result)
4281 * Zero out gmt to prevent time zone offsets.
4283 * While this is only necessary on some platforms
4284 * (mingw32 for example), I don't know how to
4285 * detect these automatically and doing it everywhere
4288 memset(&gmt, 0, sizeof(gmt));
4290 /* Tue, 02 Jun 2037 20:00:00 */
4291 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
4292 /* Tue, 02-Jun-2037 20:00:00 */
4293 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
4294 /* Tue, 02-Jun-37 20:00:00 */
4295 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
4296 /* Tuesday, 02-Jun-2037 20:00:00 */
4297 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
4298 /* Tuesday Jun 02 20:00:00 2037 */
4299 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
4301 return JB_ERR_PARSE;
4304 *result = timegm(&gmt);
4311 /*********************************************************************
4313 * Function : get_destination_from_headers
4315 * Description : Parse the "Host:" header to get the request's destination.
4316 * Only needed if the client's request was forcefully
4317 * redirected into Privoxy.
4319 * Code mainly copied from client_host() which is currently
4320 * run too late for this purpose.
4323 * 1 : headers = List of headers (one of them hopefully being
4324 * the "Host:" header)
4325 * 2 : http = storage for the result (host, port and hostport).
4327 * Returns : JB_ERR_MEMORY in case of memory problems,
4328 * JB_ERR_PARSE if the host header couldn't be found,
4329 * JB_ERR_OK otherwise.
4331 *********************************************************************/
4332 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4338 host = get_header_value(headers, "Host:");
4342 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4343 return JB_ERR_PARSE;
4346 if (NULL == (p = strdup((host))))
4348 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4349 return JB_ERR_MEMORY;
4352 if (NULL == (q = strdup(p)))
4355 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4356 return JB_ERR_MEMORY;
4359 freez(http->hostport);
4363 q = strchr(http->host, ':');
4366 /* Terminate hostname and evaluate port string */
4368 http->port = atoi(q);
4372 http->port = http->ssl ? 443 : 80;
4375 /* Rebuild request URL */
4377 http->url = strdup(http->ssl ? "https://" : "http://");