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