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