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