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