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