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