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