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