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