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