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