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