Update ChageLog (mostly to test my CVS access on a CYGWIN machine)
[privoxy.git] / src / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 2.5 2003/01/26 20:24:26 david__schmidt Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/src/jcc.c,v $
5  *
6  * Purpose     :  Main file.  Contains main() method, main loop, and
7  *                the main connection-handling function.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: jcc.c,v $
36  *    Revision 2.5  2003/01/26 20:24:26  david__schmidt
37  *    Updated activity console instrumentation locations
38  *
39  *    Revision 2.4  2002/12/28 03:58:19  david__schmidt
40  *    Initial drop of dashboard instrumentation - enabled with
41  *    --enable-activity-console
42  *
43  *    Revision 2.3  2002/07/18 22:06:12  jongfoster
44  *    Trivial formatting changes
45  *
46  *    Revision 2.2  2002/07/12 04:26:17  agotneja
47  *    Re-factored 'chat()' to become understandable and maintainable as
48  *    a first step in adding Transparent Proxy functionality.
49  *
50  *    Added several new static functions in jcc.c, and moved some data
51  *    parameters up into project.h to allow them to be passed between
52  *    the new functions.
53  *
54  *    Revision 1.91  2002/04/08 20:35:58  swa
55  *    fixed JB spelling
56  *
57  *    Revision 1.90  2002/04/02 14:57:28  oes
58  *    Made sending wafers independent of FEATURE_COOKIE_JAR
59  *
60  *    Revision 1.89  2002/03/31 17:18:59  jongfoster
61  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
62  *
63  *    Revision 1.88  2002/03/27 14:32:43  david__schmidt
64  *    More compiler warning message maintenance
65  *
66  *    Revision 1.87  2002/03/26 22:29:54  swa
67  *    we have a new homepage!
68  *
69  *    Revision 1.86  2002/03/25 17:04:55  david__schmidt
70  *    Workaround for closing the jarfile before load_config() comes around again
71  *
72  *    Revision 1.85  2002/03/24 15:23:33  jongfoster
73  *    Name changes
74  *
75  *    Revision 1.84  2002/03/24 13:25:43  swa
76  *    name change related issues
77  *
78  *    Revision 1.83  2002/03/16 23:54:06  jongfoster
79  *    Adding graceful termination feature, to help look for memory leaks.
80  *    If you enable this (which, by design, has to be done by hand
81  *    editing config.h) and then go to http://i.j.b/die, then the program
82  *    will exit cleanly after the *next* request.  It should free all the
83  *    memory that was used.
84  *
85  *    Revision 1.82  2002/03/13 00:27:05  jongfoster
86  *    Killing warnings
87  *
88  *    Revision 1.81  2002/03/12 01:42:50  oes
89  *    Introduced modular filters
90  *
91  *    Revision 1.80  2002/03/11 22:07:05  david__schmidt
92  *    OS/2 port maintenance:
93  *    - Fixed EMX build - it had decayed a little
94  *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
95  *      substituted a memset for now.
96  *
97  *    Revision 1.79  2002/03/09 20:03:52  jongfoster
98  *    - Making various functions return int rather than size_t.
99  *      (Undoing a recent change).  Since size_t is unsigned on
100  *      Windows, functions like read_socket that return -1 on
101  *      error cannot return a size_t.
102  *
103  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
104  *      crashes, and also frequently caused JB to jump to 100%
105  *      CPU and stay there.  (Because it thought it had just
106  *      read ((unsigned)-1) == 4Gb of data...)
107  *
108  *    - The signature of write_socket has changed, it now simply
109  *      returns success=0/failure=nonzero.
110  *
111  *    - Trying to get rid of a few warnings --with-debug on
112  *      Windows, I've introduced a new type "jb_socket".  This is
113  *      used for the socket file descriptors.  On Windows, this
114  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
115  *      an int.  The error value can't be -1 any more, so it's
116  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
117  *      Windows it maps to the #define INVALID_SOCKET.)
118  *
119  *    - The signature of bind_port has changed.
120  *
121  *    Revision 1.78  2002/03/08 21:35:04  oes
122  *    Added optional group supplement to --user option. Will now use default group of user if no group given
123  *
124  *    Revision 1.77  2002/03/07 03:52:06  oes
125  *     - Fixed compiler warnings etc
126  *     - Improved handling of failed DNS lookups
127  *
128  *    Revision 1.76  2002/03/06 22:54:35  jongfoster
129  *    Automated function-comment nitpicking.
130  *
131  *    Revision 1.75  2002/03/06 10:02:19  oes
132  *    Fixed stupid bug when --user was not given
133  *
134  *    Revision 1.74  2002/03/06 00:49:31  jongfoster
135  *    Fixing warning on Windows
136  *    Making #ifdefs that refer to the same variable consistently
137  *    use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
138  *
139  *    Revision 1.73  2002/03/05 23:57:30  hal9
140  *    Stray character 's' on line 1618 was breaking build.
141  *
142  *    Revision 1.72  2002/03/05 21:33:45  david__schmidt
143  *    - Re-enable OS/2 building after new parms were added
144  *    - Fix false out of memory report when resolving CGI templates when no IP
145  *      address is available of failed attempt (a la no such domain)
146  *
147  *    Revision 1.71  2002/03/05 18:13:56  oes
148  *    Added --user option
149  *
150  *    Revision 1.70  2002/03/05 04:52:42  oes
151  *    Deleted non-errlog debugging code
152  *
153  *    Revision 1.69  2002/03/04 23:50:00  jongfoster
154  *    Splitting off bind_port() call into bind_port_helper(), with
155  *    improved logging.
156  *
157  *    Revision 1.68  2002/03/04 20:17:32  oes
158  *    Fixed usage info
159  *
160  *    Revision 1.67  2002/03/04 18:18:57  oes
161  *    - Removed _DEBUG mode
162  *    - Cleand up cmdline parsing
163  *    - Introduced --no-daemon, --pidfile options
164  *    - Cleaned up signal handling:
165  *      - Terminate cleanly on INT, TERM and ABRT
166  *      - Schedule logfile for re-opening on HUP
167  *      - Ignore CHLD and PIPE
168  *      - Leave the rest with their default handlers
169  *      - Uniform handler registration
170  *    - Added usage() function
171  *    - Played styleguide police
172  *
173  *    Revision 1.66  2002/03/03 15:06:55  oes
174  *    Re-enabled automatic config reloading
175  *
176  *    Revision 1.65  2002/03/03 14:49:11  oes
177  *    Fixed CLF logging: Now uses client's original HTTP request
178  *
179  *    Revision 1.64  2002/03/03 09:18:03  joergs
180  *    Made jumbjuster work on AmigaOS again.
181  *
182  *    Revision 1.63  2002/03/02 04:14:50  david__schmidt
183  *    Clean up a little CRLF unpleasantness that suddenly appeared
184  *
185  *    Revision 1.62  2002/02/20 23:17:23  jongfoster
186  *    Detecting some out-of memory conditions and exiting with a log message.
187  *
188  *    Revision 1.61  2002/01/17 21:01:52  jongfoster
189  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
190  *
191  *    Revision 1.60  2001/12/30 14:07:32  steudten
192  *    - Add signal handling (unix)
193  *    - Add SIGHUP handler (unix)
194  *    - Add creation of pidfile (unix)
195  *    - Add action 'top' in rc file (RH)
196  *    - Add entry 'SIGNALS' to manpage
197  *    - Add exit message to logfile (unix)
198  *
199  *    Revision 1.59  2001/12/13 14:07:18  oes
200  *    Fixed Bug: 503 error page now sent OK
201  *
202  *    Revision 1.58  2001/11/30 23:37:24  jongfoster
203  *    Renaming the Win32 config file to config.txt - this is almost the
204  *    same as the corresponding UNIX name "config"
205  *
206  *    Revision 1.57  2001/11/16 00:47:43  jongfoster
207  *    Changing the tty-disconnection code to use setsid().
208  *
209  *    Revision 1.56  2001/11/13 20:20:54  jongfoster
210  *    Tabs->spaces, fixing a bug with missing {} around an if()
211  *
212  *    Revision 1.55  2001/11/13 20:14:53  jongfoster
213  *    Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
214  *
215  *    Revision 1.54  2001/11/07 00:03:14  steudten
216  *    Give reliable return value if an error
217  *    occurs not just 0 with new daemon mode.
218  *
219  *    Revision 1.53  2001/11/05 21:41:43  steudten
220  *    Add changes to be a real daemon just for unix os.
221  *    (change cwd to /, detach from controlling tty, set
222  *    process group and session leader to the own process.
223  *    Add DBG() Macro.
224  *    Add some fatal-error log message for failed malloc().
225  *    Add '-d' if compiled with 'configure --with-debug' to
226  *    enable debug output.
227  *
228  *    Revision 1.52  2001/10/26 20:11:20  jongfoster
229  *    Fixing type mismatch
230  *
231  *    Revision 1.51  2001/10/26 17:38:28  oes
232  *    Cosmetics
233  *
234  *    Revision 1.50  2001/10/25 03:40:48  david__schmidt
235  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
236  *    threads to call select() simultaneously.  So, it's time to do a real, live,
237  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
238  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
239  *
240  *    Revision 1.49  2001/10/23 21:41:35  jongfoster
241  *    Added call to initialize the (statically-allocated of course)
242  *    "out of memory" CGI response.
243  *
244  *    Revision 1.48  2001/10/10 19:56:46  jongfoster
245  *    Moving some code that wasn't cookie-related out of an #ifdef
246  *    FEATURE_COOKIE_JAR
247  *
248  *    Revision 1.47  2001/10/10 16:44:36  oes
249  *    Added CONNECT destination port limitation check
250  *
251  *    Revision 1.46  2001/10/08 15:17:41  oes
252  *    Re-enabled SSL forwarding
253  *
254  *    Revision 1.45  2001/10/07 15:42:11  oes
255  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
256  *
257  *    Moved downgrading of the HTTP version from parse_http_request to
258  *      chat(), since we can't decide if it is necessary before we have
259  *      determined the actions for the URL. The HTTP command is now
260  *      *always* re-built so the repairs need no longer be special-cased.
261  *
262  *    filter_popups now gets a csp pointer so it can raise the new
263  *      CSP_FLAG_MODIFIED flag.
264  *
265  *    Bugfix
266  *
267  *    Added configurable size limit for the IOB. If the IOB grows so
268  *      large that the next read would exceed the limit, the header
269  *      is generated, and the header & unfiltered buffer are flushed
270  *      to the client. Chat then continues in non-buffering,
271  *      non-filtering body mode.
272  *
273  *    Revision 1.44  2001/10/02 18:13:57  oes
274  *    Ooops
275  *
276  *    Revision 1.43  2001/10/02 15:32:13  oes
277  *    Moved generation of hdr
278  *
279  *    Revision 1.42  2001/09/21 23:02:02  david__schmidt
280  *    Cleaning up 2 compiler warnings on OS/2.
281  *
282  *    Revision 1.41  2001/09/16 17:05:14  jongfoster
283  *    Removing unused #include showarg.h
284  *
285  *    Revision 1.40  2001/09/16 15:41:45  jongfoster
286  *    Fixing signed/unsigned comparison warning.
287  *
288  *    Revision 1.39  2001/09/16 13:21:27  jongfoster
289  *    Changes to use new list functions.
290  *
291  *    Revision 1.38  2001/09/16 13:01:46  jongfoster
292  *    Removing redundant function call that zeroed zalloc()'d memory.
293  *
294  *    Revision 1.37  2001/09/10 11:12:24  oes
295  *    Deleted unused variable
296  *
297  *    Revision 1.36  2001/09/10 10:56:15  oes
298  *    Silenced compiler warnings
299  *
300  *    Revision 1.35  2001/07/31 14:44:22  oes
301  *    Deleted unused size parameter from filter_popups()
302  *
303  *    Revision 1.34  2001/07/30 22:08:36  jongfoster
304  *    Tidying up #defines:
305  *    - All feature #defines are now of the form FEATURE_xxx
306  *    - Permanently turned off WIN_GUI_EDIT
307  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
308  *
309  *    Revision 1.33  2001/07/29 19:32:00  jongfoster
310  *    Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
311  *
312  *    Revision 1.32  2001/07/29 18:47:05  jongfoster
313  *    Adding missing #include "loadcfg.h"
314  *
315  *    Revision 1.31  2001/07/29 12:17:48  oes
316  *    Applied pthread fix by Paul Lieverse
317  *
318  *    Revision 1.30  2001/07/25 22:57:13  jongfoster
319  *    __BEOS__ no longer overrides FEATURE_PTHREAD.
320  *    This is because FEATURE_PTHREAD will soon be widely used, so I
321  *    want to keep it simple.
322  *
323  *    Revision 1.29  2001/07/24 12:47:06  oes
324  *    Applied BeOS support update by Eugenia
325  *
326  *    Revision 1.28  2001/07/23 13:26:12  oes
327  *    Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
328  *
329  *    Revision 1.27  2001/07/19 19:09:47  haroon
330  *    - Added code to take care of the situation where while processing the first
331  *      server response (which includes the server header), after finding the end
332  *      of the headers we were not looking past the end of the headers for
333  *      content modification. I enabled it for filter_popups.
334  *      Someone else should look to see if other similar operations should be
335  *      done to the discarded portion of the buffer.
336  *
337  *      Note 2001/07/20: No, the other content modification mechanisms will process
338  *                       the whole iob later anyway. --oes
339  *
340  *    Revision 1.26  2001/07/18 12:31:36  oes
341  *    cosmetics
342  *
343  *    Revision 1.25  2001/07/15 19:43:49  jongfoster
344  *    Supports POSIX threads.
345  *    Also removed some unused #includes.
346  *
347  *    Revision 1.24  2001/07/13 14:00:40  oes
348  *     - Generic content modification scheme:
349  *       Each feature has its own applicability flag that is set
350  *       from csp->action->flags.
351  *       Replaced the "filtering" int flag , by a function pointer
352  *       "content_filter" to the function that will do the content
353  *       modification. If it is != NULL, the document will be buffered
354  *       and processed through *content_filter, which must set
355  *       csp->content_length and return a modified copy of the body
356  *       or return NULL (on failiure).
357  *     - Changed csp->is_text to the more generic bitmap csp->content_type
358  *       which can currently take the valued CT_TEXT or CT_GIF
359  *     - Reformatting etc
360  *     - Removed all #ifdef PCRS
361  *
362  *    Revision 1.23  2001/07/02 02:28:25  iwanttokeepanon
363  *    Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
364  *    the `block_acl' call.  This prevents a compilation error when the user
365  *    does not wish to use the "ACL" feature.
366  *
367  *    Revision 1.22  2001/06/29 21:45:41  oes
368  *    Indentation, CRLF->LF, Tab-> Space
369  *
370  *    Revision 1.21  2001/06/29 13:29:36  oes
371  *    - Cleaned up, improved comments
372  *    - Unified all possible interceptors (CGI,
373  *      block, trust, fast_redirect) in one
374  *      place, with one (CGI) answer generation
375  *      mechansim. Much clearer now.
376  *    - Removed the GIF image generation, which
377  *      is now done in filters.c:block_url()
378  *    - Made error conditions like domain lookup
379  *      failiure or (various) problems while talking
380  *      to the server use cgi.c:error_response()
381  *      instead of generating HTML/HTTP in chat() (yuck!)
382  *    - Removed logentry from cancelled commit
383  *
384  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
385  *    Changing BUFSIZ ==> BUFFER_SIZE
386  *
387  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
388  *    Replacing function pointer in struct gateway with a directly
389  *    called function forwarded_connect().
390  *    Replacing struct gateway with struct forward_spec
391  *
392  *    Revision 1.18  2001/06/03 19:12:16  oes
393  *    introduced new cgi handling
394  *
395  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
396  *    Now uses action +image-blocker{} rather than config->tinygif
397  *
398  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
399  *    Replaced "list_share" with "list" - the tiny memory gain was not
400  *    worth the extra complexity.
401  *
402  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
403  *    Changed "permission" to "action" throughout.
404  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
405  *    Moved vanilla wafer check into chat(), since we must now
406  *    decide whether or not to add it based on the URL.
407  *
408  *    Revision 1.14  2001/05/29 20:14:01  joergs
409  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
410  *    increased.
411  *
412  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
413  *    Unified blocklist/imagelist/permissionslist.
414  *    File format is still under discussion, but the internal changes
415  *    are (mostly) done.
416  *
417  *    Also modified interceptor behaviour:
418  *    - We now intercept all URLs beginning with one of the following
419  *      prefixes (and *only* these prefixes):
420  *        * http://i.j.b/
421  *        * http://ijbswa.sf.net/config/
422  *        * http://ijbswa.sourceforge.net/config/
423  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
424  *    - Internal changes so that intercepted and fast redirect pages
425  *      are not replaced with an image.
426  *    - Interceptors now have the option to send a binary page direct
427  *      to the client. (i.e. ijb-send-banner uses this)
428  *    - Implemented show-url-info interceptor.  (Which is why I needed
429  *      the above interceptors changes - a typical URL is
430  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
431  *      The previous mechanism would not have intercepted that, and
432  *      if it had been intercepted then it then it would have replaced
433  *      it with an image.)
434  *
435  *    Revision 1.12  2001/05/27 22:17:04  oes
436  *
437  *    - re_process_buffer no longer writes the modified buffer
438  *      to the client, which was very ugly. It now returns the
439  *      buffer, which it is then written by chat.
440  *
441  *    - content_length now adjusts the Content-Length: header
442  *      for modified documents rather than crunch()ing it.
443  *      (Length info in csp->content_length, which is 0 for
444  *      unmodified documents)
445  *
446  *    - For this to work, sed() is called twice when filtering.
447  *
448  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
449  *    Added support for CLF and fixed LOG_LEVEL_LOG.
450  *    Also did CRLF->LF fix of my previous patch.
451  *
452  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
453  *    ACL feature now provides more security by immediately dropping
454  *    connections from untrusted hosts.
455  *
456  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
457  *    Automatic reloading of config file.
458  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
459  *    Most of the global variables have been moved to a new
460  *    struct configuration_spec, accessed through csp->config->globalname
461  *    Most of the globals remaining are used by the Win32 GUI.
462  *
463  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
464  *    Fixing minor memory leak and buffer overflow.
465  *
466  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
467  *    Hard tabs->Spaces
468  *
469  *    Revision 1.6  2001/05/23 00:13:58  joergs
470  *    AmigaOS support fixed.
471  *
472  *    Revision 1.5  2001/05/22 18:46:04  oes
473  *
474  *    - Enabled filtering banners by size rather than URL
475  *      by adding patterns that replace all standard banner
476  *      sizes with the "Junkbuster" gif to the re_filterfile
477  *
478  *    - Enabled filtering WebBugs by providing a pattern
479  *      which kills all 1x1 images
480  *
481  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
482  *      which is selected by the (nonstandard and therefore
483  *      capital) letter 'U' in the option string.
484  *      It causes the quantifiers to be ungreedy by default.
485  *      Appending a ? turns back to greedy (!).
486  *
487  *    - Added a new interceptor ijb-send-banner, which
488  *      sends back the "Junkbuster" gif. Without imagelist or
489  *      MSIE detection support, or if tinygif = 1, or the
490  *      URL isn't recognized as an imageurl, a lame HTML
491  *      explanation is sent instead.
492  *
493  *    - Added new feature, which permits blocking remote
494  *      script redirects and firing back a local redirect
495  *      to the browser.
496  *      The feature is conditionally compiled, i.e. it
497  *      can be disabled with --disable-fast-redirects,
498  *      plus it must be activated by a "fast-redirects"
499  *      line in the config file, has its own log level
500  *      and of course wants to be displayed by show-proxy-args
501  *      Note: Boy, all the #ifdefs in 1001 locations and
502  *      all the fumbling with configure.in and acconfig.h
503  *      were *way* more work than the feature itself :-(
504  *
505  *    - Because a generic redirect template was needed for
506  *      this, tinygif = 3 now uses the same.
507  *
508  *    - Moved GIFs, and other static HTTP response templates
509  *      to project.h
510  *
511  *    - Some minor fixes
512  *
513  *    - Removed some >400 CRs again (Jon, you really worked
514  *      a lot! ;-)
515  *
516  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
517  *    Made failure to bind() a fatal error.
518  *
519  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
520  *    Version 2.9.4 checkin.
521  *    - Merged popupfile and cookiefile, and added control over PCRS
522  *      filtering, in new "permissionsfile".
523  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
524  *      file error you now get a message box (in the Win32 GUI) rather
525  *      than the program exiting with no explanation.
526  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
527  *      skipping.
528  *    - Removed tabs from "config"
529  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
530  *    - Bumped up version number.
531  *
532  *    Revision 1.2  2001/05/17 22:34:44  oes
533  *     - Added hint on GIF char array generation to jcc.c
534  *     - Cleaned CRLF's from the sources and related files
535  *     - Repaired logging for REF and FRC
536  *
537  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
538  *    Initial import of version 2.9.3 source tree
539  *
540  *
541  *********************************************************************/
542 \f
543
544 #include "config.h"
545
546 #include <stdio.h>
547 #include <sys/types.h>
548 #include <stdlib.h>
549 #include <string.h>
550 #include <signal.h>
551 #include <fcntl.h>
552 #include <errno.h>
553
554 #ifdef FEATURE_PTHREAD
555 #include <pthread.h>
556 #endif /* def FEATURE_PTHREAD */
557
558 #ifdef _WIN32
559 # ifndef FEATURE_PTHREAD
560 #  ifndef STRICT
561 #   define STRICT
562 #  endif
563 #  include <windows.h>
564 #  include <process.h>
565 # endif /* ndef FEATURE_PTHREAD */
566
567 # include "win32.h"
568 # ifndef _WIN_CONSOLE
569 #  include "w32log.h"
570 # endif /* ndef _WIN_CONSOLE */
571
572 #else /* ifndef _WIN32 */
573
574 # if !defined (__OS2__)
575 # include <unistd.h>
576 # include <sys/wait.h>
577 # endif /* ndef __OS2__ */
578 # include <sys/time.h>
579 # include <sys/stat.h>
580 # include <sys/ioctl.h>
581
582 #ifdef sun
583 #include <sys/termios.h>
584 #endif /* sun */
585
586 #ifdef unix
587 #include <pwd.h>
588 #include <grp.h>
589 #endif
590
591 # include <signal.h>
592
593 # ifdef __BEOS__
594 #  include <socket.h>  /* BeOS has select() for sockets only. */
595 #  include <OS.h>      /* declarations for threads and stuff. */
596 # endif
597
598 # if defined(__EMX__) || defined(__OS2__)
599 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
600 # endif
601 # ifdef __OS2__
602 #define INCL_DOS
603 # include <os2.h>
604 #define bzero(B,N) memset(B,0x00,n)
605 # endif
606
607 # ifndef FD_ZERO
608 #  include <select.h>
609 # endif
610
611 #endif
612
613 #include "project.h"
614 #include "list.h"
615 #include "jcc.h"
616 #include "filters.h"
617 #include "loaders.h"
618 #include "parsers.h"
619 #include "killpopup.h"
620 #include "miscutil.h"
621 #include "errlog.h"
622 #include "jbsockets.h"
623 #include "gateway.h"
624 #include "actions.h"
625 #include "cgi.h"
626 #include "loadcfg.h"
627 #include "urlmatch.h"
628 #ifdef FEATURE_ACTIVITY_CONSOLE
629 #include "stats.h"
630 #endif /* def FEATURE_ACTIVITY_CONSOLE */
631
632 const char jcc_h_rcs[] = JCC_H_VERSION;
633 const char project_h_rcs[] = PROJECT_H_VERSION;
634
635 int no_daemon = 0;
636 struct client_state  clients[1];
637 struct file_list     files[1];
638
639 #ifdef FEATURE_STATISTICS
640 int urls_read     = 0;     /* total nr of urls read inc rejected */
641 int urls_rejected = 0;     /* total nr of urls rejected */
642 #endif /* def FEATURE_STATISTICS */
643
644 #ifdef FEATURE_GRACEFUL_TERMINATION
645 int g_terminate = 0;
646 #endif
647
648 static void listen_loop(void);
649 static void chat(struct client_state *csp);
650 static jb_err relay_server_traffic( struct client_state *csp ) ;
651 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
652 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
653 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
654 static jb_err open_forwarding_connection( struct client_state *csp );
655 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http,  char* hdr );
656 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
657
658
659 #ifdef AMIGA
660 void serve(struct client_state *csp);
661 #else /* ifndef AMIGA */
662 static void serve(struct client_state *csp);
663 #endif /* def AMIGA */
664
665 #ifdef __BEOS__
666 static int32 server_thread(void *data);
667 #endif /* def __BEOS__ */
668
669 #ifdef _WIN32
670 #define sleep(N)  Sleep(((N) * 1000))
671 #endif
672
673 #ifdef __OS2__
674 #define sleep(N)  DosSleep(((N) * 100))
675 #endif
676
677 #if defined(unix) || defined(__EMX__)
678 const char *basedir;
679 const char *pidfile = NULL;
680 int received_hup_signal = 0;
681 #endif /* defined unix */
682
683 /* The vanilla wafer. */
684 static const char VANILLA_WAFER[] =
685    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
686    "Do_not_send_me_any_copyrighted_information_other_than_the_"
687    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
688    "In_particular_do_not_send_me_any_cookies_that_"
689    "are_subject_to_a_claim_of_copyright_by_anybody._"
690    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
691    "(copyright_or_otherwise)_applying_to_any_cookie._";
692
693 /**
694  * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
695  */
696 static const char CSUCCEED[] =
697    "HTTP/1.0 200 Connection established\n"
698    "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
699
700
701 /**
702  * HTTP reply sent when the browser sends something unintelligible.
703  */
704 static const char CHEADER[] =
705    "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
706
707
708 /**
709  * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
710  * other than a HTTPS port (as defined by +limit-connect).
711  */
712 static const char CFORBIDDEN[] =
713    "HTTP/1.0 403 Connection not allowable\r\nX-Hint: If you read this message interactively, then you know why this happens ,-)\r\n\r\n";
714
715 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
716 /*********************************************************************
717  *
718  * Function    :  sig_handler 
719  *
720  * Description :  Signal handler for different signals.
721  *                Exit gracefully on ABRT, TERM and  INT
722  *                or set a flag that will cause the errlog
723  *                to be reopened by the main thread on HUP.
724  *
725  * Parameters  :
726  *          1  :  the_signal = the signal cause this function to call
727  *
728  * Returns     :  - 
729  *
730  *********************************************************************/
731 static void sig_handler(int the_signal)
732 {
733    switch(the_signal)
734    {
735       case SIGABRT:
736       case SIGTERM:
737       case SIGINT:
738          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
739 #if defined(unix)
740          unlink(pidfile);
741 #endif /* unix */
742          exit(the_signal);
743          break;
744
745       case SIGHUP:
746          received_hup_signal = 1;
747          break;         
748
749       default:
750          /* 
751           * We shouldn't be here, unless we catch signals
752           * in main() that we can't handle here!
753           */
754          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
755    }
756    return;
757
758 }
759 #endif
760
761
762 /*********************************************************************
763  *
764  * Function    :  chat
765  *
766  * Description :  Once a connection to the client has been accepted,
767  *                this function is called (via serve()) to handle the
768  *                main business of the communication.  When this
769  *                function returns, the caller must close the client
770  *                socket handle.
771  *
772  * Parameters  :
773  *          1  :  csp = Current client state (buffers, headers, etc...)
774  *
775  * Returns     :  void
776  *
777  *********************************************************************/
778 static void chat(struct client_state *csp)
779 {
780
781
782    char buf[BUFFER_SIZE];
783    int len; /* for buffer sizes */
784    char *hdr; 
785    fd_set rfds;
786    int n;
787    jb_socket maxfd;
788    int byte_count = 0;
789    struct http_request *http;
790
791    http = csp->http;
792
793    if (read_client_headers(csp, http ) != JB_ERR_OK )
794       return;
795    
796
797    /* Process the client headers */
798    if (process_client_headers(csp, http) != JB_ERR_OK)
799       return;
800    
801
802    /* Check if this connection request is permitted */
803    if (is_connect_request_allowed(csp) != JB_ERR_OK)
804       return ;
805
806    /*
807     * We have a valid and legit request. Now, check to see if we need to
808     * intercept it.
809     */
810    if (intercept_page(csp, http) != JB_ERR_OK)
811       return;
812   
813    /* 
814     * The page passed the intercept routine, so open a forwarding
815     * connection for conversation
816     */
817    if (open_forwarding_connection(csp) != JB_ERR_OK )
818       return ;
819
820
821
822    hdr = sed(client_patterns, add_client_headers, csp);
823    if (hdr == NULL)
824    {
825       /* FIXME Should handle error properly */
826       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
827    }
828
829    /* FIXME - where should this go, logically ? */
830    list_remove_all(csp->headers);
831
832
833    if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
834       return ;
835
836
837    /* we're finished with the client's header */
838    freez(hdr);
839
840    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
841
842    /* pass data between the client and server
843     * until one or the other shuts down the connection.
844     */
845
846    /* Set the flag for reading headers to False */
847    /* This is used in relay_server_traffic */
848    csp->all_headers_read = 0 ;
849
850    for (;;)
851    {
852       jb_err tmp_ret_val = JB_ERR_GENERIC ;
853
854 #ifdef __OS2__
855       /*
856        * FD_ZERO here seems to point to an errant macro which crashes.
857        * So do this by hand for now...
858        */
859       memset(&rfds,0x00,sizeof(fd_set));
860 #else
861       FD_ZERO(&rfds);
862 #endif
863       FD_SET(csp->cfd, &rfds);
864       FD_SET(csp->sfd, &rfds);
865
866       n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
867
868       if (n < 0)
869       {
870          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
871          return;
872       }
873
874       /*
875        * This is the body of the browser's request.
876        * Just read it and write it.
877        */
878
879       if (FD_ISSET(csp->cfd, &rfds))
880       {
881          len = read_socket(csp->cfd, buf, sizeof(buf));
882
883          if (len <= 0)
884          {
885             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
886              csp->ip_addr_str, http->ocmd, byte_count);
887             return ;
888          }
889
890          if (write_socket(csp->sfd, buf, (size_t)len))
891          {
892             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
893             return;
894          }
895          continue;
896       }
897
898       /*
899        * Check if the server wants to talk, and if so, converse.
900        */
901
902       if (FD_ISSET(csp->sfd, &rfds))
903          tmp_ret_val = relay_server_traffic(csp) ;
904
905
906       if (tmp_ret_val == JB_ERR_OK)
907          continue ;
908       else
909          return; 
910    }
911    /* We should never get here! */
912    log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
913 } /* END chat() */
914
915
916 /*********************************************************************
917  *
918  * Function    :  serve
919  *
920  * Description :  This is little more than chat.  We only "serve" to
921  *                to close any socket that chat may have opened.
922  *
923  * Parameters  :
924  *          1  :  csp = Current client state (buffers, headers, etc...)
925  *
926  * Returns     :  N/A
927  *
928  *********************************************************************/
929 #ifdef AMIGA
930 void serve(struct client_state *csp)
931 #else /* ifndef AMIGA */
932 static void serve(struct client_state *csp)
933 #endif /* def AMIGA */
934 {
935    chat(csp);
936    close_socket(csp->cfd);
937
938    if (csp->sfd != JB_INVALID_SOCKET)
939    {
940       close_socket(csp->sfd);
941    }
942
943    csp->flags &= ~CSP_FLAG_ACTIVE;
944
945 }
946
947
948 #ifdef __BEOS__
949 /*********************************************************************
950  *
951  * Function    :  server_thread
952  *
953  * Description :  We only exist to call `serve' in a threaded environment.
954  *
955  * Parameters  :
956  *          1  :  data = Current client state (buffers, headers, etc...)
957  *
958  * Returns     :  Always 0.
959  *
960  *********************************************************************/
961 static int32 server_thread(void *data)
962 {
963    serve((struct client_state *) data);
964    return 0;
965
966 }
967 #endif
968
969
970 /*********************************************************************
971  *
972  * Function    :  usage
973  *
974  * Description :  Print usage info & exit.
975  *
976  * Parameters  :  Pointer to argv[0] for identifying ourselves
977  *
978  * Returns     :  No. ,-)
979  *
980  *********************************************************************/
981 void usage(const char *myname)
982 {
983    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
984            "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
985            "Aborting.\n", myname);
986  
987    exit(2);
988
989 }
990
991
992 /*********************************************************************
993  *
994  * Function    :  main
995  *
996  * Description :  Load the config file and start the listen loop.
997  *                This function is a lot more *sane* with the `load_config'
998  *                and `listen_loop' functions; although it stills does
999  *                a *little* too much for my taste.
1000  *
1001  * Parameters  :
1002  *          1  :  argc = Number of parameters (including $0).
1003  *          2  :  argv = Array of (char *)'s to the parameters.
1004  *
1005  * Returns     :  1 if : can't open config file, unrecognized directive,
1006  *                stats requested in multi-thread mode, can't open the
1007  *                log file, can't open the jar file, listen port is invalid,
1008  *                any load fails, and can't bind port.
1009  *
1010  *                Else main never returns, the process must be signaled
1011  *                to terminate execution.  Or, on Windows, use the
1012  *                "File", "Exit" menu option.
1013  *
1014  *********************************************************************/
1015 #ifdef __MINGW32__
1016 int real_main(int argc, const char *argv[])
1017 #else
1018 int main(int argc, const char *argv[])
1019 #endif
1020 {
1021    int argc_pos = 0;
1022 #ifdef unix
1023    struct passwd *pw = NULL;
1024    struct group *grp = NULL;
1025    char *p;
1026 #endif
1027
1028    Argc = argc;
1029    Argv = argv;
1030
1031    configfile =
1032 #if !defined(_WIN32)
1033    "config"
1034 #else
1035    "config.txt"
1036 #endif
1037       ;
1038
1039    /*
1040     * Parse the command line arguments
1041     */
1042    while (++argc_pos < argc)
1043    {
1044 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1045
1046       if (strcmp(argv[argc_pos], "--help") == 0)
1047       {
1048          usage(argv[0]);
1049       }
1050
1051       else if(strcmp(argv[argc_pos], "--version") == 0)
1052       {
1053          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1054          exit(0);
1055       }
1056
1057       else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1058       {
1059          no_daemon = 1;
1060       }
1061 #if defined(unix)
1062       else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1063       {
1064          if (++argc_pos == argc) usage(argv[0]);
1065          pidfile = strdup(argv[argc_pos]);
1066       }
1067
1068       else if (strcmp(argv[argc_pos], "--user" ) == 0)
1069       {
1070          if (++argc_pos == argc) usage(argv[argc_pos]);
1071
1072          if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1073          {
1074             *p++ = '\0';
1075             if (NULL == (grp = getgrnam(p)))
1076             {
1077                log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1078             }
1079          }
1080
1081          if (NULL == (pw = getpwnam(argv[argc_pos])))
1082          {
1083             log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1084          }
1085
1086          if (p != NULL) *--p = '\0';
1087       }
1088 #endif /* defined(unix) */
1089       else
1090 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1091       {
1092          configfile = argv[argc_pos];
1093       }
1094
1095    } /* -END- while (more arguments) */
1096
1097 #if defined(unix)
1098    if ( *configfile != '/' )
1099    {
1100       char *abs_file;
1101
1102       /* make config-filename absolute here */
1103       if ( !(basedir = getcwd( NULL, 1024 )))
1104       {
1105          perror("get working dir failed");
1106          exit( 1 );
1107       }
1108
1109       if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1110       {
1111          perror("malloc failed");
1112          exit( 1 );
1113       }
1114       strcpy( abs_file, basedir );
1115       strcat( abs_file, "/" );
1116       strcat( abs_file, configfile );
1117       configfile = abs_file;
1118    }
1119 #endif /* defined unix */
1120
1121
1122    files->next = NULL;
1123
1124 #ifdef AMIGA
1125    InitAmiga();
1126 #elif defined(_WIN32)
1127    InitWin32();
1128 #endif
1129
1130    /*
1131     * Unix signal handling
1132     *
1133     * Catch the abort, interrupt and terminate signals for a graceful exit
1134     * Catch the hangup signal so the errlog can be reopened.
1135     * Ignore the broken pipe and child signals
1136     *  FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE? 
1137     */
1138 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1139 {
1140    int idx;
1141    const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1142    const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1143
1144    for (idx = 0; catched_signals[idx] != 0; idx++)
1145    {
1146       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1147       {
1148          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1149       }
1150    }
1151
1152    for (idx = 0; ignored_signals[idx] != 0; idx++)
1153    {
1154       if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1155       {
1156          log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1157       }
1158    }
1159
1160 }
1161 #else /* ifdef _WIN32 */
1162 # ifdef _WIN_CONSOLE
1163    /*
1164     * We *are* in a windows console app.
1165     * Print a verbose messages about FAQ's and such
1166     */
1167    printf(win32_blurb);
1168 # endif /* def _WIN_CONSOLE */
1169 #endif /* def _WIN32 */
1170
1171
1172    /* Initialize the CGI subsystem */
1173    cgi_init_error_messages();
1174
1175    /*
1176     * If runnig on unix and without the --nodaemon
1177     * option, become a daemon. I.e. fork, detach
1178     * from tty and get process group leadership
1179     */
1180 #if defined(unix)
1181    {
1182       pid_t pid = 0;
1183 #if 0
1184       int   fd;
1185 #endif
1186
1187       if (!no_daemon)
1188       {
1189          pid  = fork();
1190
1191          if ( pid < 0 ) /* error */
1192          {
1193             perror("fork");
1194             exit( 3 );
1195          }
1196          else if ( pid != 0 ) /* parent */
1197          {
1198             int status;
1199             pid_t wpid;
1200             /*
1201              * must check for errors
1202              * child died due to missing files aso
1203              */
1204             sleep( 1 );
1205             wpid = waitpid( pid, &status, WNOHANG );
1206             if ( wpid != 0 )
1207             {
1208                exit( 1 );
1209             }
1210             exit( 0 );
1211          }
1212          /* child */
1213 #if 1
1214          /* Should be more portable, but not as well tested */
1215          setsid();
1216 #else /* !1 */
1217 #ifdef __FreeBSD__
1218          setpgrp(0,0);
1219 #else /* ndef __FreeBSD__ */
1220          setpgrp();
1221 #endif /* ndef __FreeBSD__ */
1222          fd = open("/dev/tty", O_RDONLY);
1223          if ( fd )
1224          {
1225             /* no error check here */
1226             ioctl( fd, TIOCNOTTY,0 );
1227             close ( fd );
1228          }
1229 #endif /* 1 */
1230          /* FIXME: should close stderr (fd 2) here too, but the test
1231           * for existence
1232           * and load config file is done in listen_loop() and puts
1233           * some messages on stderr there.
1234           */
1235
1236          close( 0 );
1237          close( 1 );
1238          chdir("/");
1239
1240       } /* -END- if (!no_daemon) */
1241
1242       /*
1243        * As soon as we have written the PID file, we can switch
1244        * to the user and group ID indicated by the --user option
1245        */
1246       write_pid_file();
1247    
1248       if (NULL != pw)
1249       {
1250          if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1251          {
1252             log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1253          }
1254          if (setuid(pw->pw_uid))
1255          {
1256             log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1257          }
1258       }
1259    }
1260 #endif /* defined unix */
1261
1262    listen_loop();
1263
1264    /* NOTREACHED */
1265    return(-1);
1266
1267 }
1268
1269
1270 /*********************************************************************
1271  *
1272  * Function    :  bind_port_helper
1273  *
1274  * Description :  Bind the listen port.  Handles logging, and aborts
1275  *                on failure.
1276  *
1277  * Parameters  :
1278  *          1  :  config = Privoxy configuration.  Specifies port
1279  *                         to bind to.
1280  *
1281  * Returns     :  Port that was opened.
1282  *
1283  *********************************************************************/
1284 static jb_socket bind_port_helper(struct configuration_spec * config)
1285 {
1286    int result;
1287    jb_socket bfd;
1288
1289    if ( (config->haddr != NULL)
1290      && (config->haddr[0] == '1')
1291      && (config->haddr[1] == '2')
1292      && (config->haddr[2] == '7')
1293      && (config->haddr[3] == '.') )
1294    {
1295       log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1296                 config->hport);
1297    }
1298    else if (config->haddr == NULL)
1299    {
1300       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1301                 config->hport);
1302    }
1303    else
1304    {
1305       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1306                 config->hport, config->haddr);
1307    }
1308
1309    result = bind_port(config->haddr, config->hport, &bfd);
1310
1311    if (result < 0)
1312    {
1313       switch(result)
1314       {
1315          case -3 :
1316             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1317                "There may be another Privoxy or some other "
1318                "proxy running on port %d",
1319                (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1320                       config->hport, config->hport);
1321
1322          case -2 :
1323             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: " 
1324                "The hostname is not resolvable",
1325                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1326
1327          default :
1328             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1329                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1330       }
1331
1332       /* shouldn't get here */
1333       return JB_INVALID_SOCKET;
1334    }
1335
1336    config->need_bind = 0;
1337
1338    return bfd;
1339 }
1340
1341
1342 /*********************************************************************
1343  *
1344  * Function    :  listen_loop
1345  *
1346  * Description :  bind the listen port and enter a "FOREVER" listening loop.
1347  *
1348  * Parameters  :  N/A
1349  *
1350  * Returns     :  Never.
1351  *
1352  *********************************************************************/
1353 static void listen_loop(void)
1354 {
1355    struct client_state *csp = NULL;
1356    jb_socket bfd;
1357    struct configuration_spec * config;
1358
1359    config = load_config();
1360
1361    bfd = bind_port_helper(config);
1362
1363 #ifdef FEATURE_ACTIVITY_CONSOLE
1364    init_stats_config(config);
1365 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1366
1367 #ifdef FEATURE_GRACEFUL_TERMINATION
1368    while (!g_terminate)
1369 #else
1370    for (;;)
1371 #endif
1372    {
1373 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1374       while (waitpid(-1, NULL, WNOHANG) > 0)
1375       {
1376          /* zombie children */
1377       }
1378 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1379
1380       /*
1381        * Free data that was used by died threads
1382        */
1383       sweep();
1384
1385 #if defined(unix)
1386       /*
1387        * Re-open the errlog after HUP signal
1388        */
1389       if (received_hup_signal)
1390       {
1391          init_error_log(Argv[0], config->logfile, config->debug);
1392          received_hup_signal = 0;
1393       }
1394 #endif
1395
1396 #ifdef __OS2__
1397 #ifdef FEATURE_COOKIE_JAR
1398       /*
1399        * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1400        * already open.  I think unload_configfile() is not being run, which should do
1401        * this work.  Until that can get resolved, we'll use this workaround.
1402        *
1403        * [Note from Jon: We don't unload_configfile() until all existing threads have
1404        * exited - they're likely to hang aroung transferring data to the browser.]
1405        */
1406        if (csp)
1407          if(csp->config)
1408            if (csp->config->jar)
1409            {
1410              fclose(csp->config->jar);
1411              csp->config->jar = NULL;
1412            }
1413 #endif /* FEATURE_COOKIE_JAR */
1414 #endif /* __OS2__ */
1415
1416       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1417       {
1418          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1419          continue;
1420       }
1421
1422       csp->flags |= CSP_FLAG_ACTIVE;
1423       csp->sfd    = JB_INVALID_SOCKET;
1424
1425       csp->config = config = load_config();
1426
1427       if ( config->need_bind )
1428       {
1429          /*
1430           * Since we were listening to the "old port", we will not see
1431           * a "listen" param change until the next IJB request.  So, at
1432           * least 1 more request must be made for us to find the new
1433           * setting.  I am simply closing the old socket and binding the
1434           * new one.
1435           *
1436           * Which-ever is correct, we will serve 1 more page via the
1437           * old settings.  This should probably be a "show-proxy-args"
1438           * request.  This should not be a so common of an operation
1439           * that this will hurt people's feelings.
1440           */
1441
1442          close_socket(bfd);
1443
1444          bfd = bind_port_helper(config);
1445       }
1446
1447       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1448
1449       if (!accept_connection(csp, bfd))
1450       {
1451          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1452
1453 #ifdef AMIGA
1454          if(!childs)
1455          {
1456             exit(1);
1457          }
1458 #endif
1459          freez(csp);
1460          continue;
1461       }
1462       else
1463       {
1464          log_error(LOG_LEVEL_CONNECT, "OK");
1465       }
1466
1467 #ifdef FEATURE_TOGGLE
1468       if (g_bToggleIJB)
1469       {
1470          csp->flags |= CSP_FLAG_TOGGLED_ON;
1471       }
1472 #endif /* def FEATURE_TOGGLE */
1473
1474 #ifdef FEATURE_ACTIVITY_CONSOLE
1475       update_stats_config(config);
1476 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1477
1478       if (run_loader(csp))
1479       {
1480          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1481          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1482       }
1483
1484 #ifdef FEATURE_ACL
1485       if (block_acl(NULL,csp))
1486       {
1487 #ifdef FEATURE_ACTIVITY_CONSOLE
1488          accumulate_stats(STATS_ACL_RESTRICT,1);
1489 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1490          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1491          close_socket(csp->cfd);
1492          freez(csp);
1493          continue;
1494       }
1495 #endif /* def FEATURE_ACL */
1496
1497       /* add it to the list of clients */
1498       csp->next = clients->next;
1499       clients->next = csp;
1500
1501       if (config->multi_threaded)
1502       {
1503          int child_id;
1504
1505 /* this is a switch () statment in the C preprocessor - ugh */
1506 #undef SELECTED_ONE_OPTION
1507
1508 /* Use Pthreads in preference to native code */
1509 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1510 #define SELECTED_ONE_OPTION
1511          {
1512             pthread_t the_thread;
1513             pthread_attr_t attrs;
1514
1515             pthread_attr_init(&attrs);
1516             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1517             child_id = (pthread_create(&the_thread, &attrs,
1518                (void*)serve, csp) ? -1 : 0);
1519             pthread_attr_destroy(&attrs);
1520          }
1521 #endif
1522
1523 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1524 #define SELECTED_ONE_OPTION
1525          child_id = _beginthread(
1526             (void (*)(void *))serve,
1527             64 * 1024,
1528             csp);
1529 #endif
1530
1531 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1532 #define SELECTED_ONE_OPTION
1533          child_id = _beginthread(
1534             (void(* _Optlink)(void*))serve,
1535             NULL,
1536             64 * 1024,
1537             csp);
1538 #endif
1539
1540 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1541 #define SELECTED_ONE_OPTION
1542          {
1543             thread_id tid = spawn_thread
1544                (server_thread, "server", B_NORMAL_PRIORITY, csp);
1545
1546             if ((tid >= 0) && (resume_thread(tid) == B_OK))
1547             {
1548                child_id = (int) tid;
1549             }
1550             else
1551             {
1552                child_id = -1;
1553             }
1554          }
1555 #endif
1556
1557 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1558 #define SELECTED_ONE_OPTION
1559          csp->cfd = ReleaseSocket(csp->cfd, -1);
1560          if((child_id = (int)CreateNewProcTags(
1561             NP_Entry, (ULONG)server_thread,
1562             NP_Output, Output(),
1563             NP_CloseOutput, FALSE,
1564             NP_Name, (ULONG)"privoxy child",
1565             NP_StackSize, 200*1024,
1566             TAG_DONE)))
1567          {
1568             childs++;
1569             ((struct Task *)child_id)->tc_UserData = csp;
1570             Signal((struct Task *)child_id, SIGF_SINGLE);
1571             Wait(SIGF_SINGLE);
1572          }
1573 #endif
1574
1575 #if !defined(SELECTED_ONE_OPTION)
1576          child_id = fork();
1577
1578          /* This block is only needed when using fork().
1579           * When using threads, the server thread was
1580           * created and run by the call to _beginthread().
1581           */
1582          if (child_id == 0)   /* child */
1583          {
1584             serve(csp);
1585             _exit(0);
1586
1587          }
1588          else if (child_id > 0) /* parent */
1589          {
1590             /* in a fork()'d environment, the parent's
1591              * copy of the client socket and the CSP
1592              * are not used.
1593              */
1594
1595 #if !defined(_WIN32) && defined(__CYGWIN__)
1596             wait( NULL );
1597 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1598             close_socket(csp->cfd);
1599             csp->flags &= ~CSP_FLAG_ACTIVE;
1600          }
1601 #endif
1602
1603 #undef SELECTED_ONE_OPTION
1604 /* end of cpp switch () */
1605
1606          if (child_id < 0) /* failed */
1607          {
1608             char buf[BUFFER_SIZE];
1609
1610             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1611
1612             sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1613
1614             write_socket(csp->cfd, buf, strlen(buf));
1615             close_socket(csp->cfd);
1616             csp->flags &= ~CSP_FLAG_ACTIVE;
1617             sleep(5);
1618             continue;
1619          }
1620       }
1621       else
1622       {
1623          serve(csp);
1624       }
1625    }
1626
1627    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1628
1629    /* Clean up.  Aim: free all memory (no leaks) */
1630 #ifdef FEATURE_GRACEFUL_TERMINATION
1631
1632    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1633
1634    unload_current_config_file();
1635    unload_current_actions_file();
1636    unload_current_re_filterfile();
1637 #ifdef FEATURE_TRUST
1638    unload_current_trust_file();
1639 #endif
1640
1641    if (config->multi_threaded)
1642    {
1643       int i = 60;
1644       do
1645       {
1646          sleep(1);
1647          sweep();
1648       } while ((clients->next != NULL) && (--i > 0));
1649
1650       if (i <= 0)
1651       {
1652          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1653       }
1654    }
1655    sweep();
1656    sweep();
1657
1658 #if defined(unix)
1659    free(basedir);
1660 #endif
1661 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1662    /* Cleanup - remove taskbar icon etc. */
1663    TermLogWindow();
1664 #endif
1665
1666    exit(0);
1667 #endif /* FEATURE_GRACEFUL_TERMINATION */
1668
1669 }
1670
1671 /*********************************************************************
1672  *
1673  * Function    :  relay_server_traffic
1674  *
1675  * Description :  receive traffic from the server and relay it
1676  *                to the client, with some processing
1677  *
1678  * Parameters  :
1679  *          1  :  client_state structure
1680  *                         
1681  *
1682  * Returns     :  JB_ERR_OK if there may be more work
1683  *             :  other values for errors
1684  *
1685  **********************************************************************/
1686
1687 static jb_err relay_server_traffic( struct client_state *csp )
1688 {
1689 #ifdef FEATURE_KILL_POPUPS
1690    int block_popups;         /* bool, 1==will block popups */
1691    int block_popups_now = 0; /* bool, 1==currently blocking popups */
1692 #endif /* def FEATURE_KILL_POPUPS */
1693    
1694    char buf[BUFFER_SIZE];
1695    int len; /* for buffer sizes */
1696    int ms_iis5_hack = 0;
1697    int byte_count = 0;
1698    char *hdr;
1699    char *p;
1700
1701    /* Skeleton for HTTP response, if we should intercept the request */
1702    struct http_response *rsp;
1703
1704    int pcrs_filter;        /* bool, 1==will filter through pcrs */
1705    int gif_deanimate;      /* bool, 1==will deanimate gifs */
1706
1707 #ifdef FEATURE_KILL_POPUPS
1708    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1709 #endif /* def FEATURE_KILL_POPUPS */
1710
1711    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
1712                                 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1713
1714    gif_deanimate              = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1715
1716
1717    fflush (0);
1718    len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1719
1720    if (len < 0)
1721    {
1722       log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1723
1724       log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1725          csp->ip_addr_str, csp->http->ocmd);
1726
1727       rsp = error_response (csp, "connect-failed", errno);
1728
1729       if (rsp)
1730       {
1731          if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1732             || write_socket (csp->cfd, rsp->body, rsp->content_length))
1733          {
1734             log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1735                        csp->http->host);
1736          }
1737       }
1738
1739       free_http_response (rsp);
1740       return JB_ERR_GENERIC;
1741    }
1742
1743    /* Add a trailing zero.  This lets filter_popups
1744     * use string operations.
1745     */
1746    buf[len] = '\0';
1747
1748 #ifdef FEATURE_KILL_POPUPS
1749    /* Filter the popups on this read. */
1750    if (block_popups_now)
1751    {
1752       filter_popups (buf, csp);
1753    }
1754 #endif /* def FEATURE_KILL_POPUPS */
1755
1756
1757    /* Normally, this would indicate that we've read
1758     * as much as the server has sent us and we can
1759     * close the client connection.  However, Microsoft
1760     * in its wisdom has released IIS/5 with a bug that
1761     * prevents it from sending the trailing \r\n in
1762     * a 302 redirect header (and possibly other headers).
1763     * To work around this if we've haven't parsed
1764     * a full header we'll append a trailing \r\n
1765     * and see if this now generates a valid one.
1766     *
1767     * This hack shouldn't have any impacts.  If we've
1768     * already transmitted the header or if this is a
1769     * SSL connection, then we won't bother with this
1770     * hack.  So we only work on partially received
1771     * headers.  If we append a \r\n and this still
1772     * doesn't generate a valid header, then we won't
1773     * transmit anything to the client.
1774     */
1775    if (len == 0)
1776    {
1777
1778       if (csp->all_headers_read || csp->http->ssl)
1779       {
1780          /*
1781           * If we have been buffering up the document,
1782           * now is the time to apply content modification
1783           * and send the result to the client.
1784           */
1785          if (csp->content_filter)
1786          {
1787             /*
1788              * If the content filter fails, use the original
1789              * buffer and length.
1790              * (see p != NULL ? p : csp->iob->cur below)
1791              */
1792             if (NULL == (p = (*csp->content_filter) (csp)))
1793             {
1794                csp->content_length = csp->iob->eod - csp->iob->cur;
1795             }
1796
1797             hdr = sed (server_patterns, add_server_headers, csp);
1798             if (hdr == NULL)
1799             {
1800                /* FIXME Should handle error properly */
1801                log_error (LOG_LEVEL_FATAL,
1802                   "Out of memory parsing server header");
1803
1804             }
1805
1806             if (write_socket (csp->cfd, hdr, strlen (hdr))
1807                || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1808                           csp->content_length))
1809             {
1810                log_error (LOG_LEVEL_ERROR,
1811                   "write modified content to client failed: %E");
1812                return JB_ERR_GENERIC;
1813             }
1814
1815             freez (hdr);
1816             if (NULL != p)
1817             {
1818                freez (p);
1819             }
1820          }
1821          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1822             csp->ip_addr_str, csp->http->ocmd, byte_count);
1823          return JB_ERR_GENERIC;
1824       }
1825
1826       /*
1827        * This is NOT the body, so
1828        * Let's pretend the server just sent us a blank line.
1829        */
1830       len = sprintf (buf, "\r\n");
1831
1832       /*
1833        * Now, let the normal header parsing algorithm below do its
1834        * job.  If it fails, we'll exit instead of continuing.
1835        */
1836
1837       ms_iis5_hack = 1;
1838    }
1839
1840    /*
1841     * If this is an SSL connection or we're in the body
1842     * of the server document, just write it to the client,
1843     * unless we need to buffer the body for later content-filtering
1844     */
1845
1846    if (csp->all_headers_read || csp->http->ssl)
1847    {
1848       if (csp->content_filter)
1849       {
1850          add_to_iob (csp, buf, len);
1851
1852          /*
1853           * If the buffer limit will be reached on the next read,
1854           * switch to non-filtering mode, i.e. make & write the
1855           * header, flush the socket and get out of the way.
1856           */
1857          if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1858               (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1859          {
1860             size_t hdrlen;
1861
1862             log_error (LOG_LEVEL_ERROR,
1863                         "Buffer size limit reached! Flushing and stepping back.");
1864
1865             hdr = sed (server_patterns, add_server_headers, csp);
1866             if (hdr == NULL)
1867             {
1868                /* FIXME Should handle error properly */
1869                log_error (LOG_LEVEL_FATAL,
1870                   "Out of memory parsing server header");
1871             }
1872
1873             hdrlen = strlen (hdr);
1874             byte_count += hdrlen;
1875
1876             if (write_socket (csp->cfd, hdr, hdrlen)
1877                || ((len = flush_socket (csp->cfd, csp)) < 0))
1878             {
1879                log_error (LOG_LEVEL_CONNECT,
1880                   "write header to client failed: %E");
1881
1882                freez (hdr);
1883                return JB_ERR_GENERIC;
1884             }
1885
1886             freez (hdr);
1887             byte_count += len;
1888
1889             csp->content_filter = NULL;
1890             csp->all_headers_read = 1;
1891
1892          }
1893       }
1894       else
1895       {
1896          if (write_socket (csp->cfd, buf, (size_t) len))
1897          {
1898             log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1899             return JB_ERR_GENERIC;
1900          }
1901       }
1902       byte_count += len;
1903       return JB_ERR_OK ;
1904    }
1905    else
1906    {
1907       /*
1908        * we're still looking for the end of the
1909        * server's header ... (does that make header
1910        * parsing an "out of body experience" ?
1911        */
1912
1913       /* buffer up the data we just read */
1914       add_to_iob (csp, buf, len);
1915
1916       /* get header lines from the iob */
1917
1918       while ((p = get_header (csp)) != NULL)
1919       {
1920          if (*p == '\0')
1921          {
1922             /* see following note */
1923             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1924                csp->ip_addr_str, csp->http->ocmd, byte_count);
1925             return JB_ERR_GENERIC;
1926          }
1927          enlist (csp->headers, p);
1928          freez (p);
1929       }
1930
1931       /* NOTE: there are no "empty" headers so
1932        * if the pointer `p' is not NULL we must
1933        * assume that we reached the end of the
1934        * buffer before we hit the end of the header.
1935        */
1936
1937       if (p)
1938       {
1939          if (ms_iis5_hack)
1940          {
1941             /* Well, we tried our MS IIS/5
1942              * hack and it didn't work.
1943              * The header is incomplete
1944              * and there isn't anything
1945              * we can do about it.
1946              */
1947             log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1948                 csp->ip_addr_str, csp->http->ocmd, byte_count);
1949             return JB_ERR_GENERIC;
1950          }
1951          else
1952          {
1953             /* Since we have to wait for
1954              * more from the server before
1955              * we can parse the headers
1956              * we just continue here.
1957              */
1958             return JB_ERR_OK;
1959          }
1960       }      
1961       
1962       /* we have now received the entire header.
1963        * filter it and send the result to the client
1964        */
1965
1966       hdr = sed (server_patterns, add_server_headers, csp);
1967       if (hdr == NULL)
1968       {
1969          /* FIXME Should handle error properly */
1970          log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
1971       }
1972
1973   
1974
1975 #ifdef FEATURE_KILL_POPUPS
1976       /* Start blocking popups if appropriate. */
1977
1978       if ((csp->content_type & CT_TEXT) &&   /* It's a text / * MIME-Type */
1979           !csp->http->ssl &&                 /* We talk plaintext */
1980           block_popups)                      /* Policy allows */
1981       {
1982          block_popups_now = 1;
1983          /*
1984           * Filter the part of the body that came in the same read
1985           * as the last headers:
1986           */
1987          filter_popups (csp->iob->cur, csp);
1988       }
1989
1990 #endif /* def FEATURE_KILL_POPUPS */
1991
1992         /* Buffer and pcrs filter this if appropriate. */
1993
1994       if ((csp->content_type & CT_TEXT) &&       /* It's a text / * MIME-Type */
1995           !csp->http->ssl &&                     /* We talk plaintext */
1996           pcrs_filter)                           /* Policy allows */
1997       {
1998          csp->content_filter = pcrs_filter_response;
1999       }
2000
2001       /* Buffer and gif_deanimate this if appropriate. */
2002
2003       if ((csp->content_type & CT_GIF) &&        /* It's a image/gif MIME-Type */
2004           !csp->http->ssl &&                     /* We talk plaintext */
2005           gif_deanimate)                         /* Policy allows */
2006       {
2007          csp->content_filter = gif_deanimate_response;
2008       }
2009       /*
2010        * Only write if we're not buffering for content modification
2011        */
2012       if (!csp->content_filter)
2013       {
2014          /* write the server's (modified) header to
2015           * the client (along with anything else that
2016           * may be in the buffer)
2017           */
2018          if (write_socket (csp->cfd, hdr, strlen (hdr))
2019              || ((len = flush_socket (csp->cfd, csp)) < 0))
2020          {
2021             log_error (LOG_LEVEL_CONNECT,
2022                "write header to client failed: %E");
2023
2024             /* the write failed, so don't bother
2025              * mentioning it to the client...
2026              * it probably can't hear us anyway.
2027              */
2028             freez (hdr);
2029             return JB_ERR_GENERIC;
2030          }
2031
2032          byte_count += len;
2033       }
2034
2035       /* we're finished with the server's header */
2036
2037       freez (hdr);
2038       csp->all_headers_read = 1;
2039
2040       /* If this was a MS IIS/5 hack then it means
2041        * the server has already closed the
2042        * connection.  Nothing more to read.  Time
2043        * to bail.
2044        */
2045       if (ms_iis5_hack)
2046       {
2047          return JB_ERR_GENERIC ;
2048       }
2049    }
2050    return JB_ERR_OK ;
2051 } /* END relay_server_traffic() */
2052
2053
2054 /*********************************************************************
2055  *
2056  * Function    :  read_client_headers
2057  *
2058  * Description :  read all the client headers, and fill in the
2059  *                http* structure
2060  *
2061  * Parameters  :
2062  *          1  :  client_state structure
2063  *          2  :  http_request structure
2064  *                         
2065  *
2066  * Returns     :  JB_ERR_OK  - headers read and parsed ok
2067  *             :  other values - an error occurred.
2068  *********************************************************************/
2069
2070 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2071 {
2072
2073    char *p;
2074    char *req;
2075    char buf[BUFFER_SIZE];
2076    int len; /* for buffer sizes */
2077
2078    /*
2079     * Read the client's request.  Note that since we're not using select() we
2080     * could get blocked here if a client connected, then didn't say anything!
2081     *
2082     * This will read all the client headers.
2083     */
2084
2085    req = NULL ;
2086    for (;;)
2087    {
2088       len = read_socket(csp->cfd, buf, sizeof(buf));
2089
2090       if (len <= 0) break;      /* error! */
2091
2092       add_to_iob(csp, buf, len);
2093
2094       req = get_header(csp);
2095
2096       if (req == NULL)
2097       {
2098          break;    /* no HTTP request! */
2099       }
2100
2101       if (*req == '\0')
2102       {
2103          continue;   /* more to come! */
2104       }
2105
2106       /* When we get here we have read one header which is enough */
2107       /* to check whether the connection is allowed */
2108       break; 
2109    }
2110
2111
2112    for(;;) 
2113    {
2114
2115      if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2116       {
2117          len = read_socket(csp->cfd, buf, sizeof(buf));
2118          if (len <= 0)
2119          {
2120             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2121             return JB_ERR_GENERIC;
2122          }
2123          add_to_iob(csp, buf, len);
2124          continue;
2125       }
2126
2127       if (p == NULL) break;
2128
2129       enlist(csp->headers, p);
2130       freez(p);
2131
2132    }
2133
2134    parse_http_request(req, http, csp);
2135    freez(req);
2136
2137    if (http->cmd == NULL)
2138    {
2139       strcpy(buf, CHEADER);
2140       write_socket(csp->cfd, buf, strlen(buf));
2141
2142       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2143
2144       return JB_ERR_GENERIC;
2145    }
2146
2147    return JB_ERR_OK ;
2148
2149
2150 } /* END read_client_headers */
2151
2152
2153 /*********************************************************************
2154  *
2155  * Function    :  process_client_headers
2156  *
2157  * Description :  Process client headers
2158  * FIXME: Add description of what we do here!
2159  *
2160  * Parameters  :
2161  *          1  :  client_state structure
2162  *          2  :  http_request structure
2163  *                         
2164  *
2165  * Returns     :  JB_ERR_OK  - headers processed ok
2166  *             :  other values - an error occurred.
2167  *********************************************************************/
2168
2169 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2170 {
2171
2172
2173 #ifdef FEATURE_FORCE_LOAD
2174       /* If this request contains the FORCE_PREFIX,
2175        * better get rid of it now and set the force flag --oes
2176        * Changed to use the http structure rather than the req field --jaa
2177        * FIXME: This isn't enough -- there is the path and referrer etc! *
2178        */
2179
2180       if (strstr(http->url, FORCE_PREFIX))
2181       {
2182          strclean(http->url, FORCE_PREFIX);
2183          strclean(http->path, FORCE_PREFIX);
2184          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2185          csp->flags |= CSP_FLAG_FORCED;
2186       }
2187
2188 #endif /* def FEATURE_FORCE_LOAD */
2189
2190
2191    /* decide how to route the HTTP request */
2192
2193    if ((http->fwd = forward_url(http, csp)) == NULL)
2194    {
2195       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
2196       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2197    }
2198
2199    /* build the http request to send to the server
2200     * we have to do one of the following:
2201     *
2202     * create = use the original HTTP request to create a new
2203     *          HTTP request that has either the path component
2204     *          without the http://domainspec (w/path) or the
2205     *          full orininal URL (w/url)
2206     *          Note that the path and/or the HTTP version may
2207     *          have been altered by now.
2208     *
2209     * connect = Open a socket to the host:port of the server
2210     *           and short-circuit server and client socket.
2211     *
2212     * pass =  Pass the request unchanged if forwarding a CONNECT
2213     *         request to a parent proxy. Note that we'll be sending
2214     *         the CFAIL message ourselves if connecting to the parent
2215     *         fails, but we won't send a CSUCCEED message if it works,
2216     *         since that would result in a double message (ours and the
2217     *         parent's). After sending the request to the parent, we simply
2218     *         tunnel.
2219     *
2220     * here's the matrix:
2221     *                        SSL
2222     *                    0        1
2223     *                +--------+--------+
2224     *                |        |        |
2225     *             0  | create | connect|
2226     *                | w/path |        |
2227     *  Forwarding    +--------+--------+
2228     *                |        |        |
2229     *             1  | create | pass   |
2230     *                | w/url  |        |
2231     *                +--------+--------+
2232     *
2233     */
2234
2235    /*
2236     * Determine the actions for this URL
2237     */
2238 #ifdef FEATURE_TOGGLE
2239    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2240    {
2241       /* Most compatible set of actions (i.e. none) */
2242       init_current_action(csp->action);
2243    }
2244    else
2245 #endif /* ndef FEATURE_TOGGLE */
2246    {
2247       url_actions(http, csp);
2248    }
2249
2250
2251
2252
2253
2254    /*
2255     * Downgrade http version from 1.1 to 1.0 if +downgrade
2256     * action applies
2257     */
2258    if ( (http->ssl == 0)
2259      && (!strcmpic(http->ver, "HTTP/1.1"))
2260      && (csp->action->flags & ACTION_DOWNGRADE))
2261    {
2262       freez(http->ver);
2263       http->ver = strdup("HTTP/1.0");
2264
2265       if (http->ver == NULL)
2266       {
2267          log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2268       }
2269    }
2270
2271    /* 
2272     * Save a copy of the original request for logging
2273     */
2274    http->ocmd = strdup(http->cmd);
2275
2276    if (http->ocmd == NULL)
2277    {
2278       log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2279    }
2280
2281    /*
2282     * (Re)build the HTTP request for non-SSL requests.
2283     * If forwarding, use the whole URL, else, use only the path.
2284     */
2285    if (http->ssl == 0)
2286    {
2287       freez(http->cmd);
2288
2289       http->cmd = strdup(http->gpc);
2290       string_append(&http->cmd, " ");
2291
2292       if (http->fwd->forward_host)
2293       {
2294          string_append(&http->cmd, http->url);
2295       }
2296       else
2297       {
2298          string_append(&http->cmd, http->path);
2299       }
2300
2301       string_append(&http->cmd, " ");
2302       string_append(&http->cmd, http->ver);
2303
2304       if (http->cmd == NULL)
2305       {
2306          log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2307       }
2308    }
2309    enlist_first(csp->headers, http->cmd);
2310
2311
2312    /*
2313     * If the user has not supplied any wafers, and the user has not
2314     * told us to suppress the vanilla wafer, then send the vanilla wafer.
2315     */
2316    if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2317        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2318    {
2319       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2320    }
2321
2322    return JB_ERR_OK ;
2323 } /* process_client_headers */
2324
2325 /*********************************************************************
2326  *
2327  * Function    :  intercept_page
2328  *
2329  * Description :  Check whether to intercept page
2330  *
2331  * Parameters  :
2332  *          1  :  client_state structure
2333  *          2  :  http_request structure
2334  *                         
2335  *
2336  * Returns     :  JB_ERR_OK  - Do NOT intercept this page
2337  *             :  JB_ERR_INTERCEPT - intercept this page
2338  *             :  all other values - an error occurred.  
2339  *********************************************************************/
2340 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2341 {
2342
2343    /* Skeleton for HTTP response, if we should intercept the request */
2344    struct http_response *rsp;
2345
2346
2347 /*
2348  * These next lines are a little ugly, but they simplifies the if statements
2349  * below.  Basically if TOGGLE, then we want the if to test if the
2350  * CSP_FLAG_TOGGLED_ON flag ist set, else we don't.  And if FEATURE_FORCE_LOAD,
2351  * then we want the if to test for CSP_FLAG_FORCED , else we don't
2352  */
2353 #ifdef FEATURE_TOGGLE
2354 #   define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2355 #else /* ifndef FEATURE_TOGGLE */
2356 #   define IS_TOGGLED_ON_AND
2357 #endif /* ndef FEATURE_TOGGLE */
2358 #ifdef FEATURE_FORCE_LOAD
2359 #   define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2360 #else /* ifndef FEATURE_FORCE_LOAD */
2361 #   define IS_NOT_FORCED_AND
2362 #endif /* def FEATURE_FORCE_LOAD */
2363
2364 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2365
2366    if (
2367        /* a CGI call was detected and answered */
2368        (NULL != (rsp = dispatch_cgi(csp)))
2369
2370        /* or we are enabled and... */
2371        || (IS_ENABLED_AND (
2372
2373             /* ..the request was blocked */
2374           ( NULL != (rsp = block_url(csp)))
2375
2376           /* ..or untrusted */
2377 #ifdef FEATURE_TRUST
2378           || ( NULL != (rsp = trust_url(csp)))
2379 #endif /* def FEATURE_TRUST */
2380
2381           /* ..or a fast redirect kicked in */
2382 #ifdef FEATURE_FAST_REDIRECTS
2383           || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2384                 (NULL != (rsp = redirect_url(csp))))
2385 #endif /* def FEATURE_FAST_REDIRECTS */
2386           ))
2387       )
2388    {
2389       /* Write the answer to the client */
2390       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2391        || write_socket(csp->cfd, rsp->body, rsp->content_length))
2392       {
2393          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2394       }
2395
2396 #ifdef FEATURE_STATISTICS
2397       /* Count as a rejected request */
2398       csp->flags |= CSP_FLAG_REJECTED;
2399 #endif /* def FEATURE_STATISTICS */
2400
2401       /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2402       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2403       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2404
2405       /* Clean up and return */
2406       free_http_response(rsp);
2407       return JB_ERR_INTERCEPT;
2408    }
2409
2410    /* When we get here the request doesn't need to be intercepted */
2411    return JB_ERR_OK ;
2412 }
2413
2414 /*********************************************************************
2415  *
2416  * Function    :  open_forwarding_connection
2417  *
2418  * Description :  Check whether to intercept page
2419  *
2420  * Parameters  :
2421  *          1  :  client_state structure
2422  *          2  :  http_request structure
2423  *                         
2424  * Returns     :  JB_ERR_OK  - Connection opened ok
2425  *             :  all other values - an error occurred.  
2426  *********************************************************************/
2427 static jb_err open_forwarding_connection(struct client_state *csp )
2428 {
2429    struct http_response *rsp;
2430    
2431 #ifdef FEATURE_ACTIVITY_CONSOLE
2432    accumulate_stats(STATS_REQUEST, 1);
2433 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2434    log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2435
2436    if (csp->http->fwd->forward_host)
2437    {
2438       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2439                csp->http->fwd->forward_host, csp->http->fwd->forward_port, 
2440                csp->http->hostport);
2441    }
2442    else
2443    {
2444       log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2445    }
2446
2447    /* here we connect to the server, gateway, or the forwarder */
2448
2449    csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2450
2451    if (csp->sfd == JB_INVALID_SOCKET)
2452    {
2453       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2454                 csp->http->hostport);
2455
2456       if (errno == EINVAL)
2457       {
2458          rsp = error_response(csp, "no-such-domain", errno);
2459
2460          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2461                    csp->ip_addr_str, csp->http->ocmd);
2462       }
2463       else
2464       {
2465          rsp = error_response(csp, "connect-failed", errno);
2466
2467          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2468                    csp->ip_addr_str, csp->http->ocmd);
2469       }
2470
2471
2472       /* Write the answer to the client */
2473       if(rsp)
2474       {
2475          if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2476           || write_socket(csp->cfd, rsp->body, rsp->content_length))
2477          {
2478             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2479          }
2480       }
2481
2482       free_http_response(rsp);
2483       return JB_ERR_GENERIC;
2484    }
2485
2486    log_error(LOG_LEVEL_CONNECT, "OK");
2487    return JB_ERR_OK ;
2488
2489 } /* END open_forwarding_connection() */
2490
2491
2492 /*********************************************************************
2493  *
2494  * Function    :  send_client_headers_to_server
2495  *
2496  * Description :  send the client headers (possibly modified) to the server
2497  *
2498  * Parameters  :
2499  *          1  :  client_state structure
2500  *          2  :  http_request structure
2501  *                         
2502  *
2503  * Returns     :  JB_ERR_OK  - headers sent ok
2504  *             :  other values - an error occurred.
2505  *********************************************************************/
2506
2507 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2508 {
2509
2510    struct http_response *rsp;
2511
2512    if (http->fwd->forward_host || (http->ssl == 0))
2513    {
2514       /* write the client's (modified) header to the server
2515        * (along with anything else that may be in the buffer)
2516        */
2517
2518       if (write_socket(csp->sfd, hdr, strlen(hdr))
2519        || (flush_socket(csp->sfd, csp) <  0))
2520       {
2521          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2522                     http->hostport);
2523
2524          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2525                    csp->ip_addr_str, http->ocmd);
2526
2527          rsp = error_response(csp, "connect-failed", errno);
2528
2529          if(rsp)
2530          {
2531             if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2532              || write_socket(csp->cfd, rsp->body, rsp->content_length))
2533             {
2534                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2535             }
2536          }
2537
2538          free_http_response(rsp);
2539          return JB_ERR_GENERIC;
2540       }
2541    }
2542    else
2543    {
2544       /*
2545        * We're running an SSL tunnel and we're not forwarding,
2546        * so just send the "connect succeeded" message to the
2547        * client, flush the rest, and get out of the way.
2548        */
2549       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2550                 csp->ip_addr_str, http->ocmd);
2551
2552       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2553       {
2554          return JB_ERR_OK;
2555       }
2556       IOB_RESET(csp);
2557    }
2558
2559    return JB_ERR_OK ;
2560 } /* END send_client_headers_to_server */
2561
2562
2563 /*********************************************************************
2564  *
2565  * Function    :  is_connect_request_allowed
2566  *
2567  * Description :  send the client headers (possibly modified) to the server
2568  *
2569  * Parameters  :
2570  *          1  :  client_state structure
2571  *
2572  *                         
2573  *
2574  * Returns     :  JB_ERR_OK  - connect request allowed
2575  *             :  other values - connect request not allowed
2576  *********************************************************************/
2577 static jb_err is_connect_request_allowed( struct client_state *csp )
2578 {
2579    /*
2580     * Check if a CONNECT request is allowable:
2581     * In the absence of a +limit-connect action, allow only port 443.
2582     * If there is an action, allow whatever matches the specificaton.
2583     */
2584
2585    if(csp->http->ssl)
2586    {
2587       if(  ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2588            || (csp->action->flags & ACTION_LIMIT_CONNECT
2589               && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2590       {
2591          char buf[BUFFER_SIZE];
2592          strcpy(buf, CFORBIDDEN);
2593          write_socket(csp->cfd, buf, strlen(buf));
2594
2595          log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2596          log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2597
2598          return JB_ERR_GENERIC;
2599       }
2600    }
2601
2602    return JB_ERR_OK ;
2603 } /* END is_connect_request_allowed */
2604
2605 /*
2606   Local Variables:
2607   tab-width: 3
2608   end:
2609 */