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