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