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