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