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