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