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