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