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