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