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