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