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