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