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