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