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