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