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