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