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