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