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