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