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