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