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