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