- Added LOG_LEVEL_DEANIMATE
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.22 2001/06/29 21:45:41 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
5  *
6  * Purpose     :  Main file.  Contains main() method, main loop, and 
7  *                the main connection-handling function.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
10  *                IJBSWA team.  http://ijbswa.sourceforge.net
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and 
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it 
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: jcc.c,v $
36  *    Revision 1.22  2001/06/29 21:45:41  oes
37  *    Indentation, CRLF->LF, Tab-> Space
38  *
39  *    Revision 1.21  2001/06/29 13:29:36  oes
40  *    - Cleaned up, improved comments
41  *    - Unified all possible interceptors (CGI,
42  *      block, trust, fast_redirect) in one
43  *      place, with one (CGI) answer generation
44  *      mechansim. Much clearer now.
45  *    - Removed the GIF image generation, which
46  *      is now done in filters.c:block_url()
47  *    - Made error conditions like domain lookup
48  *      failiure or (various) problems while talking
49  *      to the server use cgi.c:error_response()
50  *      instead of generating HTML/HTTP in chat() (yuck!)
51  *    - Removed logentry from cancelled commit
52  *
53  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
54  *    Changing BUFSIZ ==> BUFFER_SIZE
55  *
56  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
57  *    Replacing function pointer in struct gateway with a directly
58  *    called function forwarded_connect().
59  *    Replacing struct gateway with struct forward_spec
60  *
61  *    Revision 1.18  2001/06/03 19:12:16  oes
62  *    introduced new cgi handling
63  *
64  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
65  *    Now uses action +image-blocker{} rather than config->tinygif
66  *
67  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
68  *    Replaced "list_share" with "list" - the tiny memory gain was not
69  *    worth the extra complexity.
70  *
71  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
72  *    Changed "permission" to "action" throughout.
73  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
74  *    Moved vanilla wafer check into chat(), since we must now
75  *    decide whether or not to add it based on the URL.
76  *
77  *    Revision 1.14  2001/05/29 20:14:01  joergs
78  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
79  *    increased.
80  *
81  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
82  *    Unified blocklist/imagelist/permissionslist.
83  *    File format is still under discussion, but the internal changes
84  *    are (mostly) done.
85  *
86  *    Also modified interceptor behaviour:
87  *    - We now intercept all URLs beginning with one of the following
88  *      prefixes (and *only* these prefixes):
89  *        * http://i.j.b/
90  *        * http://ijbswa.sf.net/config/
91  *        * http://ijbswa.sourceforge.net/config/
92  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
93  *    - Internal changes so that intercepted and fast redirect pages
94  *      are not replaced with an image.
95  *    - Interceptors now have the option to send a binary page direct
96  *      to the client. (i.e. ijb-send-banner uses this)
97  *    - Implemented show-url-info interceptor.  (Which is why I needed
98  *      the above interceptors changes - a typical URL is
99  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
100  *      The previous mechanism would not have intercepted that, and
101  *      if it had been intercepted then it then it would have replaced
102  *      it with an image.)
103  *
104  *    Revision 1.12  2001/05/27 22:17:04  oes
105  *
106  *    - re_process_buffer no longer writes the modified buffer
107  *      to the client, which was very ugly. It now returns the
108  *      buffer, which it is then written by chat.
109  *
110  *    - content_length now adjusts the Content-Length: header
111  *      for modified documents rather than crunch()ing it.
112  *      (Length info in csp->content_length, which is 0 for
113  *      unmodified documents)
114  *
115  *    - For this to work, sed() is called twice when filtering.
116  *
117  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
118  *    Added support for CLF and fixed LOG_LEVEL_LOG.
119  *    Also did CRLF->LF fix of my previous patch.
120  *
121  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
122  *    ACL feature now provides more security by immediately dropping
123  *    connections from untrusted hosts.
124  *
125  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
126  *    Automatic reloading of config file.
127  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
128  *    Most of the global variables have been moved to a new
129  *    struct configuration_spec, accessed through csp->config->globalname
130  *    Most of the globals remaining are used by the Win32 GUI.
131  *
132  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
133  *    Fixing minor memory leak and buffer overflow.
134  *
135  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
136  *    Hard tabs->Spaces
137  *
138  *    Revision 1.6  2001/05/23 00:13:58  joergs
139  *    AmigaOS support fixed.
140  *
141  *    Revision 1.5  2001/05/22 18:46:04  oes
142  *
143  *    - Enabled filtering banners by size rather than URL
144  *      by adding patterns that replace all standard banner
145  *      sizes with the "Junkbuster" gif to the re_filterfile
146  *
147  *    - Enabled filtering WebBugs by providing a pattern
148  *      which kills all 1x1 images
149  *
150  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
151  *      which is selected by the (nonstandard and therefore
152  *      capital) letter 'U' in the option string.
153  *      It causes the quantifiers to be ungreedy by default.
154  *      Appending a ? turns back to greedy (!).
155  *
156  *    - Added a new interceptor ijb-send-banner, which
157  *      sends back the "Junkbuster" gif. Without imagelist or
158  *      MSIE detection support, or if tinygif = 1, or the
159  *      URL isn't recognized as an imageurl, a lame HTML
160  *      explanation is sent instead.
161  *
162  *    - Added new feature, which permits blocking remote
163  *      script redirects and firing back a local redirect
164  *      to the browser.
165  *      The feature is conditionally compiled, i.e. it
166  *      can be disabled with --disable-fast-redirects,
167  *      plus it must be activated by a "fast-redirects"
168  *      line in the config file, has its own log level
169  *      and of course wants to be displayed by show-proxy-args
170  *      Note: Boy, all the #ifdefs in 1001 locations and
171  *      all the fumbling with configure.in and acconfig.h
172  *      were *way* more work than the feature itself :-(
173  *
174  *    - Because a generic redirect template was needed for
175  *      this, tinygif = 3 now uses the same.
176  *
177  *    - Moved GIFs, and other static HTTP response templates
178  *      to project.h
179  *
180  *    - Some minor fixes
181  *
182  *    - Removed some >400 CRs again (Jon, you really worked
183  *      a lot! ;-)
184  *
185  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
186  *    Made failure to bind() a fatal error.
187  *
188  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
189  *    Version 2.9.4 checkin.
190  *    - Merged popupfile and cookiefile, and added control over PCRS
191  *      filtering, in new "permissionsfile".
192  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
193  *      file error you now get a message box (in the Win32 GUI) rather
194  *      than the program exiting with no explanation.
195  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
196  *      skipping.
197  *    - Removed tabs from "config"
198  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
199  *    - Bumped up version number.
200  *
201  *    Revision 1.2  2001/05/17 22:34:44  oes
202  *     - Added hint on GIF char array generation to jcc.c
203  *     - Cleaned CRLF's from the sources and related files
204  *     - Repaired logging for REF and FRC
205  *
206  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
207  *    Initial import of version 2.9.3 source tree
208  *
209  *
210  *********************************************************************/
211 \f
212
213 #include "config.h"
214
215 #include <stdio.h>
216 #include <sys/types.h>
217 #include <stdlib.h>
218 #include <string.h>
219 #include <signal.h>
220 #include <fcntl.h>
221 #include <errno.h>
222
223 #ifdef _WIN32
224
225 # include <sys/timeb.h>
226 # include <windows.h>
227 # include <io.h>
228 # include <process.h>
229 # ifdef TOGGLE
230 #  include <time.h>
231 # endif /* def TOGGLE */
232
233 # include "win32.h"
234 # ifndef _WIN_CONSOLE
235 #  include "w32log.h"
236 # endif /* ndef _WIN_CONSOLE */
237
238 #else /* ifndef _WIN32 */
239
240 # include <unistd.h>
241 # include <sys/time.h>
242 # include <sys/wait.h>
243 # include <sys/stat.h>
244 # include <signal.h>
245
246 # ifdef __BEOS__
247 #  include <socket.h>  /* BeOS has select() for sockets only. */
248 #  include <OS.h>      /* declarations for threads and stuff. */
249 # endif
250
251 # ifndef FD_ZERO
252 #  include <select.h>
253 # endif
254
255 #endif
256
257 #include "project.h"
258 #include "list.h"
259 #include "jcc.h"
260 #include "filters.h"
261 #include "loaders.h"
262 #include "showargs.h"
263 #include "parsers.h"
264 #include "killpopup.h"
265 #include "miscutil.h"
266 #include "errlog.h"
267 #include "jbsockets.h"
268 #include "gateway.h"
269 #include "actions.h"
270 #include "cgi.h"
271
272 const char jcc_h_rcs[] = JCC_H_VERSION;
273 const char project_h_rcs[] = PROJECT_H_VERSION;
274
275 struct client_state  clients[1];
276 struct file_list     files[1];
277
278 #ifdef STATISTICS
279 int urls_read     = 0;     /* total nr of urls read inc rejected */
280 int urls_rejected = 0;     /* total nr of urls rejected */
281 #endif /* def STATISTICS */
282
283
284 static void listen_loop(void);
285 static void chat(struct client_state *csp);
286 #ifdef AMIGA
287 void serve(struct client_state *csp);
288 #else /* ifndef AMIGA */
289 static void serve(struct client_state *csp);
290 #endif /* def AMIGA */
291
292 #ifdef __BEOS__
293 static int32 server_thread(void *data);
294 #endif /* def __BEOS__ */
295
296 #ifdef _WIN32
297 #define sleep(N)  Sleep(((N) * 1000))
298 #endif
299
300
301 /* The vanilla wafer. */
302 static const char VANILLA_WAFER[] =
303    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
304    "Do_not_send_me_any_copyrighted_information_other_than_the_"
305    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
306    "In_particular_do_not_send_me_any_cookies_that_"
307    "are_subject_to_a_claim_of_copyright_by_anybody._"
308    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
309    "(copyright_or_otherwise)_applying_to_any_cookie._";
310
311
312 /*********************************************************************
313  *
314  * Function    :  chat
315  *
316  * Description :  Once a connection to the client has been accepted,
317  *                this function is called (via serve()) to handle the
318  *                main business of the communication.  When this 
319  *                function returns, the caller must close the client
320  *                socket handle.
321  *
322  * Parameters  :
323  *          1  :  csp = Current client state (buffers, headers, etc...)
324  *
325  * Returns     :  On success, the number of bytes written are returned (zero
326  *                indicates nothing was written).  On error, -1 is returned,
327  *                and errno is set appropriately.  If count is zero and the
328  *                file descriptor refers to a regular file, 0 will be
329  *                returned without causing any other effect.  For a special
330  *                file, the results are not portable.
331  *
332  *********************************************************************/
333 static void chat(struct client_state *csp)
334 {
335 /*
336  * This next lines are a little ugly, but they simplifies the if statements below.
337  * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
338  * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
339  */
340 #ifdef TOGGLE
341 #   define IS_TOGGLED_ON_AND (csp->toggled_on) &&
342 #else /* ifndef TOGGLE */
343 #   define IS_TOGGLED_ON_AND
344 #endif /* ndef TOGGLE */
345 #ifdef FORCE_LOAD
346 #   define IS_NOT_FORCED_AND (!csp->force) && 
347 #else /* ifndef FORCE_LOAD */
348 #   define IS_NOT_FORCED_AND
349 #endif /* def FORCE_LOAD */
350
351 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
352
353    char buf[BUFFER_SIZE];
354    char *hdr, *p, *req;
355    char *err = NULL;
356    fd_set rfds;
357    int n, maxfd, server_body;
358    int ms_iis5_hack = 0;
359    int byte_count = 0;
360    const struct forward_spec * fwd;
361    struct http_request *http;
362 #ifdef KILLPOPUPS
363    int block_popups;         /* bool, 1==will block popups */
364    int block_popups_now = 0; /* bool, 1==currently blocking popups */
365 #endif /* def KILLPOPUPS */
366 #ifdef PCRS
367    int pcrs_filter;   /* bool, 1==will filter through pcrs */
368    int filtering = 0; /* bool, 1==currently filtering through pcrs */
369 #endif /* def PCRS */
370    struct http_response *rsp;
371
372    http = csp->http;
373
374    /*
375     * Read the client's request.  Note that since we're not using select() we
376     * could get blocked here if a client connected, then didn't say anything!
377     */
378
379    while (FOREVER)
380    {
381       n = read_socket(csp->cfd, buf, sizeof(buf));
382
383       if (n <= 0) break;      /* error! */
384
385       add_to_iob(csp, buf, n);
386
387       req = get_header(csp);
388
389       if (req == NULL)
390       {
391          break;    /* no HTTP request! */
392       }
393
394       if (*req == '\0')
395       {
396          continue;   /* more to come! */
397       }
398  
399 #ifdef FORCE_LOAD
400       /* If this request contains the FORCE_PREFIX,
401        * better get rid of it now and set the force flag --oes
402        */
403
404       if (strstr(req, FORCE_PREFIX))
405       {
406          strclean(req, FORCE_PREFIX);
407          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
408          csp->force = 1;
409       } 
410       else
411       {
412          csp->force = 0;
413       }
414 #endif /* def FORCE_LOAD */
415   
416       parse_http_request(req, http, csp);
417       freez(req);
418       break;
419    }
420
421    if (http->cmd == NULL)
422    {
423       strcpy(buf, CHEADER);
424       write_socket(csp->cfd, buf, strlen(buf));
425
426       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
427
428       return;
429    }
430
431    /* decide how to route the HTTP request */
432
433    if ((fwd = forward_url(http, csp)) == NULL)
434    {
435       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
436       /* Never get here - LOG_LEVEL_FATAL causes program exit */
437    }
438
439    /* build the http request to send to the server
440     * we have to do one of the following:
441     *
442     * create = use the original HTTP request to create a new
443     *          HTTP request that has only the path component
444     *          without the http://domainspec
445     * pass   = pass the original HTTP request unchanged
446     *
447     * drop   = drop the HTTP request
448     *
449     * here's the matrix:
450     *                        SSL
451     *                    0        1
452     *                +--------+--------+
453     *                |        |        |
454     *             0  | create | drop   |
455     *                |        |        |
456     *  Forwarding    +--------+--------+
457     *                |        |        |
458     *             1  | pass   | pass   |
459     *                |        |        |
460     *                +--------+--------+
461     *
462     */
463
464    if (fwd->forward_host)
465    {
466       /* if forwarding, just pass the request as is */
467       enlist(csp->headers, http->cmd);
468    }
469    else
470    {
471       if (http->ssl == 0)
472       {
473          /* otherwise elide the host information from the url */
474          p = NULL;
475          p = strsav(p, http->gpc);
476          p = strsav(p, " ");
477          p = strsav(p, http->path);
478          p = strsav(p, " ");
479          p = strsav(p, http->ver);
480          enlist(csp->headers, p);
481          freez(p);
482       }
483    }
484
485    /* decide what we're to do with cookies */
486
487 #ifdef TOGGLE
488    if (!csp->toggled_on)
489    {
490       /* Most compatible set of actions (i.e. none) */
491       init_current_action(csp->action);
492    }
493    else
494 #endif /* ndef TOGGLE */
495    {
496       url_actions(http, csp);
497    }
498
499 #ifdef JAR_FILES
500    /*
501     * If we're logging cookies in a cookie jar, and the user has not
502     * supplied any wafers, and the user has not told us to suppress the
503     * vanilla wafer, then send the vanilla wafer.
504     */
505    if ((csp->config->jarfile != NULL)
506        && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
507        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
508    {
509       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
510    }
511 #endif /* def JAR_FILES */
512
513 #ifdef KILLPOPUPS
514    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
515 #endif /* def KILLPOPUPS */
516 #ifdef PCRS
517    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
518                                 ((csp->action->flags & ACTION_FILTER) != 0);
519 #endif /* def PCRS */
520
521
522    /* grab the rest of the client's headers */
523
524    while (FOREVER)
525    {
526       if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
527       {
528          n = read_socket(csp->cfd, buf, sizeof(buf));
529          if (n <= 0)
530          {
531             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
532             return;
533          }
534          add_to_iob(csp, buf, n);
535          continue;
536       }
537
538       if (p == NULL) break;
539
540       enlist(csp->headers, p);
541       freez(p);
542    }
543
544    /* We have a request. */
545
546    hdr = sed(client_patterns, add_client_headers, csp);
547    destroy_list(csp->headers);
548
549    /* 
550     * Now, check to see if we need to intercept it, i.e.
551     * If
552     */
553  
554    if (
555        /* a CGI call was detected and answered */
556          (NULL != (rsp = dispatch_cgi(csp))) 
557
558        /* or we are enabled and... */
559        || (IS_ENABLED_AND (
560
561             /* ..the request was blocked */
562             ( NULL != (rsp = block_url(csp)))
563
564           /* ..or untrusted */
565 #ifdef TRUST_FILES
566           || ( NULL != (rsp = trust_url(csp)))
567 #endif 
568
569           /* ..or a fast redirect kicked in */
570 #ifdef FAST_REDIRECTS
571           || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) && 
572                      (NULL != (rsp = redirect_url(csp))))
573 #endif /* def FAST_REDIRECTS */
574                  ))
575         )
576    {
577       /* Write the answer to the client */
578       if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
579              || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
580       { 
581          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
582       }
583
584 #ifdef STATISTICS
585       /* Count as a rejected request */
586       csp->rejected = 1;
587 #endif /* def STATISTICS */
588
589       /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
590       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
591       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd); 
592
593       /* Clean up and return */
594       free_http_response(rsp);
595       freez(hdr);
596       return;
597    }
598
599    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
600
601    if (fwd->forward_host)
602    {
603       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
604                fwd->forward_host, fwd->forward_port, http->hostport);
605    }
606    else
607    {
608       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
609    }
610
611    /* here we connect to the server, gateway, or the forwarder */
612
613    csp->sfd = forwarded_connect(fwd, http, csp);
614
615    if (csp->sfd < 0)
616    {
617       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
618                 http->hostport);
619
620       if (errno == EINVAL)
621       {
622            rsp = error_response(csp, "no-such-domain", errno);
623
624          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0", 
625                    csp->ip_addr_str, http->cmd);
626       }
627       else
628       {
629            rsp = error_response(csp, "connect-failed", errno);
630
631          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
632                    csp->ip_addr_str, http->cmd);
633       }
634
635       /* Write the answer to the client */
636       if(rsp)
637         {
638          if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
639                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
640          { 
641             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
642          }
643       }
644
645       free_http_response(rsp);
646       freez(hdr);
647       return;
648    }
649
650    log_error(LOG_LEVEL_CONNECT, "OK");
651
652    if (fwd->forward_host || (http->ssl == 0))
653    {
654       /* write the client's (modified) header to the server
655        * (along with anything else that may be in the buffer)
656        */
657
658       n = strlen(hdr);
659
660       if ((write_socket(csp->sfd, hdr, n) != n)
661           || (flush_socket(csp->sfd, csp   ) <  0))
662       {
663          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
664                     http->hostport);
665
666          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
667                    csp->ip_addr_str, http->cmd); 
668
669          rsp = error_response(csp, "connect-failed", errno);
670
671          if(rsp)
672          {
673             if ((write_socket(csp->cfd, rsp->head, n) != n)
674                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
675             { 
676                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
677             }
678          }
679
680          free_http_response(rsp);
681          freez(hdr);
682          return;
683       }
684    }
685    else
686    {
687       /*
688        * We're running an SSL tunnel and we're not forwarding,
689        * so just send the "connect succeeded" message to the
690        * client, flush the rest, and get out of the way.
691        */
692       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n", 
693                 csp->ip_addr_str, http->cmd); 
694
695       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
696       {
697          freez(hdr);
698          return;
699       }
700       IOB_RESET(csp);
701    }
702
703    /* we're finished with the client's header */
704    freez(hdr);
705
706    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
707
708    /* pass data between the client and server
709     * until one or the other shuts down the connection.
710     */
711
712    server_body = 0;
713
714    while (FOREVER)
715    {
716       FD_ZERO(&rfds);
717
718       FD_SET(csp->cfd, &rfds);
719       FD_SET(csp->sfd, &rfds);
720
721       n = select(maxfd+1, &rfds, NULL, NULL, NULL);
722
723       if (n < 0)
724       {
725          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
726          return;
727       }
728
729       /* this is the body of the browser's request
730        * just read it and write it.
731        */
732
733       if (FD_ISSET(csp->cfd, &rfds))
734       {
735          n = read_socket(csp->cfd, buf, sizeof(buf));
736
737          if (n <= 0)
738          {
739             break; /* "game over, man" */
740          }
741
742          if (write_socket(csp->sfd, buf, n) != n)
743          {
744             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
745             return;
746          }
747          continue;
748       }
749
750       /*
751        * The server wants to talk.  It could be the header or the body.
752        * If `hdr' is null, then it's the header otherwise it's the body.
753        * FIXME: Does `hdr' really mean `host'?
754        */
755
756
757       if (FD_ISSET(csp->sfd, &rfds))
758       {
759          fflush( 0 );
760          n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
761
762          if (n < 0)
763          {
764             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
765
766             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
767                       csp->ip_addr_str, http->cmd); 
768
769             rsp = error_response(csp, "connect-failed", errno);
770
771             if(rsp)
772             {
773                if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
774                     || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
775                { 
776                   log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
777                            }
778                         }
779
780             free_http_response(rsp);
781             return;
782          }
783
784          /* Add a trailing zero.  This lets filter_popups
785           * use string operations.
786           */
787          buf[n] = '\0';
788
789 #ifdef KILLPOPUPS
790          /* Filter the popups on this read. */
791          if (block_popups_now)
792          {
793             filter_popups(buf, n);
794          }
795 #endif /* def KILLPOPUPS */
796
797          /* Normally, this would indicate that we've read
798           * as much as the server has sent us and we can
799           * close the client connection.  However, Microsoft
800           * in its wisdom has released IIS/5 with a bug that
801           * prevents it from sending the trailing \r\n in
802           * a 302 redirect header (and possibly other headers).
803           * To work around this if we've haven't parsed
804           * a full header we'll append a trailing \r\n
805           * and see if this now generates a valid one.
806           *
807           * This hack shouldn't have any impacts.  If we've
808           * already transmitted the header or if this is a
809           * SSL connection, then we won't bother with this
810           * hack.  So we only work on partially received
811           * headers.  If we append a \r\n and this still
812           * doesn't generate a valid header, then we won't
813           * transmit anything to the client.
814           */
815          if (n == 0)
816          {
817             /* This hack must only be enforced for headers. */
818             if (server_body || http->ssl)
819             {
820 #ifdef PCRS
821                if (filtering)
822                {
823                   p = re_process_buffer(csp);
824                   hdr = sed(server_patterns, add_server_headers, csp);
825                   n = strlen(hdr);
826                   if ((write_socket(csp->cfd, hdr, n) != n)
827                       || (write_socket(csp->cfd, p, csp->content_length) != csp->content_length))
828                   {
829                      log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
830                      return;
831                   }
832                freez(hdr);
833                freez(p);
834                }
835 #endif /* def PCRS */
836                break; /* "game over, man" */
837             }
838
839             /* Let's pretend the server just sent us a blank line. */
840             n = sprintf(buf, "\r\n");
841
842             /*
843              * Now, let the normal header parsing algorithm below do its
844              * job.  If it fails, we'll exit instead of continuing.
845              */
846
847             ms_iis5_hack = 1;
848          }
849
850          /*
851           * If this is an SSL connection or we're in the body
852           * of the server document, just write it to the client.
853           */
854
855          if (server_body || http->ssl)
856          {
857 #ifdef PCRS
858             if (filtering)
859             {
860                add_to_iob(csp, buf, n); /* Buffer the body for filtering */
861             }
862             else
863 #endif /* def PCRS */
864             {
865                /* just write */
866                if (write_socket(csp->cfd, buf, n) != n)
867                {
868                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
869                   return;
870                }
871             }
872             byte_count += n;
873             continue;
874          }
875          else
876          {
877             /* we're still looking for the end of the
878              * server's header ... (does that make header
879              * parsing an "out of body experience" ?
880              */
881
882             /* buffer up the data we just read */
883             add_to_iob(csp, buf, n);
884
885             /* get header lines from the iob */
886
887             while ((p = get_header(csp)))
888             {
889                if (*p == '\0')
890                {
891                   /* see following note */
892                   break;
893                }
894                enlist(csp->headers, p);
895                freez(p);
896             }
897
898             /* NOTE: there are no "empty" headers so
899              * if the pointer `p' is not NULL we must
900              * assume that we reached the end of the
901              * buffer before we hit the end of the header.
902              */
903
904             if (p)
905             {
906                if (ms_iis5_hack)
907                {
908                   /* Well, we tried our MS IIS/5
909                    * hack and it didn't work.
910                    * The header is incomplete
911                    * and there isn't anything
912                    * we can do about it.
913                    */
914                   break;
915                }
916                else
917                {
918                   /* Since we have to wait for
919                    * more from the server before
920                    * we can parse the headers
921                    * we just continue here.
922                    */
923                   continue;
924                }
925             }
926
927             /* we have now received the entire header.
928              * filter it and send the result to the client
929              */
930
931             hdr = sed(server_patterns, add_server_headers, csp);
932             n   = strlen(hdr);
933
934             /* write the server's (modified) header to
935              * the client (along with anything else that
936              * may be in the buffer)
937              */
938
939 #ifdef KILLPOPUPS
940             /* Start blocking popups if appropriate. */
941
942             if (csp->is_text  &&  /* It's a text / * MIME-Type */
943                 !http->ssl    &&  /* We talk plaintext */
944                 block_popups)     /* Policy allows */
945             {
946                block_popups_now = 1;
947             }
948
949 #endif /* def KILLPOPUPS */
950
951 #ifdef PCRS
952             /* Start re_filtering this if appropriate. */
953
954             if (csp->is_text  &&  /* It's a text / * MIME-Type */
955                 !http->ssl    &&  /* We talk plaintext */
956                 pcrs_filter)      /* Policy allows */
957             {
958                filtering = 1;
959             }
960
961 /* This next line is a little ugly, but it simplifies the if statement below. */
962 /* Basically if using PCRS, we want the OR condition to require "!filtering"  */
963 #define NOT_FILTERING_AND !filtering &&
964
965 #else /* not def PCRS */
966
967 #define NOT_FILTERING_AND
968
969 #endif /* def PCRS */
970
971             if (NOT_FILTERING_AND ((write_socket(csp->cfd, hdr, n) != n)
972                 || (n = flush_socket(csp->cfd, csp) < 0)))
973             {
974                log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
975
976                /* the write failed, so don't bother
977                 * mentioning it to the client...
978                 * it probably can't hear us anyway.
979                 */
980                freez(hdr);
981                return;
982             }
983
984             NOT_FILTERING_AND (byte_count += n);
985
986             /* we're finished with the server's header */
987
988             freez(hdr);
989             server_body = 1;
990
991             /* If this was a MS IIS/5 hack then it means
992              * the server has already closed the
993              * connection.  Nothing more to read.  Time
994              * to bail.
995              */
996             if (ms_iis5_hack)
997             {
998                break;
999             }
1000          }
1001          continue;
1002       }
1003
1004       return; /* huh? we should never get here */
1005    }
1006
1007    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d", 
1008              csp->ip_addr_str, http->cmd, byte_count); 
1009 }
1010
1011
1012 /*********************************************************************
1013  *
1014  * Function    :  serve
1015  *
1016  * Description :  This is little more than chat.  We only "serve" to
1017  *                to close any socket that chat may have opened.
1018  *
1019  * Parameters  :
1020  *          1  :  csp = Current client state (buffers, headers, etc...)
1021  *
1022  * Returns     :  N/A
1023  *
1024  *********************************************************************/
1025 #ifdef AMIGA
1026 void serve(struct client_state *csp)
1027 #else /* ifndef AMIGA */
1028 static void serve(struct client_state *csp)
1029 #endif /* def AMIGA */
1030 {
1031    chat(csp);
1032    close_socket(csp->cfd);
1033
1034    if (csp->sfd >= 0)
1035    {
1036       close_socket(csp->sfd);
1037    }
1038
1039    csp->active = 0;
1040
1041 }
1042
1043
1044 #ifdef __BEOS__
1045 /*********************************************************************
1046  *
1047  * Function    :  server_thread
1048  *
1049  * Description :  We only exist to call `serve' in a threaded environment.
1050  *
1051  * Parameters  :
1052  *          1  :  data = Current client state (buffers, headers, etc...)
1053  *
1054  * Returns     :  Always 0.
1055  *
1056  *********************************************************************/
1057 static int32 server_thread(void *data)
1058 {
1059    serve((struct client_state *) data);
1060    return 0;
1061
1062 }
1063 #endif
1064
1065
1066 /*********************************************************************
1067  *
1068  * Function    :  main
1069  *
1070  * Description :  Load the config file and start the listen loop.
1071  *                This function is a lot more *sane* with the `load_config'
1072  *                and `listen_loop' functions; although it stills does
1073  *                a *little* too much for my taste.
1074  *
1075  * Parameters  :
1076  *          1  :  argc = Number of parameters (including $0).
1077  *          2  :  argv = Array of (char *)'s to the parameters.
1078  *
1079  * Returns     :  1 if : can't open config file, unrecognized directive,
1080  *                stats requested in multi-thread mode, can't open the
1081  *                log file, can't open the jar file, listen port is invalid,
1082  *                any load fails, and can't bind port.
1083  *
1084  *                Else main never returns, the process must be signaled
1085  *                to terminate execution.  Or, on Windows, use the 
1086  *                "File", "Exit" menu option.
1087  *
1088  *********************************************************************/
1089 #ifdef __MINGW32__
1090 int _main(int argc, const char *argv[])
1091 #else
1092 int main(int argc, const char *argv[])
1093 #endif
1094 {
1095    configfile =
1096 #ifdef AMIGA
1097    "AmiTCP:db/junkbuster/config"
1098 #elif !defined(_WIN32)
1099    "config"
1100 #else
1101    "junkbstr.txt"
1102 #endif
1103       ;
1104
1105 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1106    if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1107    {
1108       printf("JunkBuster proxy version " VERSION ".\n\n"
1109          "Usage: %s [configfile]\n\n"
1110          "See " HOME_PAGE_URL " for details.\n"
1111          "This program is distributed under the GNU GPL, version 2 or later.\n",
1112          argv[0]);
1113       exit(2);
1114    }
1115    if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1116    {
1117       printf(VERSION "\n");
1118       exit(2);
1119    }
1120 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1121
1122    Argc = argc;
1123    Argv = argv;
1124
1125    if (argc > 1)
1126    {
1127       configfile = argv[1];
1128    }
1129
1130    files->next = NULL;
1131
1132 #ifdef AMIGA
1133    InitAmiga();
1134 #elif defined(_WIN32)
1135    InitWin32();
1136 #endif
1137
1138
1139 #ifndef _WIN32
1140    signal(SIGPIPE, SIG_IGN);
1141    signal(SIGCHLD, SIG_IGN);
1142
1143 #else /* ifdef _WIN32 */
1144 # ifdef _WIN_CONSOLE
1145    /*
1146     * We *are* in a windows console app.
1147     * Print a verbose messages about FAQ's and such
1148     */
1149    printf(win32_blurb);
1150 # endif /* def _WIN_CONSOLE */
1151 #endif /* def _WIN32 */
1152
1153
1154    listen_loop();
1155
1156    /* NOTREACHED */
1157    return(-1);
1158
1159 }
1160
1161
1162 /*********************************************************************
1163  *
1164  * Function    :  listen_loop
1165  *
1166  * Description :  bind the listen port and enter a "FOREVER" listening loop.
1167  *
1168  * Parameters  :  N/A
1169  *
1170  * Returns     :  Never.
1171  *
1172  *********************************************************************/
1173 static void listen_loop(void)
1174 {
1175    struct client_state *csp = NULL;
1176    int bfd;
1177    struct configuration_spec * config;
1178
1179    config = load_config();
1180
1181    log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1182              config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1183
1184    bfd = bind_port(config->haddr, config->hport);
1185
1186    if (bfd < 0)
1187    {
1188       log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1189          "- There may be another junkbuster or some other "
1190          "proxy running on port %d", 
1191          (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1192          config->hport, config->hport
1193       );
1194       /* shouldn't get here */
1195       return;
1196    }
1197
1198    config->need_bind = 0;
1199
1200
1201    while (FOREVER)
1202    {
1203 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1204       while (waitpid(-1, NULL, WNOHANG) > 0)
1205       {
1206          /* zombie children */
1207       }
1208 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1209       sweep();
1210
1211       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1212       {
1213          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1214          continue;
1215       }
1216
1217       memset(csp, '\0', sizeof(*csp));
1218
1219       csp->active = 1;
1220       csp->sfd    = -1;
1221
1222       csp->config = config = load_config();
1223
1224       if ( config->need_bind )
1225       {
1226          /*
1227           * Since we were listening to the "old port", we will not see
1228           * a "listen" param change until the next IJB request.  So, at
1229           * least 1 more request must be made for us to find the new
1230           * setting.  I am simply closing the old socket and binding the
1231           * new one.
1232           *
1233           * Which-ever is correct, we will serve 1 more page via the
1234           * old settings.  This should probably be a "show-proxy-args"
1235           * request.  This should not be a so common of an operation
1236           * that this will hurt people's feelings.
1237           */
1238
1239          close_socket(bfd);
1240
1241          log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1242                    config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1243          bfd = bind_port(config->haddr, config->hport);
1244
1245          if (bfd < 0)
1246          {
1247             log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1248                "- There may be another junkbuster or some other "
1249                "proxy running on port %d", 
1250                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1251                config->hport, config->hport
1252             );
1253             /* shouldn't get here */
1254             return;
1255          }
1256
1257          config->need_bind = 0;
1258       }
1259
1260       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1261
1262       if (!accept_connection(csp, bfd))
1263       {
1264          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1265
1266 #ifdef AMIGA
1267          if(!childs)
1268          {
1269             exit(1); 
1270          }
1271 #endif
1272          freez(csp);
1273          continue;
1274       }
1275       else
1276       {
1277          log_error(LOG_LEVEL_CONNECT, "OK");
1278       }
1279
1280 #if defined(TOGGLE)
1281       /* by haroon - most of credit to srt19170 */
1282       csp->toggled_on = g_bToggleIJB;
1283 #endif
1284
1285       if (run_loader(csp))
1286       {
1287          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1288          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1289       }
1290
1291 #ifdef ACL_FILES
1292       if (block_acl(NULL,csp))
1293       {
1294          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1295          close_socket(csp->cfd);
1296          freez(csp);
1297          continue;
1298       }
1299 #endif /* def ACL_FILES */
1300
1301       /* add it to the list of clients */
1302       csp->next = clients->next;
1303       clients->next = csp;
1304
1305       if (config->multi_threaded)
1306       {
1307          int child_id;
1308
1309 /* this is a switch () statment in the C preprocessor - ugh */
1310 #undef SELECTED_ONE_OPTION
1311
1312 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1313 #define SELECTED_ONE_OPTION
1314          child_id = _beginthread(
1315             (void*)serve,
1316             64 * 1024,
1317             csp);
1318 #endif
1319
1320 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1321 #define SELECTED_ONE_OPTION
1322          {
1323             thread_id tid = spawn_thread
1324                (server_thread, "server", B_NORMAL_PRIORITY, csp);
1325
1326             if ((tid >= 0) && (resume_thread(tid) == B_OK))
1327             {
1328                child_id = (int) tid;
1329             }
1330             else
1331             {
1332                child_id = -1;
1333             }
1334          }
1335 #endif
1336
1337 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1338 #define SELECTED_ONE_OPTION
1339          csp->cfd = ReleaseSocket(csp->cfd, -1);
1340          if((child_id = (int)CreateNewProcTags(
1341             NP_Entry, (ULONG)server_thread,
1342             NP_Output, Output(),
1343             NP_CloseOutput, FALSE,
1344             NP_Name, (ULONG)"junkbuster child",
1345             NP_StackSize, 200*1024,
1346             TAG_DONE)))
1347          {
1348             childs++;
1349             ((struct Task *)child_id)->tc_UserData = csp;
1350             Signal((struct Task *)child_id, SIGF_SINGLE);
1351             Wait(SIGF_SINGLE);
1352          }
1353 #endif
1354
1355 #if !defined(SELECTED_ONE_OPTION)
1356          child_id = fork();
1357 #endif
1358
1359 #undef SELECTED_ONE_OPTION
1360 /* end of cpp switch () */
1361
1362          if (child_id < 0) /* failed */
1363          {
1364             char buf[BUFFER_SIZE];
1365
1366             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1367
1368             sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1369
1370             write_socket(csp->cfd, buf, strlen(buf));
1371             close_socket(csp->cfd);
1372             csp->active = 0;
1373             sleep(5);
1374             continue;
1375          }
1376
1377 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1378          /* This block is only needed when using fork().
1379           * When using threads, the server thread was
1380           * created and run by the call to _beginthread().
1381           */
1382          if (child_id == 0)   /* child */
1383          {
1384             serve(csp);
1385             _exit(0);
1386
1387          }
1388          else  /* parent */
1389          {
1390             /* in a fork()'d environment, the parent's
1391              * copy of the client socket and the CSP
1392              * are not used.
1393              */
1394
1395 #if !defined(_WIN32) && defined(__CYGWIN__)
1396             wait( NULL );
1397 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1398             close_socket(csp->cfd);
1399             csp->active = 0;
1400          }
1401 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1402       }
1403       else
1404       {
1405          serve(csp);
1406       }
1407    }
1408    /* NOTREACHED */
1409
1410 }
1411
1412
1413 /*
1414   Local Variables:
1415   tab-width: 3
1416   end:
1417 */