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