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