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