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