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