Rebuilding from latest configure.in and acconfig.h
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.33 2001/07/29 19:32:00 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.33  2001/07/29 19:32:00  jongfoster
37  *    Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
38  *
39  *    Revision 1.32  2001/07/29 18:47:05  jongfoster
40  *    Adding missing #include "loadcfg.h"
41  *
42  *    Revision 1.31  2001/07/29 12:17:48  oes
43  *    Applied pthread fix by Paul Lieverse
44  *
45  *    Revision 1.30  2001/07/25 22:57:13  jongfoster
46  *    __BEOS__ no longer overrides FEATURE_PTHREAD.
47  *    This is because FEATURE_PTHREAD will soon be widely used, so I
48  *    want to keep it simple.
49  *
50  *    Revision 1.29  2001/07/24 12:47:06  oes
51  *    Applied BeOS support update by Eugenia
52  *
53  *    Revision 1.28  2001/07/23 13:26:12  oes
54  *    Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
55  *
56  *    Revision 1.27  2001/07/19 19:09:47  haroon
57  *    - Added code to take care of the situation where while processing the first
58  *      server response (which includes the server header), after finding the end
59  *      of the headers we were not looking past the end of the headers for
60  *      content modification. I enabled it for filter_popups.
61  *      Someone else should look to see if other similar operations should be
62  *      done to the discarded portion of the buffer.
63  *
64  *      Note 2001/07/20: No, the other content modification mechanisms will process
65  *                       the whole iob later anyway. --oes
66  *
67  *    Revision 1.26  2001/07/18 12:31:36  oes
68  *    cosmetics
69  *
70  *    Revision 1.25  2001/07/15 19:43:49  jongfoster
71  *    Supports POSIX threads.
72  *    Also removed some unused #includes.
73  *
74  *    Revision 1.24  2001/07/13 14:00:40  oes
75  *     - Generic content modification scheme:
76  *       Each feature has its own applicability flag that is set
77  *       from csp->action->flags.
78  *       Replaced the "filtering" int flag , by a function pointer
79  *       "content_filter" to the function that will do the content
80  *       modification. If it is != NULL, the document will be buffered
81  *       and processed through *content_filter, which must set
82  *       csp->content_length and return a modified copy of the body
83  *       or return NULL (on failiure).
84  *     - Changed csp->is_text to the more generic bitmap csp->content_type
85  *       which can currently take the valued CT_TEXT or CT_GIF
86  *     - Reformatting etc
87  *     - Removed all #ifdef PCRS
88  *
89  *    Revision 1.23  2001/07/02 02:28:25  iwanttokeepanon
90  *    Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
91  *    the `block_acl' call.  This prevents a compilation error when the user
92  *    does not wish to use the "ACL" feature.
93  *
94  *    Revision 1.22  2001/06/29 21:45:41  oes
95  *    Indentation, CRLF->LF, Tab-> Space
96  *
97  *    Revision 1.21  2001/06/29 13:29:36  oes
98  *    - Cleaned up, improved comments
99  *    - Unified all possible interceptors (CGI,
100  *      block, trust, fast_redirect) in one
101  *      place, with one (CGI) answer generation
102  *      mechansim. Much clearer now.
103  *    - Removed the GIF image generation, which
104  *      is now done in filters.c:block_url()
105  *    - Made error conditions like domain lookup
106  *      failiure or (various) problems while talking
107  *      to the server use cgi.c:error_response()
108  *      instead of generating HTML/HTTP in chat() (yuck!)
109  *    - Removed logentry from cancelled commit
110  *
111  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
112  *    Changing BUFSIZ ==> BUFFER_SIZE
113  *
114  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
115  *    Replacing function pointer in struct gateway with a directly
116  *    called function forwarded_connect().
117  *    Replacing struct gateway with struct forward_spec
118  *
119  *    Revision 1.18  2001/06/03 19:12:16  oes
120  *    introduced new cgi handling
121  *
122  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
123  *    Now uses action +image-blocker{} rather than config->tinygif
124  *
125  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
126  *    Replaced "list_share" with "list" - the tiny memory gain was not
127  *    worth the extra complexity.
128  *
129  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
130  *    Changed "permission" to "action" throughout.
131  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
132  *    Moved vanilla wafer check into chat(), since we must now
133  *    decide whether or not to add it based on the URL.
134  *
135  *    Revision 1.14  2001/05/29 20:14:01  joergs
136  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
137  *    increased.
138  *
139  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
140  *    Unified blocklist/imagelist/permissionslist.
141  *    File format is still under discussion, but the internal changes
142  *    are (mostly) done.
143  *
144  *    Also modified interceptor behaviour:
145  *    - We now intercept all URLs beginning with one of the following
146  *      prefixes (and *only* these prefixes):
147  *        * http://i.j.b/
148  *        * http://ijbswa.sf.net/config/
149  *        * http://ijbswa.sourceforge.net/config/
150  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
151  *    - Internal changes so that intercepted and fast redirect pages
152  *      are not replaced with an image.
153  *    - Interceptors now have the option to send a binary page direct
154  *      to the client. (i.e. ijb-send-banner uses this)
155  *    - Implemented show-url-info interceptor.  (Which is why I needed
156  *      the above interceptors changes - a typical URL is
157  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
158  *      The previous mechanism would not have intercepted that, and
159  *      if it had been intercepted then it then it would have replaced
160  *      it with an image.)
161  *
162  *    Revision 1.12  2001/05/27 22:17:04  oes
163  *
164  *    - re_process_buffer no longer writes the modified buffer
165  *      to the client, which was very ugly. It now returns the
166  *      buffer, which it is then written by chat.
167  *
168  *    - content_length now adjusts the Content-Length: header
169  *      for modified documents rather than crunch()ing it.
170  *      (Length info in csp->content_length, which is 0 for
171  *      unmodified documents)
172  *
173  *    - For this to work, sed() is called twice when filtering.
174  *
175  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
176  *    Added support for CLF and fixed LOG_LEVEL_LOG.
177  *    Also did CRLF->LF fix of my previous patch.
178  *
179  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
180  *    ACL feature now provides more security by immediately dropping
181  *    connections from untrusted hosts.
182  *
183  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
184  *    Automatic reloading of config file.
185  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
186  *    Most of the global variables have been moved to a new
187  *    struct configuration_spec, accessed through csp->config->globalname
188  *    Most of the globals remaining are used by the Win32 GUI.
189  *
190  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
191  *    Fixing minor memory leak and buffer overflow.
192  *
193  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
194  *    Hard tabs->Spaces
195  *
196  *    Revision 1.6  2001/05/23 00:13:58  joergs
197  *    AmigaOS support fixed.
198  *
199  *    Revision 1.5  2001/05/22 18:46:04  oes
200  *
201  *    - Enabled filtering banners by size rather than URL
202  *      by adding patterns that replace all standard banner
203  *      sizes with the "Junkbuster" gif to the re_filterfile
204  *
205  *    - Enabled filtering WebBugs by providing a pattern
206  *      which kills all 1x1 images
207  *
208  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
209  *      which is selected by the (nonstandard and therefore
210  *      capital) letter 'U' in the option string.
211  *      It causes the quantifiers to be ungreedy by default.
212  *      Appending a ? turns back to greedy (!).
213  *
214  *    - Added a new interceptor ijb-send-banner, which
215  *      sends back the "Junkbuster" gif. Without imagelist or
216  *      MSIE detection support, or if tinygif = 1, or the
217  *      URL isn't recognized as an imageurl, a lame HTML
218  *      explanation is sent instead.
219  *
220  *    - Added new feature, which permits blocking remote
221  *      script redirects and firing back a local redirect
222  *      to the browser.
223  *      The feature is conditionally compiled, i.e. it
224  *      can be disabled with --disable-fast-redirects,
225  *      plus it must be activated by a "fast-redirects"
226  *      line in the config file, has its own log level
227  *      and of course wants to be displayed by show-proxy-args
228  *      Note: Boy, all the #ifdefs in 1001 locations and
229  *      all the fumbling with configure.in and acconfig.h
230  *      were *way* more work than the feature itself :-(
231  *
232  *    - Because a generic redirect template was needed for
233  *      this, tinygif = 3 now uses the same.
234  *
235  *    - Moved GIFs, and other static HTTP response templates
236  *      to project.h
237  *
238  *    - Some minor fixes
239  *
240  *    - Removed some >400 CRs again (Jon, you really worked
241  *      a lot! ;-)
242  *
243  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
244  *    Made failure to bind() a fatal error.
245  *
246  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
247  *    Version 2.9.4 checkin.
248  *    - Merged popupfile and cookiefile, and added control over PCRS
249  *      filtering, in new "permissionsfile".
250  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
251  *      file error you now get a message box (in the Win32 GUI) rather
252  *      than the program exiting with no explanation.
253  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
254  *      skipping.
255  *    - Removed tabs from "config"
256  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
257  *    - Bumped up version number.
258  *
259  *    Revision 1.2  2001/05/17 22:34:44  oes
260  *     - Added hint on GIF char array generation to jcc.c
261  *     - Cleaned CRLF's from the sources and related files
262  *     - Repaired logging for REF and FRC
263  *
264  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
265  *    Initial import of version 2.9.3 source tree
266  *
267  *
268  *********************************************************************/
269 \f
270
271 #include "config.h"
272
273 #include <stdio.h>
274 #include <sys/types.h>
275 #include <stdlib.h>
276 #include <string.h>
277 #include <signal.h>
278 #include <fcntl.h>
279 #include <errno.h>
280
281 #ifdef FEATURE_PTHREAD
282 #include <pthread.h>
283 #endif /* def FEATURE_PTHREAD */
284
285 #ifdef _WIN32
286 # ifndef FEATURE_PTHREAD
287 #  include <windows.h>
288 #  include <process.h>
289 # endif /* ndef FEATURE_PTHREAD */
290
291 # include "win32.h"
292 # ifndef _WIN_CONSOLE
293 #  include "w32log.h"
294 # endif /* ndef _WIN_CONSOLE */
295
296 #else /* ifndef _WIN32 */
297
298 # include <unistd.h>
299 # include <sys/time.h>
300 # include <sys/wait.h>
301 # include <sys/stat.h>
302 # include <signal.h>
303
304 # ifdef __BEOS__
305 #  include <socket.h>  /* BeOS has select() for sockets only. */
306 #  include <OS.h>      /* declarations for threads and stuff. */
307 # endif
308
309 # ifndef FD_ZERO
310 #  include <select.h>
311 # endif
312
313 #endif
314
315 #include "project.h"
316 #include "list.h"
317 #include "jcc.h"
318 #include "filters.h"
319 #include "loaders.h"
320 #include "showargs.h"
321 #include "parsers.h"
322 #include "killpopup.h"
323 #include "miscutil.h"
324 #include "errlog.h"
325 #include "jbsockets.h"
326 #include "gateway.h"
327 #include "actions.h"
328 #include "cgi.h"
329 #include "loadcfg.h"
330
331 const char jcc_h_rcs[] = JCC_H_VERSION;
332 const char project_h_rcs[] = PROJECT_H_VERSION;
333
334 struct client_state  clients[1];
335 struct file_list     files[1];
336
337 #ifdef FEATURE_STATISTICS
338 int urls_read     = 0;     /* total nr of urls read inc rejected */
339 int urls_rejected = 0;     /* total nr of urls rejected */
340 #endif /* def FEATURE_STATISTICS */
341
342
343 static void listen_loop(void);
344 static void chat(struct client_state *csp);
345 #ifdef AMIGA
346 void serve(struct client_state *csp);
347 #else /* ifndef AMIGA */
348 static void serve(struct client_state *csp);
349 #endif /* def AMIGA */
350
351 #ifdef __BEOS__
352 static int32 server_thread(void *data);
353 #endif /* def __BEOS__ */
354
355 #ifdef _WIN32
356 #define sleep(N)  Sleep(((N) * 1000))
357 #endif
358
359
360 /* The vanilla wafer. */
361 static const char VANILLA_WAFER[] =
362    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
363    "Do_not_send_me_any_copyrighted_information_other_than_the_"
364    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
365    "In_particular_do_not_send_me_any_cookies_that_"
366    "are_subject_to_a_claim_of_copyright_by_anybody._"
367    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
368    "(copyright_or_otherwise)_applying_to_any_cookie._";
369
370
371 /*********************************************************************
372  *
373  * Function    :  chat
374  *
375  * Description :  Once a connection to the client has been accepted,
376  *                this function is called (via serve()) to handle the
377  *                main business of the communication.  When this 
378  *                function returns, the caller must close the client
379  *                socket handle.
380  *
381  * Parameters  :
382  *          1  :  csp = Current client state (buffers, headers, etc...)
383  *
384  * Returns     :  On success, the number of bytes written are returned (zero
385  *                indicates nothing was written).  On error, -1 is returned,
386  *                and errno is set appropriately.  If count is zero and the
387  *                file descriptor refers to a regular file, 0 will be
388  *                returned without causing any other effect.  For a special
389  *                file, the results are not portable.
390  *
391  *********************************************************************/
392 static void chat(struct client_state *csp)
393 {
394 /*
395  * This next lines are a little ugly, but they simplifies the if statements
396  * below.  Basically if TOGGLE, then we want the if to test "csp->toggled_on",
397  * else we don't.  And if FEATURE_FORCE_LOAD, then we want the if to test
398  * "csp->toggled_on", else we don't
399  */
400 #ifdef FEATURE_TOGGLE
401 #   define IS_TOGGLED_ON_AND (csp->toggled_on) &&
402 #else /* ifndef FEATURE_TOGGLE */
403 #   define IS_TOGGLED_ON_AND
404 #endif /* ndef FEATURE_TOGGLE */
405 #ifdef FEATURE_FORCE_LOAD
406 #   define IS_NOT_FORCED_AND (!csp->force) && 
407 #else /* ifndef FEATURE_FORCE_LOAD */
408 #   define IS_NOT_FORCED_AND
409 #endif /* def FEATURE_FORCE_LOAD */
410
411 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
412
413    char buf[BUFFER_SIZE];
414    char *hdr, *p, *req;
415    char *err = NULL;
416    fd_set rfds;
417    int n, maxfd, server_body;
418    int ms_iis5_hack = 0;
419    int byte_count = 0;
420    const struct forward_spec * fwd;
421    struct http_request *http;
422 #ifdef FEATURE_KILL_POPUPS
423    int block_popups;         /* bool, 1==will block popups */
424    int block_popups_now = 0; /* bool, 1==currently blocking popups */
425 #endif /* def FEATURE_KILL_POPUPS */
426
427    int pcrs_filter;        /* bool, 1==will filter through pcrs */
428    int gif_deanimate;      /* bool, 1==will deanimate gifs */
429
430    /* Function that does the content filtering for the current request */
431    char *(*content_filter)() = NULL; 
432
433    /* Skeleton for HTTP response, if we should intercept the request */
434    struct http_response *rsp;
435
436    http = csp->http;
437
438    /*
439     * Read the client's request.  Note that since we're not using select() we
440     * could get blocked here if a client connected, then didn't say anything!
441     */
442
443    while (FOREVER)
444    {
445       n = read_socket(csp->cfd, buf, sizeof(buf));
446
447       if (n <= 0) break;      /* error! */
448
449       add_to_iob(csp, buf, n);
450
451       req = get_header(csp);
452
453       if (req == NULL)
454       {
455          break;    /* no HTTP request! */
456       }
457
458       if (*req == '\0')
459       {
460          continue;   /* more to come! */
461       }
462  
463 #ifdef FEATURE_FORCE_LOAD
464       /* If this request contains the FORCE_PREFIX,
465        * better get rid of it now and set the force flag --oes
466        */
467
468       if (strstr(req, FORCE_PREFIX))
469       {
470          strclean(req, FORCE_PREFIX);
471          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
472          csp->force = 1;
473       } 
474       else
475       {
476          csp->force = 0;
477       }
478 #endif /* def FEATURE_FORCE_LOAD */
479   
480       parse_http_request(req, http, csp);
481       freez(req);
482       break;
483    }
484
485    if (http->cmd == NULL)
486    {
487       strcpy(buf, CHEADER);
488       write_socket(csp->cfd, buf, strlen(buf));
489
490       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
491
492       return;
493    }
494
495    /* decide how to route the HTTP request */
496
497    if ((fwd = forward_url(http, csp)) == NULL)
498    {
499       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
500       /* Never get here - LOG_LEVEL_FATAL causes program exit */
501    }
502
503    /* build the http request to send to the server
504     * we have to do one of the following:
505     *
506     * create = use the original HTTP request to create a new
507     *          HTTP request that has only the path component
508     *          without the http://domainspec
509     * pass   = pass the original HTTP request unchanged
510     *
511     * drop   = drop the HTTP request
512     *
513     * here's the matrix:
514     *                        SSL
515     *                    0        1
516     *                +--------+--------+
517     *                |        |        |
518     *             0  | create | drop   |
519     *                |        |        |
520     *  Forwarding    +--------+--------+
521     *                |        |        |
522     *             1  | pass   | pass   |
523     *                |        |        |
524     *                +--------+--------+
525     *
526     */
527
528    if (fwd->forward_host)
529    {
530       /* if forwarding, just pass the request as is */
531       enlist(csp->headers, http->cmd);
532    }
533    else
534    {
535       if (http->ssl == 0)
536       {
537          /* otherwise elide the host information from the url */
538          p = NULL;
539          p = strsav(p, http->gpc);
540          p = strsav(p, " ");
541          p = strsav(p, http->path);
542          p = strsav(p, " ");
543          p = strsav(p, http->ver);
544          enlist(csp->headers, p);
545          freez(p);
546       }
547    }
548
549    /* decide what we're to do with cookies */
550
551 #ifdef FEATURE_TOGGLE
552    if (!csp->toggled_on)
553    {
554       /* Most compatible set of actions (i.e. none) */
555       init_current_action(csp->action);
556    }
557    else
558 #endif /* ndef FEATURE_TOGGLE */
559    {
560       url_actions(http, csp);
561    }
562
563 #ifdef FEATURE_COOKIE_JAR
564    /*
565     * If we're logging cookies in a cookie jar, and the user has not
566     * supplied any wafers, and the user has not told us to suppress the
567     * vanilla wafer, then send the vanilla wafer.
568     */
569    if ((csp->config->jarfile != NULL)
570        && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
571        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
572    {
573       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
574    }
575 #endif /* def FEATURE_COOKIE_JAR */
576
577 #ifdef FEATURE_KILL_POPUPS
578    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
579 #endif /* def FEATURE_KILL_POPUPS */
580
581    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
582                                 ((csp->action->flags & ACTION_FILTER) != 0);
583
584    gif_deanimate              = ((csp->action->flags & ACTION_DEANIMATE) != 0);
585
586    /* grab the rest of the client's headers */
587
588    while (FOREVER)
589    {
590       if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
591       {
592          n = read_socket(csp->cfd, buf, sizeof(buf));
593          if (n <= 0)
594          {
595             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
596             return;
597          }
598          add_to_iob(csp, buf, n);
599          continue;
600       }
601
602       if (p == NULL) break;
603
604       enlist(csp->headers, p);
605       freez(p);
606    }
607
608    /* We have a request. */
609
610    hdr = sed(client_patterns, add_client_headers, csp);
611    destroy_list(csp->headers);
612
613    /* 
614     * Now, check to see if we need to intercept it, i.e.
615     * If
616     */
617  
618    if (
619        /* a CGI call was detected and answered */
620          (NULL != (rsp = dispatch_cgi(csp))) 
621
622        /* or we are enabled and... */
623        || (IS_ENABLED_AND (
624
625             /* ..the request was blocked */
626             ( NULL != (rsp = block_url(csp)))
627
628           /* ..or untrusted */
629 #ifdef FEATURE_TRUST
630           || ( NULL != (rsp = trust_url(csp)))
631 #endif /* def FEATURE_TRUST */
632
633           /* ..or a fast redirect kicked in */
634 #ifdef FEATURE_FAST_REDIRECTS
635           || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) && 
636                      (NULL != (rsp = redirect_url(csp))))
637 #endif /* def FEATURE_FAST_REDIRECTS */
638                  ))
639         )
640    {
641       /* Write the answer to the client */
642       if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
643              || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
644       { 
645          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
646       }
647
648 #ifdef FEATURE_STATISTICS
649       /* Count as a rejected request */
650       csp->rejected = 1;
651 #endif /* def FEATURE_STATISTICS */
652
653       /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
654       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
655       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd); 
656
657       /* Clean up and return */
658       free_http_response(rsp);
659       freez(hdr);
660       return;
661    }
662
663    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
664
665    if (fwd->forward_host)
666    {
667       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
668                fwd->forward_host, fwd->forward_port, http->hostport);
669    }
670    else
671    {
672       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
673    }
674
675    /* here we connect to the server, gateway, or the forwarder */
676
677    csp->sfd = forwarded_connect(fwd, http, csp);
678
679    if (csp->sfd < 0)
680    {
681       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
682                 http->hostport);
683
684       if (errno == EINVAL)
685       {
686            rsp = error_response(csp, "no-such-domain", errno);
687
688          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0", 
689                    csp->ip_addr_str, http->cmd);
690       }
691       else
692       {
693            rsp = error_response(csp, "connect-failed", errno);
694
695          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
696                    csp->ip_addr_str, http->cmd);
697       }
698
699       /* Write the answer to the client */
700       if(rsp)
701         {
702          if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
703                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
704          { 
705             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
706          }
707       }
708
709       free_http_response(rsp);
710       freez(hdr);
711       return;
712    }
713
714    log_error(LOG_LEVEL_CONNECT, "OK");
715
716    if (fwd->forward_host || (http->ssl == 0))
717    {
718       /* write the client's (modified) header to the server
719        * (along with anything else that may be in the buffer)
720        */
721
722       n = strlen(hdr);
723
724       if ((write_socket(csp->sfd, hdr, n) != n)
725           || (flush_socket(csp->sfd, csp   ) <  0))
726       {
727          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
728                     http->hostport);
729
730          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
731                    csp->ip_addr_str, http->cmd); 
732
733          rsp = error_response(csp, "connect-failed", errno);
734
735          if(rsp)
736          {
737             if ((write_socket(csp->cfd, rsp->head, n) != n)
738                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
739             { 
740                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
741             }
742          }
743
744          free_http_response(rsp);
745          freez(hdr);
746          return;
747       }
748    }
749    else
750    {
751       /*
752        * We're running an SSL tunnel and we're not forwarding,
753        * so just send the "connect succeeded" message to the
754        * client, flush the rest, and get out of the way.
755        */
756       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n", 
757                 csp->ip_addr_str, http->cmd); 
758
759       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
760       {
761          freez(hdr);
762          return;
763       }
764       IOB_RESET(csp);
765    }
766
767    /* we're finished with the client's header */
768    freez(hdr);
769
770    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
771
772    /* pass data between the client and server
773     * until one or the other shuts down the connection.
774     */
775
776    server_body = 0;
777
778    while (FOREVER)
779    {
780       FD_ZERO(&rfds);
781
782       FD_SET(csp->cfd, &rfds);
783       FD_SET(csp->sfd, &rfds);
784
785       n = select(maxfd+1, &rfds, NULL, NULL, NULL);
786
787       if (n < 0)
788       {
789          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
790          return;
791       }
792
793       /* this is the body of the browser's request
794        * just read it and write it.
795        */
796
797       if (FD_ISSET(csp->cfd, &rfds))
798       {
799          n = read_socket(csp->cfd, buf, sizeof(buf));
800
801          if (n <= 0)
802          {
803             break; /* "game over, man" */
804          }
805
806          if (write_socket(csp->sfd, buf, n) != n)
807          {
808             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
809             return;
810          }
811          continue;
812       }
813
814       /*
815        * The server wants to talk.  It could be the header or the body.
816        * If `hdr' is null, then it's the header otherwise it's the body.
817        * FIXME: Does `hdr' really mean `host'? No.
818        */
819
820
821       if (FD_ISSET(csp->sfd, &rfds))
822       {
823          fflush( 0 );
824          n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
825
826          if (n < 0)
827          {
828             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
829
830             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
831                       csp->ip_addr_str, http->cmd); 
832
833             rsp = error_response(csp, "connect-failed", errno);
834
835             if(rsp)
836             {
837                if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
838                     || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
839                { 
840                   log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
841                            }
842                         }
843
844             free_http_response(rsp);
845             return;
846          }
847
848          /* Add a trailing zero.  This lets filter_popups
849           * use string operations.
850           */
851          buf[n] = '\0';
852
853 #ifdef FEATURE_KILL_POPUPS
854          /* Filter the popups on this read. */
855          if (block_popups_now)
856          {
857             filter_popups(buf, n);
858          }
859 #endif /* def FEATURE_KILL_POPUPS */
860
861          /* Normally, this would indicate that we've read
862           * as much as the server has sent us and we can
863           * close the client connection.  However, Microsoft
864           * in its wisdom has released IIS/5 with a bug that
865           * prevents it from sending the trailing \r\n in
866           * a 302 redirect header (and possibly other headers).
867           * To work around this if we've haven't parsed
868           * a full header we'll append a trailing \r\n
869           * and see if this now generates a valid one.
870           *
871           * This hack shouldn't have any impacts.  If we've
872           * already transmitted the header or if this is a
873           * SSL connection, then we won't bother with this
874           * hack.  So we only work on partially received
875           * headers.  If we append a \r\n and this still
876           * doesn't generate a valid header, then we won't
877           * transmit anything to the client.
878           */
879          if (n == 0)
880          {
881             
882             if (server_body || http->ssl)
883             {
884                /*
885                 * If we have been buffering up the document,
886                 * now is the time to apply content modification
887                 * and send the result to the client.
888                 */
889                if (content_filter)
890                {
891                   /*
892                    * If the content filter fails, use the original
893                    * buffer and length.
894                    * (see p != NULL ? p : csp->iob->cur below)
895                    */
896                   if (NULL == (p = (*content_filter)(csp)))
897                   {
898                      csp->content_length = csp->iob->eod - csp->iob->cur;
899                   }
900
901                   hdr = sed(server_patterns, add_server_headers, csp);
902                   n = strlen(hdr);
903
904                   if ((write_socket(csp->cfd, hdr, n) != n)
905                       || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
906                   {
907                      log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
908                      return;
909                   }
910
911                   freez(hdr);
912                   freez(p);
913                }
914
915                break; /* "game over, man" */
916             }
917
918             /*
919              * This is NOT the body, so 
920              * Let's pretend the server just sent us a blank line.
921              */
922             n = sprintf(buf, "\r\n");
923
924             /*
925              * Now, let the normal header parsing algorithm below do its
926              * job.  If it fails, we'll exit instead of continuing.
927              */
928
929             ms_iis5_hack = 1;
930          }
931
932          /*
933           * If this is an SSL connection or we're in the body
934           * of the server document, just write it to the client,
935           * unless we need to buffer the body for later content-filtering
936           */
937
938          if (server_body || http->ssl)
939          {
940             if (content_filter)
941             {
942                add_to_iob(csp, buf, n); 
943             }
944             else
945             {
946                if (write_socket(csp->cfd, buf, n) != n)
947                {
948                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
949                   return;
950                }
951             }
952             byte_count += n;
953             continue;
954          }
955          else
956          {
957             /* we're still looking for the end of the
958              * server's header ... (does that make header
959              * parsing an "out of body experience" ?
960              */
961
962             /* buffer up the data we just read */
963             add_to_iob(csp, buf, n);
964
965             /* get header lines from the iob */
966
967             while ((p = get_header(csp)))
968             {
969                if (*p == '\0')
970                {
971                   /* see following note */
972                   break;
973                }
974                enlist(csp->headers, p);
975                freez(p);
976             }
977
978             /* NOTE: there are no "empty" headers so
979              * if the pointer `p' is not NULL we must
980              * assume that we reached the end of the
981              * buffer before we hit the end of the header.
982              */
983
984             if (p)
985             {
986                if (ms_iis5_hack)
987                {
988                   /* Well, we tried our MS IIS/5
989                    * hack and it didn't work.
990                    * The header is incomplete
991                    * and there isn't anything
992                    * we can do about it.
993                    */
994                   break;
995                }
996                else
997                {
998                   /* Since we have to wait for
999                    * more from the server before
1000                    * we can parse the headers
1001                    * we just continue here.
1002                    */
1003                   continue;
1004                }
1005             }
1006
1007             /* we have now received the entire header.
1008              * filter it and send the result to the client
1009              */
1010
1011             hdr = sed(server_patterns, add_server_headers, csp);
1012             n   = strlen(hdr);
1013
1014             /* write the server's (modified) header to
1015              * the client (along with anything else that
1016              * may be in the buffer)
1017              */
1018
1019 #ifdef FEATURE_KILL_POPUPS
1020             /* Start blocking popups if appropriate. */
1021
1022             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
1023                 !http->ssl    &&                  /* We talk plaintext */
1024                 block_popups)                     /* Policy allows */
1025             {
1026                block_popups_now = 1;
1027                /*
1028                 * Filter the part of the body that came in the same read
1029                 * as the last headers:
1030                 */
1031                filter_popups(csp->iob->cur, csp->iob->eod - csp->iob->cur);
1032             }
1033
1034 #endif /* def FEATURE_KILL_POPUPS */
1035
1036             /* Buffer and pcrs filter this if appropriate. */
1037
1038             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
1039                 !http->ssl    &&                  /* We talk plaintext */
1040                 pcrs_filter)                      /* Policy allows */
1041             {
1042                content_filter = pcrs_filter_response;
1043             }
1044
1045             /* Buffer and gif_deanimate this if appropriate. */
1046
1047             if ((csp->content_type & CT_GIF)  &&  /* It's a image/gif MIME-Type */
1048                 !http->ssl    &&                  /* We talk plaintext */
1049                 gif_deanimate)                    /* Policy allows */
1050             {
1051                content_filter = gif_deanimate_response;
1052             }
1053
1054
1055             /*
1056              * Only write if we're not buffering for content modification
1057              */
1058             if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1059                 || (n = flush_socket(csp->cfd, csp) < 0)))
1060             {
1061                log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1062
1063                /* the write failed, so don't bother
1064                 * mentioning it to the client...
1065                 * it probably can't hear us anyway.
1066                 */
1067                freez(hdr);
1068                return;
1069             }
1070
1071             !content_filter && (byte_count += n);
1072
1073             /* we're finished with the server's header */
1074
1075             freez(hdr);
1076             server_body = 1;
1077
1078             /* If this was a MS IIS/5 hack then it means
1079              * the server has already closed the
1080              * connection.  Nothing more to read.  Time
1081              * to bail.
1082              */
1083             if (ms_iis5_hack)
1084             {
1085                break;
1086             }
1087          }
1088          continue;
1089       }
1090
1091       return; /* huh? we should never get here */
1092    }
1093
1094    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d", 
1095              csp->ip_addr_str, http->cmd, byte_count); 
1096 }
1097
1098
1099 /*********************************************************************
1100  *
1101  * Function    :  serve
1102  *
1103  * Description :  This is little more than chat.  We only "serve" to
1104  *                to close any socket that chat may have opened.
1105  *
1106  * Parameters  :
1107  *          1  :  csp = Current client state (buffers, headers, etc...)
1108  *
1109  * Returns     :  N/A
1110  *
1111  *********************************************************************/
1112 #ifdef AMIGA
1113 void serve(struct client_state *csp)
1114 #else /* ifndef AMIGA */
1115 static void serve(struct client_state *csp)
1116 #endif /* def AMIGA */
1117 {
1118    chat(csp);
1119    close_socket(csp->cfd);
1120
1121    if (csp->sfd >= 0)
1122    {
1123       close_socket(csp->sfd);
1124    }
1125
1126    csp->active = 0;
1127
1128 }
1129
1130
1131 #ifdef __BEOS__
1132 /*********************************************************************
1133  *
1134  * Function    :  server_thread
1135  *
1136  * Description :  We only exist to call `serve' in a threaded environment.
1137  *
1138  * Parameters  :
1139  *          1  :  data = Current client state (buffers, headers, etc...)
1140  *
1141  * Returns     :  Always 0.
1142  *
1143  *********************************************************************/
1144 static int32 server_thread(void *data)
1145 {
1146    serve((struct client_state *) data);
1147    return 0;
1148
1149 }
1150 #endif
1151
1152
1153 /*********************************************************************
1154  *
1155  * Function    :  main
1156  *
1157  * Description :  Load the config file and start the listen loop.
1158  *                This function is a lot more *sane* with the `load_config'
1159  *                and `listen_loop' functions; although it stills does
1160  *                a *little* too much for my taste.
1161  *
1162  * Parameters  :
1163  *          1  :  argc = Number of parameters (including $0).
1164  *          2  :  argv = Array of (char *)'s to the parameters.
1165  *
1166  * Returns     :  1 if : can't open config file, unrecognized directive,
1167  *                stats requested in multi-thread mode, can't open the
1168  *                log file, can't open the jar file, listen port is invalid,
1169  *                any load fails, and can't bind port.
1170  *
1171  *                Else main never returns, the process must be signaled
1172  *                to terminate execution.  Or, on Windows, use the 
1173  *                "File", "Exit" menu option.
1174  *
1175  *********************************************************************/
1176 #ifdef __MINGW32__
1177 int real_main(int argc, const char *argv[])
1178 #else
1179 int main(int argc, const char *argv[])
1180 #endif
1181 {
1182    configfile =
1183 #ifdef AMIGA
1184    "AmiTCP:db/junkbuster/config"
1185 #elif !defined(_WIN32)
1186    "config"
1187 #else
1188    "junkbstr.txt"
1189 #endif
1190       ;
1191
1192 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1193    if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1194    {
1195       printf("JunkBuster proxy version " VERSION ".\n\n"
1196          "Usage: %s [configfile]\n\n"
1197          "See " HOME_PAGE_URL " for details.\n"
1198          "This program is distributed under the GNU GPL, version 2 or later.\n",
1199          argv[0]);
1200       exit(2);
1201    }
1202    if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1203    {
1204       printf(VERSION "\n");
1205       exit(2);
1206    }
1207 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1208
1209    Argc = argc;
1210    Argv = argv;
1211
1212    if (argc > 1)
1213    {
1214       configfile = argv[1];
1215    }
1216
1217    files->next = NULL;
1218
1219 #ifdef AMIGA
1220    InitAmiga();
1221 #elif defined(_WIN32)
1222    InitWin32();
1223 #endif
1224
1225
1226 #ifndef _WIN32
1227    signal(SIGPIPE, SIG_IGN);
1228    signal(SIGCHLD, SIG_IGN);
1229
1230 #else /* ifdef _WIN32 */
1231 # ifdef _WIN_CONSOLE
1232    /*
1233     * We *are* in a windows console app.
1234     * Print a verbose messages about FAQ's and such
1235     */
1236    printf(win32_blurb);
1237 # endif /* def _WIN_CONSOLE */
1238 #endif /* def _WIN32 */
1239
1240
1241    listen_loop();
1242
1243    /* NOTREACHED */
1244    return(-1);
1245
1246 }
1247
1248
1249 /*********************************************************************
1250  *
1251  * Function    :  listen_loop
1252  *
1253  * Description :  bind the listen port and enter a "FOREVER" listening loop.
1254  *
1255  * Parameters  :  N/A
1256  *
1257  * Returns     :  Never.
1258  *
1259  *********************************************************************/
1260 static void listen_loop(void)
1261 {
1262    struct client_state *csp = NULL;
1263    int bfd;
1264    struct configuration_spec * config;
1265
1266    config = load_config();
1267
1268    log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1269              config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1270
1271    bfd = bind_port(config->haddr, config->hport);
1272
1273    if (bfd < 0)
1274    {
1275       log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1276          "- There may be another junkbuster or some other "
1277          "proxy running on port %d", 
1278          (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1279          config->hport, config->hport
1280       );
1281       /* shouldn't get here */
1282       return;
1283    }
1284
1285    config->need_bind = 0;
1286
1287
1288    while (FOREVER)
1289    {
1290 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1291       while (waitpid(-1, NULL, WNOHANG) > 0)
1292       {
1293          /* zombie children */
1294       }
1295 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1296       sweep();
1297
1298       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1299       {
1300          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1301          continue;
1302       }
1303
1304       memset(csp, '\0', sizeof(*csp));
1305
1306       csp->active = 1;
1307       csp->sfd    = -1;
1308
1309       csp->config = config = load_config();
1310
1311       if ( config->need_bind )
1312       {
1313          /*
1314           * Since we were listening to the "old port", we will not see
1315           * a "listen" param change until the next IJB request.  So, at
1316           * least 1 more request must be made for us to find the new
1317           * setting.  I am simply closing the old socket and binding the
1318           * new one.
1319           *
1320           * Which-ever is correct, we will serve 1 more page via the
1321           * old settings.  This should probably be a "show-proxy-args"
1322           * request.  This should not be a so common of an operation
1323           * that this will hurt people's feelings.
1324           */
1325
1326          close_socket(bfd);
1327
1328          log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1329                    config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1330          bfd = bind_port(config->haddr, config->hport);
1331
1332          if (bfd < 0)
1333          {
1334             log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1335                "- There may be another junkbuster or some other "
1336                "proxy running on port %d", 
1337                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1338                config->hport, config->hport
1339             );
1340             /* shouldn't get here */
1341             return;
1342          }
1343
1344          config->need_bind = 0;
1345       }
1346
1347       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1348
1349       if (!accept_connection(csp, bfd))
1350       {
1351          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1352
1353 #ifdef AMIGA
1354          if(!childs)
1355          {
1356             exit(1); 
1357          }
1358 #endif
1359          freez(csp);
1360          continue;
1361       }
1362       else
1363       {
1364          log_error(LOG_LEVEL_CONNECT, "OK");
1365       }
1366
1367 #ifdef FEATURE_TOGGLE
1368       /* by haroon - most of credit to srt19170 */
1369       csp->toggled_on = g_bToggleIJB;
1370 #endif /* def FEATURE_TOGGLE */
1371
1372       if (run_loader(csp))
1373       {
1374          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1375          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1376       }
1377
1378 #ifdef FEATURE_ACL
1379       if (block_acl(NULL,csp))
1380       {
1381          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1382          close_socket(csp->cfd);
1383          freez(csp);
1384          continue;
1385       }
1386 #endif /* def FEATURE_ACL */
1387
1388       /* add it to the list of clients */
1389       csp->next = clients->next;
1390       clients->next = csp;
1391
1392       if (config->multi_threaded)
1393       {
1394          int child_id;
1395
1396 /* this is a switch () statment in the C preprocessor - ugh */
1397 #undef SELECTED_ONE_OPTION
1398
1399 /* Use Pthreads in preference to native code */
1400 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1401 #define SELECTED_ONE_OPTION
1402          {
1403             pthread_t the_thread;
1404             pthread_attr_t attrs;
1405
1406             pthread_attr_init(&attrs);
1407             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1408             child_id = (pthread_create(&the_thread, &attrs,
1409                (void*)serve, csp) ? -1 : 0);
1410             pthread_attr_destroy(&attrs);
1411          }
1412 #endif
1413
1414 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1415 #define SELECTED_ONE_OPTION
1416          child_id = _beginthread(
1417             (void*)serve,
1418             64 * 1024,
1419             csp);
1420 #endif
1421
1422 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1423 #define SELECTED_ONE_OPTION
1424          {
1425             thread_id tid = spawn_thread
1426                (server_thread, "server", B_NORMAL_PRIORITY, csp);
1427
1428             if ((tid >= 0) && (resume_thread(tid) == B_OK))
1429             {
1430                child_id = (int) tid;
1431             }
1432             else
1433             {
1434                child_id = -1;
1435             }
1436          }
1437 #endif
1438
1439 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1440 #define SELECTED_ONE_OPTION
1441          csp->cfd = ReleaseSocket(csp->cfd, -1);
1442          if((child_id = (int)CreateNewProcTags(
1443             NP_Entry, (ULONG)server_thread,
1444             NP_Output, Output(),
1445             NP_CloseOutput, FALSE,
1446             NP_Name, (ULONG)"junkbuster child",
1447             NP_StackSize, 200*1024,
1448             TAG_DONE)))
1449          {
1450             childs++;
1451             ((struct Task *)child_id)->tc_UserData = csp;
1452             Signal((struct Task *)child_id, SIGF_SINGLE);
1453             Wait(SIGF_SINGLE);
1454          }
1455 #endif
1456
1457 #if !defined(SELECTED_ONE_OPTION)
1458          child_id = fork();
1459
1460          /* This block is only needed when using fork().
1461           * When using threads, the server thread was
1462           * created and run by the call to _beginthread().
1463           */
1464          if (child_id == 0)   /* child */
1465          {
1466             serve(csp);
1467             _exit(0);
1468
1469          }
1470          else if (child_id > 0) /* parent */
1471          {
1472             /* in a fork()'d environment, the parent's
1473              * copy of the client socket and the CSP
1474              * are not used.
1475              */
1476
1477 #if !defined(_WIN32) && defined(__CYGWIN__)
1478             wait( NULL );
1479 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1480             close_socket(csp->cfd);
1481             csp->active = 0;
1482          }
1483 #endif
1484
1485 #undef SELECTED_ONE_OPTION
1486 /* end of cpp switch () */
1487
1488          if (child_id < 0) /* failed */
1489          {
1490             char buf[BUFFER_SIZE];
1491
1492             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1493
1494             sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1495
1496             write_socket(csp->cfd, buf, strlen(buf));
1497             close_socket(csp->cfd);
1498             csp->active = 0;
1499             sleep(5);
1500             continue;
1501          }
1502       }
1503       else
1504       {
1505          serve(csp);
1506       }
1507    }
1508    /* NOTREACHED */
1509
1510 }
1511
1512
1513 /*
1514   Local Variables:
1515   tab-width: 3
1516   end:
1517 */