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