Typo: inspect_jpegs, not inspect-jpegs in form
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.56.2.10 2006/01/21 16:16:08 david__schmidt Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/Attic/parsers.c,v $
5  *
6  * Purpose     :  Declares functions to parse/crunch headers and pages.
7  *                Functions declared include:
8  *                   `add_to_iob', `client_cookie_adder', `client_from',
9  *                   `client_referrer', `client_send_cookie', `client_ua',
10  *                   `client_uagent', `client_x_forwarded',
11  *                   `client_x_forwarded_adder', `client_xtra_adder',
12  *                   `content_type', `crumble', `destroy_list', `enlist',
13  *                   `flush_socket', ``get_header', `sed',
14  *                   and `server_set_cookie'.
15  *
16  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
17  *                Privoxy team. http://www.privoxy.org/
18  *
19  *                Based on the Internet Junkbuster originally written
20  *                by and Copyright (C) 1997 Anonymous Coders and
21  *                Junkbusters Corporation.  http://www.junkbusters.com
22  *
23  *                This program is free software; you can redistribute it
24  *                and/or modify it under the terms of the GNU General
25  *                Public License as published by the Free Software
26  *                Foundation; either version 2 of the License, or (at
27  *                your option) any later version.
28  *
29  *                This program is distributed in the hope that it will
30  *                be useful, but WITHOUT ANY WARRANTY; without even the
31  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
32  *                PARTICULAR PURPOSE.  See the GNU General Public
33  *                License for more details.
34  *
35  *                The GNU General Public License should be included with
36  *                this file.  If not, you can view it at
37  *                http://www.gnu.org/copyleft/gpl.html
38  *                or write to the Free Software Foundation, Inc., 59
39  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
40  *
41  * Revisions   :
42  *    $Log: parsers.c,v $
43  *    Revision 1.56.2.10  2006/01/21 16:16:08  david__schmidt
44  *    Thanks to  Edward Carrel for his patch to modernize OSX's\rpthreads support.  See bug #1409623.
45  *
46  *    Revision 1.56.2.9  2004/10/03 12:53:45  david__schmidt
47  *    Add the ability to check jpeg images for invalid
48  *    lengths of comment blocks.  Defensive strategy
49  *    against the exploit:
50  *       Microsoft Security Bulletin MS04-028
51  *       Buffer Overrun in JPEG Processing (GDI+) Could
52  *       Allow Code Execution (833987)
53  *    Enabled with +inspect-jpegs in actions files.
54  *
55  *    Revision 1.56.2.8  2003/07/11 13:21:25  oes
56  *    Excluded text/plain objects from filtering. This fixes a
57  *    couple of client-crashing, download corruption and
58  *    Privoxy performance issues, whose root cause lies in
59  *    web servers labelling content of unknown type as text/plain.
60  *
61  *    Revision 1.56.2.7  2003/05/06 12:07:26  oes
62  *    Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
63  *
64  *    Revision 1.56.2.6  2003/04/14 21:28:30  oes
65  *    Completing the previous change
66  *
67  *    Revision 1.56.2.5  2003/04/14 12:08:16  oes
68  *    Added temporary workaround for bug in PHP < 4.2.3
69  *
70  *    Revision 1.56.2.4  2003/03/07 03:41:05  david__schmidt
71  *    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.
72  *
73  *    Revision 1.56.2.3  2002/11/10 04:20:02  hal9
74  *    Fix typo: supressed -> suppressed
75  *
76  *    Revision 1.56.2.2  2002/09/25 14:59:53  oes
77  *    Improved cookie logging
78  *
79  *    Revision 1.56.2.1  2002/09/25 14:52:45  oes
80  *    Added basic support for OPTIONS and TRACE HTTP methods:
81  *     - New parser function client_max_forwards which decrements
82  *       the Max-Forwards HTTP header field of OPTIONS and TRACE
83  *       requests by one before forwarding
84  *     - New parser function client_host which extracts the host
85  *       and port information from the HTTP header field if the
86  *       request URI was not absolute
87  *     - Don't crumble and re-add the Host: header, but only generate
88  *       and append if missing
89  *
90  *    Revision 1.56  2002/05/12 15:34:22  jongfoster
91  *    Fixing typo in a comment
92  *
93  *    Revision 1.55  2002/05/08 16:01:07  oes
94  *    Optimized add_to_iob:
95  *     - Use realloc instead of malloc(), memcpy(), free()
96  *     - Expand to powers of two if possible, to get
97  *       O(log n) reallocs instead of O(n).
98  *     - Moved check for buffer limit here from chat
99  *     - Report failure via returncode
100  *
101  *    Revision 1.54  2002/04/02 15:03:16  oes
102  *    Tiny code cosmetics
103  *
104  *    Revision 1.53  2002/03/26 22:29:55  swa
105  *    we have a new homepage!
106  *
107  *    Revision 1.52  2002/03/24 13:25:43  swa
108  *    name change related issues
109  *
110  *    Revision 1.51  2002/03/13 00:27:05  jongfoster
111  *    Killing warnings
112  *
113  *    Revision 1.50  2002/03/12 01:45:35  oes
114  *    More verbose logging
115  *
116  *    Revision 1.49  2002/03/09 20:03:52  jongfoster
117  *    - Making various functions return int rather than size_t.
118  *      (Undoing a recent change).  Since size_t is unsigned on
119  *      Windows, functions like read_socket that return -1 on
120  *      error cannot return a size_t.
121  *
122  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
123  *      crashes, and also frequently caused JB to jump to 100%
124  *      CPU and stay there.  (Because it thought it had just
125  *      read ((unsigned)-1) == 4Gb of data...)
126  *
127  *    - The signature of write_socket has changed, it now simply
128  *      returns success=0/failure=nonzero.
129  *
130  *    - Trying to get rid of a few warnings --with-debug on
131  *      Windows, I've introduced a new type "jb_socket".  This is
132  *      used for the socket file descriptors.  On Windows, this
133  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
134  *      an int.  The error value can't be -1 any more, so it's
135  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
136  *      Windows it maps to the #define INVALID_SOCKET.)
137  *
138  *    - The signature of bind_port has changed.
139  *
140  *    Revision 1.48  2002/03/07 03:46:53  oes
141  *    Fixed compiler warnings etc
142  *
143  *    Revision 1.47  2002/02/20 23:15:13  jongfoster
144  *    Parsing functions now handle out-of-memory gracefully by returning
145  *    an error code.
146  *
147  *    Revision 1.46  2002/01/17 21:03:47  jongfoster
148  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
149  *
150  *    Revision 1.45  2002/01/09 14:33:03  oes
151  *    Added support for localtime_r.
152  *
153  *    Revision 1.44  2001/12/14 01:22:54  steudten
154  *    Remove 'user:pass@' from 'proto://user:pass@host' for the
155  *    new added header 'Host: ..'. (See Req ID 491818)
156  *
157  *    Revision 1.43  2001/11/23 00:26:38  jongfoster
158  *    Fixing two really stupid errors in my previous commit
159  *
160  *    Revision 1.42  2001/11/22 21:59:30  jongfoster
161  *    Adding code to handle +no-cookies-keep
162  *
163  *    Revision 1.41  2001/11/05 23:43:05  steudten
164  *    Add time+date to log files.
165  *
166  *    Revision 1.40  2001/10/26 20:13:09  jongfoster
167  *    ctype.h is needed in Windows, too.
168  *
169  *    Revision 1.39  2001/10/26 17:40:04  oes
170  *    Introduced get_header_value()
171  *    Removed http->user_agent, csp->referrer and csp->accept_types
172  *    Removed client_accept()
173  *
174  *    Revision 1.38  2001/10/25 03:40:48  david__schmidt
175  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
176  *    threads to call select() simultaneously.  So, it's time to do a real, live,
177  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
178  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
179  *
180  *    Revision 1.37  2001/10/23 21:36:02  jongfoster
181  *    Documenting sed()'s error behaviou (doc change only)
182  *
183  *    Revision 1.36  2001/10/13 12:51:51  joergs
184  *    Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
185  *    force-load), instead crumble Host: and add it (again) in client_host_adder
186  *    (in case we get a HTTP/1.0 request without Host: header and forward it to
187  *    a HTTP/1.1 server/proxy).
188  *
189  *    Revision 1.35  2001/10/09 22:39:21  jongfoster
190  *    assert.h is also required under Win32, so moving out of #ifndef _WIN32
191  *    block.
192  *
193  *    Revision 1.34  2001/10/07 18:50:55  oes
194  *    Added server_content_encoding, renamed server_transfer_encoding
195  *
196  *    Revision 1.33  2001/10/07 18:04:49  oes
197  *    Changed server_http11 to server_http and its pattern to "HTTP".
198  *      Additional functionality: it now saves the HTTP status into
199  *      csp->http->status and sets CT_TABOO for Status 206 (partial range)
200  *
201  *    Revision 1.32  2001/10/07 15:43:28  oes
202  *    Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
203  *       client_te and client_accept_encoding_adder, triggered by the new
204  *       +no-compression action. For HTTP/1.1 the Accept-Encoding header is
205  *       changed to allow only identity and chunked, and the TE header is
206  *       crunched. For HTTP/1.0, Accept-Encoding is crunched.
207  *
208  *    parse_http_request no longer does anything than parsing. The rewriting
209  *      of http->cmd and version mangling are gone. It now also recognizes
210  *      the put and delete methods and saves the url in http->url. Removed
211  *      unused variable.
212  *
213  *    renamed content_type and content_length to have the server_ prefix
214  *
215  *    server_content_type now only works if csp->content_type != CT_TABOO
216  *
217  *    added server_transfer_encoding, which
218  *      - Sets CT_TABOO to prohibit filtering if encoding compresses
219  *      - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
220  *      - Change from "chunked" to "identity" if body was chunked
221  *        but has been de-chunked for filtering.
222  *
223  *    added server_content_md5 which crunches any Content-MD5 headers
224  *      if the body was modified.
225  *
226  *    made server_http11 conditional on +downgrade action
227  *
228  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
229  *
230  *    Revision 1.31  2001/10/05 14:25:02  oes
231  *    Crumble Keep-Alive from Server
232  *
233  *    Revision 1.30  2001/09/29 12:56:03  joergs
234  *    IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
235  *
236  *    Revision 1.29  2001/09/24 21:09:24  jongfoster
237  *    Fixing 2 memory leaks that Guy spotted, where the paramater to
238  *    enlist() was not being free()d.
239  *
240  *    Revision 1.28  2001/09/22 16:32:28  jongfoster
241  *    Removing unused #includes.
242  *
243  *    Revision 1.27  2001/09/20 15:45:25  steudten
244  *
245  *    add casting from size_t to int for printf()
246  *    remove local variable shadow s2
247  *
248  *    Revision 1.26  2001/09/16 17:05:14  jongfoster
249  *    Removing unused #include showarg.h
250  *
251  *    Revision 1.25  2001/09/16 13:21:27  jongfoster
252  *    Changes to use new list functions.
253  *
254  *    Revision 1.24  2001/09/13 23:05:50  jongfoster
255  *    Changing the string paramater to the header parsers a "const".
256  *
257  *    Revision 1.23  2001/09/12 18:08:19  steudten
258  *
259  *    In parse_http_request() header rewriting miss the host value, so
260  *    from http://www.mydomain.com the result was just " / " not
261  *    http://www.mydomain.com/ in case we forward.
262  *
263  *    Revision 1.22  2001/09/10 10:58:53  oes
264  *    Silenced compiler warnings
265  *
266  *    Revision 1.21  2001/07/31 14:46:00  oes
267  *     - Persistant connections now suppressed
268  *     - sed() no longer appends empty header to csp->headers
269  *
270  *    Revision 1.20  2001/07/30 22:08:36  jongfoster
271  *    Tidying up #defines:
272  *    - All feature #defines are now of the form FEATURE_xxx
273  *    - Permanently turned off WIN_GUI_EDIT
274  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
275  *
276  *    Revision 1.19  2001/07/25 17:21:54  oes
277  *    client_uagent now saves copy of User-Agent: header value
278  *
279  *    Revision 1.18  2001/07/13 14:02:46  oes
280  *     - Included fix to repair broken HTTP requests that
281  *       don't contain a path, not even '/'.
282  *     - Removed all #ifdef PCRS
283  *     - content_type now always inspected and classified as
284  *       text, gif or other.
285  *     - formatting / comments
286  *
287  *    Revision 1.17  2001/06/29 21:45:41  oes
288  *    Indentation, CRLF->LF, Tab-> Space
289  *
290  *    Revision 1.16  2001/06/29 13:32:42  oes
291  *    - Fixed a comment
292  *    - Adapted free_http_request
293  *    - Removed logentry from cancelled commit
294  *
295  *    Revision 1.15  2001/06/03 19:12:38  oes
296  *    deleted const struct interceptors
297  *
298  *    Revision 1.14  2001/06/01 18:49:17  jongfoster
299  *    Replaced "list_share" with "list" - the tiny memory gain was not
300  *    worth the extra complexity.
301  *
302  *    Revision 1.13  2001/05/31 21:30:33  jongfoster
303  *    Removed list code - it's now in list.[ch]
304  *    Renamed "permission" to "action", and changed many features
305  *    to use the actions file rather than the global config.
306  *
307  *    Revision 1.12  2001/05/31 17:33:13  oes
308  *
309  *    CRLF -> LF
310  *
311  *    Revision 1.11  2001/05/29 20:11:19  joergs
312  *    '/ * inside comment' warning removed.
313  *
314  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
315  *    Unified blocklist/imagelist/permissionslist.
316  *    File format is still under discussion, but the internal changes
317  *    are (mostly) done.
318  *
319  *    Also modified interceptor behaviour:
320  *    - We now intercept all URLs beginning with one of the following
321  *      prefixes (and *only* these prefixes):
322  *        * http://i.j.b/
323  *        * http://ijbswa.sf.net/config/
324  *        * http://ijbswa.sourceforge.net/config/
325  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
326  *    - Internal changes so that intercepted and fast redirect pages
327  *      are not replaced with an image.
328  *    - Interceptors now have the option to send a binary page direct
329  *      to the client. (i.e. ijb-send-banner uses this)
330  *    - Implemented show-url-info interceptor.  (Which is why I needed
331  *      the above interceptors changes - a typical URL is
332  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
333  *      The previous mechanism would not have intercepted that, and
334  *      if it had been intercepted then it then it would have replaced
335  *      it with an image.)
336  *
337  *    Revision 1.9  2001/05/28 17:26:33  jongfoster
338  *    Fixing segfault if last header was crunched.
339  *    Fixing Windows build (snprintf() is _snprintf() under Win32, but we
340  *    can use the cross-platform sprintf() instead.)
341  *
342  *    Revision 1.8  2001/05/27 22:17:04  oes
343  *
344  *    - re_process_buffer no longer writes the modified buffer
345  *      to the client, which was very ugly. It now returns the
346  *      buffer, which it is then written by chat.
347  *
348  *    - content_length now adjusts the Content-Length: header
349  *      for modified documents rather than crunch()ing it.
350  *      (Length info in csp->content_length, which is 0 for
351  *      unmodified documents)
352  *
353  *    - For this to work, sed() is called twice when filtering.
354  *
355  *    Revision 1.7  2001/05/27 13:19:06  oes
356  *    Patched Joergs solution for the content-length in.
357  *
358  *    Revision 1.6  2001/05/26 13:39:32  jongfoster
359  *    Only crunches Content-Length header if applying RE filtering.
360  *    Without this fix, Microsoft Windows Update wouldn't work.
361  *
362  *    Revision 1.5  2001/05/26 00:28:36  jongfoster
363  *    Automatic reloading of config file.
364  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
365  *    Most of the global variables have been moved to a new
366  *    struct configuration_spec, accessed through csp->config->globalname
367  *    Most of the globals remaining are used by the Win32 GUI.
368  *
369  *    Revision 1.4  2001/05/22 18:46:04  oes
370  *
371  *    - Enabled filtering banners by size rather than URL
372  *      by adding patterns that replace all standard banner
373  *      sizes with the "Junkbuster" gif to the re_filterfile
374  *
375  *    - Enabled filtering WebBugs by providing a pattern
376  *      which kills all 1x1 images
377  *
378  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
379  *      which is selected by the (nonstandard and therefore
380  *      capital) letter 'U' in the option string.
381  *      It causes the quantifiers to be ungreedy by default.
382  *      Appending a ? turns back to greedy (!).
383  *
384  *    - Added a new interceptor ijb-send-banner, which
385  *      sends back the "Junkbuster" gif. Without imagelist or
386  *      MSIE detection support, or if tinygif = 1, or the
387  *      URL isn't recognized as an imageurl, a lame HTML
388  *      explanation is sent instead.
389  *
390  *    - Added new feature, which permits blocking remote
391  *      script redirects and firing back a local redirect
392  *      to the browser.
393  *      The feature is conditionally compiled, i.e. it
394  *      can be disabled with --disable-fast-redirects,
395  *      plus it must be activated by a "fast-redirects"
396  *      line in the config file, has its own log level
397  *      and of course wants to be displayed by show-proxy-args
398  *      Note: Boy, all the #ifdefs in 1001 locations and
399  *      all the fumbling with configure.in and acconfig.h
400  *      were *way* more work than the feature itself :-(
401  *
402  *    - Because a generic redirect template was needed for
403  *      this, tinygif = 3 now uses the same.
404  *
405  *    - Moved GIFs, and other static HTTP response templates
406  *      to project.h
407  *
408  *    - Some minor fixes
409  *
410  *    - Removed some >400 CRs again (Jon, you really worked
411  *      a lot! ;-)
412  *
413  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
414  *    Version 2.9.4 checkin.
415  *    - Merged popupfile and cookiefile, and added control over PCRS
416  *      filtering, in new "permissionsfile".
417  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
418  *      file error you now get a message box (in the Win32 GUI) rather
419  *      than the program exiting with no explanation.
420  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
421  *      skipping.
422  *    - Removed tabs from "config"
423  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
424  *    - Bumped up version number.
425  *
426  *    Revision 1.2  2001/05/17 23:02:36  oes
427  *     - Made referrer option accept 'L' as a substitute for '§'
428  *
429  *    Revision 1.1.1.1  2001/05/15 13:59:01  oes
430  *    Initial import of version 2.9.3 source tree
431  *
432  *
433  *********************************************************************/
434 \f
435
436 #include "config.h"
437
438 #ifndef _WIN32
439 #include <stdio.h>
440 #include <sys/types.h>
441 #endif
442
443 #include <stdlib.h>
444 #include <ctype.h>
445 #include <assert.h>
446 #include <string.h>
447
448 #if !defined(_WIN32) && !defined(__OS2__)
449 #include <unistd.h>
450 #endif
451
452 #include "project.h"
453
454 #ifdef OSX_DARWIN
455 #include <pthread.h>
456 #include "jcc.h"
457 /* jcc.h is for mutex semapores only */
458 #endif /* def OSX_DARWIN */
459 #include "list.h"
460 #include "parsers.h"
461 #include "encode.h"
462 #include "ssplit.h"
463 #include "errlog.h"
464 #include "jbsockets.h"
465 #include "miscutil.h"
466 #include "list.h"
467
468 const char parsers_h_rcs[] = PARSERS_H_VERSION;
469
470 /* Fix a problem with Solaris.  There should be no effect on other
471  * platforms.
472  * Solaris's isspace() is a macro which uses it's argument directly
473  * as an array index.  Therefore we need to make sure that high-bit
474  * characters generate +ve values, and ideally we also want to make
475  * the argument match the declared parameter type of "int".
476  *
477  * Why did they write a character function that can't take a simple
478  * "char" argument?  Doh!
479  */
480 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
481 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
482
483
484 const struct parsers client_patterns[] = {
485    { "referer:",                 8,    client_referrer },
486    { "user-agent:",              11,   client_uagent },
487    { "ua-",                      3,    client_ua },
488    { "from:",                    5,    client_from },
489    { "cookie:",                  7,    client_send_cookie },
490    { "x-forwarded-for:",         16,   client_x_forwarded },
491    { "Accept-Encoding:",         16,   client_accept_encoding },
492    { "TE:",                       3,   client_te },
493    { "Host:",                     5,   client_host },
494 /* { "if-modified-since:",       18,   crumble }, */
495    { "Keep-Alive:",              11,   crumble },
496    { "connection:",              11,   crumble },
497    { "proxy-connection:",        17,   crumble },
498    { "max-forwards:",            13,   client_max_forwards },
499    { NULL,                       0,    NULL }
500 };
501
502
503 const struct parsers server_patterns[] = {
504    { "HTTP",                4, server_http },
505    { "set-cookie:",        11, server_set_cookie },
506    { "connection:",        11, crumble },
507    { "Content-Type:",      13, server_content_type },
508    { "Content-Length:",    15, server_content_length },
509    { "Content-MD5:",       12, server_content_md5 },
510    { "Content-Encoding:",  17, server_content_encoding },
511    { "Transfer-Encoding:", 18, server_transfer_coding },
512    { "Keep-Alive:",        11, crumble },
513    { NULL, 0, NULL }
514 };
515
516
517 const add_header_func_ptr add_client_headers[] = {
518    client_host_adder,
519    client_cookie_adder,
520    client_x_forwarded_adder,
521    client_xtra_adder,
522    /* Temporarily disabled:    client_accept_encoding_adder, */
523    connection_close_adder,
524    NULL
525 };
526
527
528 const add_header_func_ptr add_server_headers[] = {
529    connection_close_adder,
530    NULL
531 };
532
533
534 /*********************************************************************
535  *
536  * Function    :  flush_socket
537  *
538  * Description :  Write any pending "buffered" content.
539  *
540  * Parameters  :
541  *          1  :  fd = file descriptor of the socket to read
542  *          2  :  csp = Current client state (buffers, headers, etc...)
543  *
544  * Returns     :  On success, the number of bytes written are returned (zero
545  *                indicates nothing was written).  On error, -1 is returned,
546  *                and errno is set appropriately.  If count is zero and the
547  *                file descriptor refers to a regular file, 0 will be
548  *                returned without causing any other effect.  For a special
549  *                file, the results are not portable.
550  *
551  *********************************************************************/
552 int flush_socket(jb_socket fd, struct client_state *csp)
553 {
554    struct iob *iob = csp->iob;
555    int len = iob->eod - iob->cur;
556
557    if (len <= 0)
558    {
559       return(0);
560    }
561
562    if (write_socket(fd, iob->cur, (size_t)len))
563    {
564       return(-1);
565    }
566    iob->eod = iob->cur = iob->buf;
567    return(len);
568
569 }
570
571
572 /*********************************************************************
573  *
574  * Function    :  add_to_iob
575  *
576  * Description :  Add content to the buffered page, expanding the
577  *                buffer if necessary.
578  *
579  * Parameters  :
580  *          1  :  csp = Current client state (buffers, headers, etc...)
581  *          2  :  buf = holds the content to be added to the page
582  *          3  :  n = number of bytes to be added
583  *
584  * Returns     :  JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
585  *                or buffer limit reached.
586  *
587  *********************************************************************/
588 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
589 {
590    struct iob *iob = csp->iob;
591    size_t used, offset, need, want;
592    char *p;
593
594    if (n <= 0) return JB_ERR_OK;
595
596    used   = iob->eod - iob->buf;
597    offset = iob->cur - iob->buf;
598    need   = used + n + 1;
599
600    /*
601     * If the buffer can't hold the new data, extend it first.
602     * Use the next power of two if possible, else use the actual need.
603     */
604    if (need > csp->config->buffer_limit)
605    {
606       log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
607       return JB_ERR_MEMORY;
608    }
609
610    if (need > iob->size)
611    {
612       for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
613       
614       if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
615       {
616          iob->size = want;
617       }
618       else if (NULL != (p = (char *)realloc(iob->buf, need)))
619       {
620          iob->size = need;
621       }
622       else
623       {
624          log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
625          return JB_ERR_MEMORY;
626       }
627
628       /* Update the iob pointers */
629       iob->cur = p + offset;
630       iob->eod = p + used;
631       iob->buf = p;
632    }
633
634    /* copy the new data into the iob buffer */
635    memcpy(iob->eod, buf, (size_t)n);
636
637    /* point to the end of the data */
638    iob->eod += n;
639
640    /* null terminate == cheap insurance */
641    *iob->eod = '\0';
642
643    return JB_ERR_OK;
644
645 }
646
647
648 /*********************************************************************
649  *
650  * Function    :  get_header
651  *
652  * Description :  This (odd) routine will parse the csp->iob
653  *
654  * Parameters  :
655  *          1  :  csp = Current client state (buffers, headers, etc...)
656  *
657  * Returns     :  Any one of the following:
658  *
659  * 1) a pointer to a dynamically allocated string that contains a header line
660  * 2) NULL  indicating that the end of the header was reached
661  * 3) ""    indicating that the end of the iob was reached before finding
662  *          a complete header line.
663  *
664  *********************************************************************/
665 char *get_header(struct client_state *csp)
666 {
667    struct iob *iob;
668    char *p, *q, *ret;
669    iob = csp->iob;
670
671    if ((iob->cur == NULL)
672       || ((p = strchr(iob->cur, '\n')) == NULL))
673    {
674       return(""); /* couldn't find a complete header */
675    }
676
677    *p = '\0';
678
679    ret = strdup(iob->cur);
680    if (ret == NULL)
681    {
682       /* FIXME No way to handle error properly */
683       log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
684    }
685
686    iob->cur = p+1;
687
688    if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
689
690    /* is this a blank line (i.e. the end of the header) ? */
691    if (*ret == '\0')
692    {
693       freez(ret);
694       return(NULL);
695    }
696
697    return(ret);
698
699 }
700
701
702 /*********************************************************************
703  *
704  * Function    :  get_header_value
705  *
706  * Description :  Get the value of a given header from a chained list
707  *                of header lines or return NULL if no such header is
708  *                present in the list.
709  *
710  * Parameters  :
711  *          1  :  header_list = pointer to list
712  *          2  :  header_name = string with name of header to look for.
713  *                              Trailing colon required, capitalization
714  *                              doesn't matter.
715  *
716  * Returns     :  NULL if not found, else value of header
717  *
718  *********************************************************************/
719 char *get_header_value(const struct list *header_list, const char *header_name)
720 {
721    struct list_entry *cur_entry;
722    char *ret = NULL;
723    size_t length = 0;
724
725    assert(header_list);
726    assert(header_name);
727    length = strlen(header_name);
728
729    for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
730    {
731       if (cur_entry->str)
732       {
733          if (!strncmpic(cur_entry->str, header_name, length))
734          {
735             /*
736              * Found: return pointer to start of value
737              */
738             ret = (char *) (cur_entry->str + length);
739             while (*ret && ijb_isspace(*ret)) ret++;
740             return(ret);
741          }
742       }
743    }
744
745    /* 
746     * Not found
747     */
748    return NULL;
749
750 }
751
752 /*********************************************************************
753  *
754  * Function    :  sed
755  *
756  * Description :  add, delete or modify lines in the HTTP header streams.
757  *                On entry, it receives a linked list of headers space
758  *                that was allocated dynamically (both the list nodes
759  *                and the header contents).
760  *
761  *                As a side effect it frees the space used by the original
762  *                header lines.
763  *
764  * Parameters  :
765  *          1  :  pats = list of patterns to match against headers
766  *          2  :  more_headers = list of functions to add more
767  *                headers (client or server)
768  *          3  :  csp = Current client state (buffers, headers, etc...)
769  *
770  * Returns     :  Single pointer to a fully formed header, or NULL
771  *                on out-of-memory error.
772  *
773  *********************************************************************/
774 char *sed(const struct parsers pats[],
775           const add_header_func_ptr more_headers[],
776           struct client_state *csp)
777 {
778    struct list_entry *p;
779    const struct parsers *v;
780    const add_header_func_ptr *f;
781    jb_err err = JB_ERR_OK;
782
783    for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
784    {
785       for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
786       {
787          /* Header crunch()ed in previous run? -> ignore */
788          if (p->str == NULL) continue;
789
790          if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
791
792          if (strncmpic(p->str, v->str, v->len) == 0)
793          {
794             err = v->parser(csp, (char **)&(p->str));
795          }
796       }
797    }
798
799    /* place any additional headers on the csp->headers list */
800    for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
801    {
802       err = (*f)(csp);
803    }
804
805    if (err != JB_ERR_OK)
806    {
807       return NULL;
808    }
809
810    return list_to_text(csp->headers);
811 }
812
813
814 /* here begins the family of parser functions that reformat header lines */
815
816
817 /*********************************************************************
818  *
819  * Function    :  crumble
820  *
821  * Description :  This is called if a header matches a pattern to "crunch"
822  *
823  * Parameters  :
824  *          1  :  csp = Current client state (buffers, headers, etc...)
825  *          2  :  header = On input, pointer to header to modify.
826  *                On output, pointer to the modified header, or NULL
827  *                to remove the header.  This function frees the
828  *                original string if necessary.
829  *
830  * Returns     :  JB_ERR_OK on success, or
831  *                JB_ERR_MEMORY on out-of-memory error.
832  *
833  *********************************************************************/
834 jb_err crumble(struct client_state *csp, char **header)
835 {
836    log_error(LOG_LEVEL_HEADER, "crunch!");
837    freez(*header);
838    return JB_ERR_OK;
839 }
840
841
842 /*********************************************************************
843  *
844  * Function    :  server_content_type
845  *
846  * Description :  Set the content-type for filterable types (text/.*,
847  *                javascript and image/gif) unless filtering has been
848  *                forbidden (CT_TABOO) while parsing earlier headers.
849  *                NOTE: Since text/plain is commonly used by web servers
850  *                      for files whose correct type is unknown, we don't
851  *                      set CT_TEXT for it.
852  *
853  * Parameters  :
854  *          1  :  csp = Current client state (buffers, headers, etc...)
855  *          2  :  header = On input, pointer to header to modify.
856  *                On output, pointer to the modified header, or NULL
857  *                to remove the header.  This function frees the
858  *                original string if necessary.
859  *
860  * Returns     :  JB_ERR_OK on success, or
861  *                JB_ERR_MEMORY on out-of-memory error.
862  *
863  *********************************************************************/
864 jb_err server_content_type(struct client_state *csp, char **header)
865 {
866    if (csp->content_type != CT_TABOO)
867    {
868       if ((strstr(*header, " text/") && !strstr(*header, "plain"))
869        || strstr(*header, "application/x-javascript"))
870          csp->content_type = CT_TEXT;
871       else if (strstr(*header, " image/gif"))
872          csp->content_type = CT_GIF;
873       else if (strstr(*header, " image/jpeg"))
874          csp->content_type = CT_JPEG;
875       else
876          csp->content_type = 0;
877    }
878
879    return JB_ERR_OK;
880 }
881
882
883 /*********************************************************************
884  *
885  * Function    :  server_transfer_coding
886  *
887  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
888  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
889  *                - Change from "chunked" to "identity" if body was chunked
890  *                  but has been de-chunked for filtering.
891  *
892  * Parameters  :
893  *          1  :  csp = Current client state (buffers, headers, etc...)
894  *          2  :  header = On input, pointer to header to modify.
895  *                On output, pointer to the modified header, or NULL
896  *                to remove the header.  This function frees the
897  *                original string if necessary.
898  *
899  * Returns     :  JB_ERR_OK on success, or
900  *                JB_ERR_MEMORY on out-of-memory error.
901  *
902  *********************************************************************/
903 jb_err server_transfer_coding(struct client_state *csp, char **header)
904 {
905    /*
906     * Turn off pcrs and gif filtering if body compressed
907     */
908    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
909    {
910       csp->content_type = CT_TABOO;
911    }
912
913    /*
914     * Raise flag if body chunked
915     */
916    if (strstr(*header, "chunked"))
917    {
918       csp->flags |= CSP_FLAG_CHUNKED;
919
920       /*
921        * If the body was modified, it has been
922        * de-chunked first, so adjust the header:
923        */
924       if (csp->flags & CSP_FLAG_MODIFIED)
925       {
926          freez(*header);
927          *header = strdup("Transfer-Encoding: identity");
928          return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
929       }
930    }
931
932    return JB_ERR_OK;
933 }
934
935
936 /*********************************************************************
937  *
938  * Function    :  server_content_encoding
939  *
940  * Description :  Prohibit filtering (CT_TABOO) if content encoding compresses
941  *
942  * Parameters  :
943  *          1  :  csp = Current client state (buffers, headers, etc...)
944  *          2  :  header = On input, pointer to header to modify.
945  *                On output, pointer to the modified header, or NULL
946  *                to remove the header.  This function frees the
947  *                original string if necessary.
948  *
949  * Returns     :  JB_ERR_OK on success, or
950  *                JB_ERR_MEMORY on out-of-memory error.
951  *
952  *********************************************************************/
953 jb_err server_content_encoding(struct client_state *csp, char **header)
954 {
955    /*
956     * Turn off pcrs and gif filtering if body compressed
957     */
958    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
959    {
960       csp->content_type = CT_TABOO;
961    }
962
963    return JB_ERR_OK;
964
965 }
966
967
968 /*********************************************************************
969  *
970  * Function    :  server_content_length
971  *
972  * Description :  Adjust Content-Length header if we modified
973  *                the body.
974  *
975  * Parameters  :
976  *          1  :  csp = Current client state (buffers, headers, etc...)
977  *          2  :  header = On input, pointer to header to modify.
978  *                On output, pointer to the modified header, or NULL
979  *                to remove the header.  This function frees the
980  *                original string if necessary.
981  *
982  * Returns     :  JB_ERR_OK on success, or
983  *                JB_ERR_MEMORY on out-of-memory error.
984  *
985  *********************************************************************/
986 jb_err server_content_length(struct client_state *csp, char **header)
987 {
988    if (csp->content_length != 0) /* Content length has been modified */
989    {
990       freez(*header);
991       *header = (char *) zalloc(100);
992       if (*header == NULL)
993       {
994          return JB_ERR_MEMORY;
995       }
996
997       sprintf(*header, "Content-Length: %d", (int) csp->content_length);
998
999       log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1000    }
1001
1002    return JB_ERR_OK;
1003 }
1004
1005
1006 /*********************************************************************
1007  *
1008  * Function    :  server_content_md5
1009  *
1010  * Description :  Crumble any Content-MD5 headers if the document was
1011  *                modified. FIXME: Should we re-compute instead?
1012  *
1013  * Parameters  :
1014  *          1  :  csp = Current client state (buffers, headers, etc...)
1015  *          2  :  header = On input, pointer to header to modify.
1016  *                On output, pointer to the modified header, or NULL
1017  *                to remove the header.  This function frees the
1018  *                original string if necessary.
1019  *
1020  * Returns     :  JB_ERR_OK on success, or
1021  *                JB_ERR_MEMORY on out-of-memory error.
1022  *
1023  *********************************************************************/
1024 jb_err server_content_md5(struct client_state *csp, char **header)
1025 {
1026    if (csp->flags & CSP_FLAG_MODIFIED)
1027    {
1028       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1029       freez(*header);
1030    }
1031
1032    return JB_ERR_OK;
1033 }
1034
1035
1036 /*********************************************************************
1037  *
1038  * Function    :  client_accept_encoding
1039  *
1040  * Description :  Rewrite the client's Accept-Encoding header so that
1041  *                if doesn't allow compression, if the action applies.
1042  *                Note: For HTTP/1.0 the absence of the header is enough.
1043  *
1044  * Parameters  :
1045  *          1  :  csp = Current client state (buffers, headers, etc...)
1046  *          2  :  header = On input, pointer to header to modify.
1047  *                On output, pointer to the modified header, or NULL
1048  *                to remove the header.  This function frees the
1049  *                original string if necessary.
1050  *
1051  * Returns     :  JB_ERR_OK on success, or
1052  *                JB_ERR_MEMORY on out-of-memory error.
1053  *
1054  *********************************************************************/
1055 jb_err client_accept_encoding(struct client_state *csp, char **header)
1056 {
1057    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1058    {
1059       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1060
1061       freez(*header);
1062
1063       /* Temporarily disable the correct behaviour to
1064        * work around a PHP bug. 
1065        *
1066        * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1067        * {
1068        *    *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1069        *    if (*header == NULL)
1070        *    {
1071        *       return JB_ERR_MEMORY;
1072        *    }
1073        * }
1074        * 
1075        */
1076    }
1077
1078    return JB_ERR_OK;
1079 }
1080
1081
1082 /*********************************************************************
1083  *
1084  * Function    :  client_te
1085  *
1086  * Description :  Rewrite the client's TE header so that
1087  *                if doesn't allow compression, if the action applies.
1088  *
1089  * Parameters  :
1090  *          1  :  csp = Current client state (buffers, headers, etc...)
1091  *          2  :  header = On input, pointer to header to modify.
1092  *                On output, pointer to the modified header, or NULL
1093  *                to remove the header.  This function frees the
1094  *                original string if necessary.
1095  *
1096  * Returns     :  JB_ERR_OK on success, or
1097  *                JB_ERR_MEMORY on out-of-memory error.
1098  *
1099  *********************************************************************/
1100 jb_err client_te(struct client_state *csp, char **header)
1101 {
1102    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1103    {
1104       freez(*header);
1105       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1106    }
1107
1108    return JB_ERR_OK;
1109 }
1110
1111 /*********************************************************************
1112  *
1113  * Function    :  client_referrer
1114  *
1115  * Description :  Handle the "referer" config setting properly.
1116  *                Called from `sed'.
1117  *
1118  * Parameters  :
1119  *          1  :  csp = Current client state (buffers, headers, etc...)
1120  *          2  :  header = On input, pointer to header to modify.
1121  *                On output, pointer to the modified header, or NULL
1122  *                to remove the header.  This function frees the
1123  *                original string if necessary.
1124  *
1125  * Returns     :  JB_ERR_OK on success, or
1126  *                JB_ERR_MEMORY on out-of-memory error.
1127  *
1128  *********************************************************************/
1129 jb_err client_referrer(struct client_state *csp, char **header)
1130 {
1131    const char *newval;
1132
1133 #ifdef FEATURE_FORCE_LOAD
1134    /* Since the referrer can include the prefix even
1135     * even if the request itself is non-forced, we must
1136     * clean it unconditionally
1137     */
1138    strclean(*header, FORCE_PREFIX);
1139 #endif /* def FEATURE_FORCE_LOAD */
1140
1141    /*
1142     * Are we sending referer?
1143     */
1144    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1145    {
1146       return JB_ERR_OK;
1147    }
1148
1149    freez(*header);
1150
1151    newval = csp->action->string[ACTION_STRING_REFERER];
1152
1153    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1154    {
1155       /*
1156        * Blocking referer
1157        */
1158       log_error(LOG_LEVEL_HEADER, "crunch!");
1159       return JB_ERR_OK;
1160    }
1161    else if (0 == strncmpic(newval, "http://", 7))
1162    {
1163       /*
1164        * We have a specific (fixed) referer we want to send.
1165        */
1166       log_error(LOG_LEVEL_HEADER, "modified");
1167
1168       *header = strdup("Referer: ");
1169       string_append(header, newval);
1170
1171       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1172    }
1173    else
1174    {
1175       /*
1176        * Forge a referer as http://[hostname:port of REQUEST]/
1177        * to fool stupid checks for in-site links
1178        */
1179       if (0 != strcmpic(newval, "forge"))
1180       {
1181          /*
1182           * Invalid choice - but forge is probably the best default.
1183           */
1184          log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1185       }
1186
1187       *header = strdup("Referer: http://");
1188       string_append(header, csp->http->hostport);
1189       string_append(header, "/");
1190       log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1191       
1192       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1193    }
1194 }
1195
1196
1197 /*********************************************************************
1198  *
1199  * Function    :  client_uagent
1200  *
1201  * Description :  Handle the "user-agent" config setting properly
1202  *                and remember its original value to enable browser
1203  *                bug workarounds. Called from `sed'.
1204  *
1205  * Parameters  :
1206  *          1  :  csp = Current client state (buffers, headers, etc...)
1207  *          2  :  header = On input, pointer to header to modify.
1208  *                On output, pointer to the modified header, or NULL
1209  *                to remove the header.  This function frees the
1210  *                original string if necessary.
1211  *
1212  * Returns     :  JB_ERR_OK on success, or
1213  *                JB_ERR_MEMORY on out-of-memory error.
1214  *
1215  *********************************************************************/
1216 jb_err client_uagent(struct client_state *csp, char **header)
1217 {
1218    const char *newval;
1219
1220    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1221    {
1222       return JB_ERR_OK;
1223    }
1224
1225    newval = csp->action->string[ACTION_STRING_USER_AGENT];
1226    if (newval == NULL)
1227    {
1228       return JB_ERR_OK;
1229    }
1230
1231    log_error(LOG_LEVEL_HEADER, "modified");
1232
1233    freez(*header);
1234    *header = strdup("User-Agent: ");
1235    string_append(header, newval);
1236
1237    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1238 }
1239
1240
1241 /*********************************************************************
1242  *
1243  * Function    :  client_ua
1244  *
1245  * Description :  Handle "ua-" headers properly.  Called from `sed'.
1246  *
1247  * Parameters  :
1248  *          1  :  csp = Current client state (buffers, headers, etc...)
1249  *          2  :  header = On input, pointer to header to modify.
1250  *                On output, pointer to the modified header, or NULL
1251  *                to remove the header.  This function frees the
1252  *                original string if necessary.
1253  *
1254  * Returns     :  JB_ERR_OK on success, or
1255  *                JB_ERR_MEMORY on out-of-memory error.
1256  *
1257  *********************************************************************/
1258 jb_err client_ua(struct client_state *csp, char **header)
1259 {
1260    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1261    {
1262       log_error(LOG_LEVEL_HEADER, "crunch!");
1263       freez(*header);
1264    }
1265
1266    return JB_ERR_OK;
1267 }
1268
1269
1270 /*********************************************************************
1271  *
1272  * Function    :  client_from
1273  *
1274  * Description :  Handle the "from" config setting properly.
1275  *                Called from `sed'.
1276  *
1277  * Parameters  :
1278  *          1  :  csp = Current client state (buffers, headers, etc...)
1279  *          2  :  header = On input, pointer to header to modify.
1280  *                On output, pointer to the modified header, or NULL
1281  *                to remove the header.  This function frees the
1282  *                original string if necessary.
1283  *
1284  * Returns     :  JB_ERR_OK on success, or
1285  *                JB_ERR_MEMORY on out-of-memory error.
1286  *
1287  *********************************************************************/
1288 jb_err client_from(struct client_state *csp, char **header)
1289 {
1290    const char *newval;
1291
1292    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1293    {
1294       return JB_ERR_OK;
1295    }
1296
1297    freez(*header);
1298
1299    newval = csp->action->string[ACTION_STRING_FROM];
1300
1301    /*
1302     * Are we blocking the e-mail address?
1303     */
1304    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1305    {
1306       log_error(LOG_LEVEL_HEADER, "crunch!");
1307       return JB_ERR_OK;
1308    }
1309
1310    log_error(LOG_LEVEL_HEADER, " modified");
1311
1312    *header = strdup("From: ");
1313    string_append(header, newval);
1314
1315    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1316 }
1317
1318
1319 /*********************************************************************
1320  *
1321  * Function    :  client_send_cookie
1322  *
1323  * Description :  Handle the "cookie" header properly.  Called from `sed'.
1324  *                If cookie is accepted, add it to the cookie_list,
1325  *                else we crunch it.  Mmmmmmmmmmm ... cookie ......
1326  *
1327  * Parameters  :
1328  *          1  :  csp = Current client state (buffers, headers, etc...)
1329  *          2  :  header = On input, pointer to header to modify.
1330  *                On output, pointer to the modified header, or NULL
1331  *                to remove the header.  This function frees the
1332  *                original string if necessary.
1333  *
1334  * Returns     :  JB_ERR_OK on success, or
1335  *                JB_ERR_MEMORY on out-of-memory error.
1336  *
1337  *********************************************************************/
1338 jb_err client_send_cookie(struct client_state *csp, char **header)
1339 {
1340    jb_err result = JB_ERR_OK;
1341
1342    if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1343    {
1344       /* strlen("cookie: ") == 8 */
1345       result = enlist(csp->cookie_list, *header + 8);
1346    }
1347    else
1348    {
1349       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
1350    }
1351
1352    /*
1353     * Always remove the cookie here.  The cookie header
1354     * will be sent at the end of the header.
1355     */
1356    freez(*header);
1357
1358    return result;
1359 }
1360
1361
1362 /*********************************************************************
1363  *
1364  * Function    :  client_x_forwarded
1365  *
1366  * Description :  Handle the "x-forwarded-for" config setting properly,
1367  *                also used in the add_client_headers list.  Called from `sed'.
1368  *
1369  * Parameters  :
1370  *          1  :  csp = Current client state (buffers, headers, etc...)
1371  *          2  :  header = On input, pointer to header to modify.
1372  *                On output, pointer to the modified header, or NULL
1373  *                to remove the header.  This function frees the
1374  *                original string if necessary.
1375  *
1376  * Returns     :  JB_ERR_OK on success, or
1377  *                JB_ERR_MEMORY on out-of-memory error.
1378  *
1379  *********************************************************************/
1380 jb_err client_x_forwarded(struct client_state *csp, char **header)
1381 {
1382    if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1383    {
1384       /* Save it so we can re-add it later */
1385       freez(csp->x_forwarded);
1386       csp->x_forwarded = *header;
1387
1388       /*
1389        * Always set *header = NULL, since this information
1390        * will be sent at the end of the header.
1391        */
1392       *header = NULL;
1393    }
1394    else
1395    {
1396       freez(*header);
1397       log_error(LOG_LEVEL_HEADER, " crunch!");
1398    }
1399
1400    return JB_ERR_OK;
1401 }
1402
1403
1404 /*********************************************************************
1405  *
1406  * Function    :  client_max_forwards
1407  *
1408  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
1409  *                from the value of the Max-Forwards header field.
1410  *
1411  * Parameters  :
1412  *          1  :  csp = Current client state (buffers, headers, etc...)
1413  *          2  :  header = On input, pointer to header to modify.
1414  *                On output, pointer to the modified header, or NULL
1415  *                to remove the header.  This function frees the
1416  *                original string if necessary.
1417  *
1418  * Returns     :  JB_ERR_OK on success, or
1419  *                JB_ERR_MEMORY on out-of-memory error.
1420  *
1421  *********************************************************************/
1422 jb_err client_max_forwards(struct client_state *csp, char **header)
1423 {
1424    unsigned int max_forwards;
1425
1426    if ((0 == strcmpic(csp->http->gpc, "trace"))
1427       || (0 == strcmpic(csp->http->gpc, "options")))
1428    {
1429       if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
1430       {
1431          if (max_forwards-- >= 1)
1432          {
1433             sprintf(*header, "Max-Forwards: %u", max_forwards);
1434             log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
1435          }
1436          else
1437          {
1438             log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
1439          }
1440       }
1441    }
1442
1443    return JB_ERR_OK;
1444 }
1445
1446
1447 /*********************************************************************
1448  *
1449  * Function    :  client_host
1450  *
1451  * Description :  If the request URI did not contain host and
1452  *                port information, parse and evaluate the Host
1453  *                header field.
1454  *
1455  *                Also, kill ill-formed HOST: headers as sent by
1456  *                Apple's iTunes software when used with a proxy.
1457  *
1458  * Parameters  :
1459  *          1  :  csp = Current client state (buffers, headers, etc...)
1460  *          2  :  header = On input, pointer to header to modify.
1461  *                On output, pointer to the modified header, or NULL
1462  *                to remove the header.  This function frees the
1463  *                original string if necessary.
1464  *
1465  * Returns     :  JB_ERR_OK on success, or
1466  *                JB_ERR_MEMORY on out-of-memory error.
1467  *
1468  *********************************************************************/
1469 jb_err client_host(struct client_state *csp, char **header)
1470 {
1471    char *p, *q;
1472
1473    /*
1474     * If the header field name is all upper-case, chances are that it's
1475     * an ill-formed one from iTunes. BTW, killing innocent headers here is
1476     * not a problem -- they are regenerated later.
1477     */
1478    if ((*header)[1] == 'O')
1479    {
1480       log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
1481       freez(*header);
1482       return JB_ERR_OK;
1483    }
1484
1485    if (!csp->http->hostport || (*csp->http->hostport == '*') ||  
1486        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
1487    {
1488       
1489       if (NULL == (p = strdup((*header)+6)))
1490       {
1491          return JB_ERR_MEMORY;
1492       }
1493       chomp(p);
1494       if (NULL == (q = strdup(p)))
1495       {
1496          freez(p);
1497          return JB_ERR_MEMORY;
1498       }
1499
1500       freez(csp->http->hostport);
1501       csp->http->hostport = p;
1502       freez(csp->http->host);
1503       csp->http->host = q;
1504       q = strchr(csp->http->host, ':');
1505       if (q != NULL)
1506       {
1507          /* Terminate hostname and evaluate port string */
1508          *q++ = '\0';
1509          csp->http->port = atoi(q);
1510       }
1511       else
1512       {
1513          csp->http->port = csp->http->ssl ? 443 : 80;
1514       }
1515
1516       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
1517                 csp->http->hostport, csp->http->host, csp->http->port);
1518    }
1519
1520    return JB_ERR_OK;
1521 }
1522
1523
1524 /* the following functions add headers directly to the header list */
1525
1526 /*********************************************************************
1527  *
1528  * Function    :  client_host_adder
1529  *
1530  * Description :  Adds the Host: header field if it is missing.
1531  *                Called from `sed'.
1532  *
1533  * Parameters  :
1534  *          1  :  csp = Current client state (buffers, headers, etc...)
1535  *
1536  * Returns     :  JB_ERR_OK on success, or
1537  *                JB_ERR_MEMORY on out-of-memory error.
1538  *
1539  *********************************************************************/
1540 jb_err client_host_adder(struct client_state *csp)
1541 {
1542    char *p;
1543    jb_err err;
1544
1545    if ( !csp->http->hostport || !*(csp->http->hostport))
1546    {
1547       return JB_ERR_OK;
1548    }
1549
1550    /*
1551     * remove 'user:pass@' from 'proto://user:pass@host'
1552     */
1553    if ( (p = strchr( csp->http->hostport, '@')) != NULL )
1554    {
1555       p++;
1556    }
1557    else
1558    {
1559       p = csp->http->hostport;
1560    }
1561
1562    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
1563    err = enlist_unique_header(csp->headers, "Host", p);
1564    return err;
1565
1566 }
1567
1568
1569 /*********************************************************************
1570  *
1571  * Function    :  client_cookie_adder
1572  *
1573  * Description :  Used in the add_client_headers list.  Called from `sed'.
1574  *
1575  * Parameters  :
1576  *          1  :  csp = Current client state (buffers, headers, etc...)
1577  *
1578  * Returns     :  JB_ERR_OK on success, or
1579  *                JB_ERR_MEMORY on out-of-memory error.
1580  *
1581  *********************************************************************/
1582 jb_err client_cookie_adder(struct client_state *csp)
1583 {
1584    struct list_entry *lst;
1585    char *tmp;
1586    struct list_entry *list1 = csp->cookie_list->first;
1587    struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1588    int first_cookie = 1;
1589    jb_err err;
1590
1591    if ((list1 == NULL) && (list2 == NULL))
1592    {
1593       /* Nothing to do */
1594       return JB_ERR_OK;
1595    }
1596
1597    tmp = strdup("Cookie: ");
1598
1599    for (lst = list1; lst ; lst = lst->next)
1600    {
1601       if (first_cookie)
1602       {
1603          first_cookie = 0;
1604       }
1605       else
1606       {
1607          string_append(&tmp, "; ");
1608       }
1609       string_append(&tmp, lst->str);
1610    }
1611
1612    for (lst = list2;  lst ; lst = lst->next)
1613    {
1614       if (first_cookie)
1615       {
1616          first_cookie = 0;
1617       }
1618       else
1619       {
1620          string_append(&tmp, "; ");
1621       }
1622       string_join(&tmp, cookie_encode(lst->str));
1623    }
1624
1625    if (tmp == NULL)
1626    {
1627       return JB_ERR_MEMORY;
1628    }
1629
1630    log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1631    err = enlist(csp->headers, tmp);
1632    free(tmp);
1633    return err;
1634 }
1635
1636
1637 /*********************************************************************
1638  *
1639  * Function    :  client_accept_encoding_adder
1640  *
1641  * Description :  Add an Accept-Encoding header to the client's request
1642  *                that disables compression if the action applies, and
1643  *                the header is not already there. Called from `sed'.
1644  *                Note: For HTTP/1.0, the absence of the header is enough.
1645  *
1646  * Parameters  :
1647  *          1  :  csp = Current client state (buffers, headers, etc...)
1648  *
1649  * Returns     :  JB_ERR_OK on success, or
1650  *                JB_ERR_MEMORY on out-of-memory error.
1651  *
1652  *********************************************************************/
1653 jb_err client_accept_encoding_adder(struct client_state *csp)
1654 {
1655    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1656        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1657    {
1658       return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1659    }
1660
1661    return JB_ERR_OK;
1662 }
1663
1664
1665 /*********************************************************************
1666  *
1667  * Function    :  client_xtra_adder
1668  *
1669  * Description :  Used in the add_client_headers list.  Called from `sed'.
1670  *
1671  * Parameters  :
1672  *          1  :  csp = Current client state (buffers, headers, etc...)
1673  *
1674  * Returns     :  JB_ERR_OK on success, or
1675  *                JB_ERR_MEMORY on out-of-memory error.
1676  *
1677  *********************************************************************/
1678 jb_err client_xtra_adder(struct client_state *csp)
1679 {
1680    struct list_entry *lst;
1681    jb_err err;
1682
1683    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1684         lst ; lst = lst->next)
1685    {
1686       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1687       err = enlist(csp->headers, lst->str);
1688       if (err)
1689       {
1690          return err;
1691       }
1692
1693    }
1694
1695    return JB_ERR_OK;
1696 }
1697
1698
1699 /*********************************************************************
1700  *
1701  * Function    :  client_x_forwarded_adder
1702  *
1703  * Description :  Used in the add_client_headers list.  Called from `sed'.
1704  *
1705  * Parameters  :
1706  *          1  :  csp = Current client state (buffers, headers, etc...)
1707  *
1708  * Returns     :  JB_ERR_OK on success, or
1709  *                JB_ERR_MEMORY on out-of-memory error.
1710  *
1711  *********************************************************************/
1712 jb_err client_x_forwarded_adder(struct client_state *csp)
1713 {
1714    char *p = NULL;
1715    jb_err err;
1716
1717    if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1718    {
1719       return JB_ERR_OK;
1720    }
1721
1722    if (csp->x_forwarded)
1723    {
1724       p = strdup(csp->x_forwarded);
1725       string_append(&p, ", ");
1726    }
1727    else
1728    {
1729       p = strdup("X-Forwarded-For: ");
1730    }
1731    string_append(&p, csp->ip_addr_str);
1732
1733    if (p == NULL)
1734    {
1735       return JB_ERR_MEMORY;
1736    }
1737
1738    log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1739    err = enlist(csp->headers, p);
1740    free(p);
1741
1742    return err;
1743 }
1744
1745
1746 /*********************************************************************
1747  *
1748  * Function    :  connection_close_adder
1749  *
1750  * Description :  Adds a "Connection: close" header to csp->headers
1751  *                as a temporary fix for the needed but missing HTTP/1.1
1752  *                support. Called from `sed'.
1753  *                FIXME: This whole function shouldn't be neccessary!
1754  *
1755  * Parameters  :
1756  *          1  :  csp = Current client state (buffers, headers, etc...)
1757  *
1758  * Returns     :  JB_ERR_OK on success, or
1759  *                JB_ERR_MEMORY on out-of-memory error.
1760  *
1761  *********************************************************************/
1762 jb_err connection_close_adder(struct client_state *csp)
1763 {
1764    return enlist(csp->headers, "Connection: close");
1765 }
1766
1767
1768 /*********************************************************************
1769  *
1770  * Function    :  server_http
1771  *
1772  * Description :  - Save the HTTP Status into csp->http->status
1773  *                - Set CT_TABOO to prevent filtering if the answer
1774  *                  is a partial range (HTTP status 206)
1775  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1776  *                  action applies.
1777  *
1778  * Parameters  :
1779  *          1  :  csp = Current client state (buffers, headers, etc...)
1780  *          2  :  header = On input, pointer to header to modify.
1781  *                On output, pointer to the modified header, or NULL
1782  *                to remove the header.  This function frees the
1783  *                original string if necessary.
1784  *
1785  * Returns     :  JB_ERR_OK on success, or
1786  *                JB_ERR_MEMORY on out-of-memory error.
1787  *
1788  *********************************************************************/
1789 jb_err server_http(struct client_state *csp, char **header)
1790 {
1791    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1792    if (csp->http->status == 206)
1793    {
1794       csp->content_type = CT_TABOO;
1795    }
1796
1797    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1798    {
1799       (*header)[7] = '0';
1800       log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1801    }
1802
1803    return JB_ERR_OK;
1804 }
1805
1806
1807 /*********************************************************************
1808  *
1809  * Function    :  server_set_cookie
1810  *
1811  * Description :  Handle the server "cookie" header properly.
1812  *                Log cookie to the jar file.  Then "crunch" it,
1813  *                or accept it.  Called from `sed'.
1814  *
1815  * Parameters  :
1816  *          1  :  csp = Current client state (buffers, headers, etc...)
1817  *          2  :  header = On input, pointer to header to modify.
1818  *                On output, pointer to the modified header, or NULL
1819  *                to remove the header.  This function frees the
1820  *                original string if necessary.
1821  *
1822  * Returns     :  JB_ERR_OK on success, or
1823  *                JB_ERR_MEMORY on out-of-memory error.
1824  *
1825  *********************************************************************/
1826 jb_err server_set_cookie(struct client_state *csp, char **header)
1827 {
1828 #ifdef FEATURE_COOKIE_JAR
1829    if (csp->config->jar)
1830    {
1831       /*
1832        * Write timestamp into outbuf.
1833        *
1834        * Complex because not all OSs have tm_gmtoff or
1835        * the %z field in strftime()
1836        */
1837       char tempbuf[ BUFFER_SIZE ];
1838       time_t now; 
1839       struct tm tm_now; 
1840       time (&now); 
1841 #ifdef HAVE_LOCALTIME_R
1842       tm_now = *localtime_r(&now, &tm_now);
1843 #elif OSX_DARWIN
1844       pthread_mutex_lock(&localtime_mutex);
1845       tm_now = *localtime (&now); 
1846       pthread_mutex_unlock(&localtime_mutex);
1847 #else
1848       tm_now = *localtime (&now); 
1849 #endif
1850       strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
1851
1852       /* strlen("set-cookie: ") = 12 */
1853       fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1854    }
1855 #endif /* def FEATURE_COOKIE_JAR */
1856
1857    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1858    {
1859       log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
1860       return crumble(csp, header);
1861    }
1862    else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1863    {
1864       /* Flag whether or not to log a message */
1865       int changed = 0;
1866
1867       /* A variable to store the tag we're working on */
1868       char *cur_tag;
1869
1870       /* Skip "Set-Cookie:" (11 characters) in header */
1871       cur_tag = *header + 11;
1872
1873       /* skip whitespace between "Set-Cookie:" and value */
1874       while (*cur_tag && ijb_isspace(*cur_tag))
1875       {
1876          cur_tag++;
1877       }
1878
1879       /* Loop through each tag in the cookie */
1880       while (*cur_tag)
1881       {
1882          /* Find next tag */
1883          char *next_tag = strchr(cur_tag, ';');
1884          if (next_tag != NULL)
1885          {
1886             /* Skip the ';' character itself */
1887             next_tag++;
1888
1889             /* skip whitespace ";" and start of tag */
1890             while (*next_tag && ijb_isspace(*next_tag))
1891             {
1892                next_tag++;
1893             }
1894          }
1895          else
1896          {
1897             /* "Next tag" is the end of the string */
1898             next_tag = cur_tag + strlen(cur_tag);
1899          }
1900
1901          /* Is this the "Expires" tag? */
1902          if (strncmpic(cur_tag, "expires=", 8) == 0)
1903          {
1904             /* Delete the tag by copying the rest of the string over it.
1905              * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1906              * since the behaviour of strcpy is undefined for overlapping
1907              * strings.)
1908              */
1909             memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1910
1911             /* That changed the header, need to issue a log message */
1912             changed = 1;
1913
1914             /* Note that the next tag has now been moved to *cur_tag,
1915              * so we do not need to update the cur_tag pointer.
1916              */
1917          }
1918          else
1919          {
1920             /* Move on to next cookie tag */
1921             cur_tag = next_tag;
1922          }
1923       }
1924
1925       if (changed)
1926       {
1927          log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1928       }
1929    }
1930
1931    return JB_ERR_OK;
1932 }
1933
1934
1935 #ifdef FEATURE_FORCE_LOAD
1936 /*********************************************************************
1937  *
1938  * Function    :  strclean
1939  *
1940  * Description :  In-Situ-Eliminate all occurances of substring in
1941  *                string
1942  *
1943  * Parameters  :
1944  *          1  :  string = string to clean
1945  *          2  :  substring = substring to eliminate
1946  *
1947  * Returns     :  Number of eliminations
1948  *
1949  *********************************************************************/
1950 int strclean(const char *string, const char *substring)
1951 {
1952    int hits = 0, len = strlen(substring);
1953    char *pos, *p;
1954
1955    while((pos = strstr(string, substring)) != NULL)
1956    {
1957       p = pos + len;
1958       do
1959       {
1960          *(p - len) = *p;
1961       }
1962       while (*p++ != '\0');
1963
1964       hits++;
1965    }
1966
1967    return(hits);
1968 }
1969 #endif /* def FEATURE_FORCE_LOAD */
1970
1971
1972 /*
1973   Local Variables:
1974   tab-width: 3
1975   end:
1976 */