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