If we decided not to keep the connection to the server alive, but have a reusable...
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.260 2009/07/05 12:00:09 fabiankeil 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-2009 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
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  *********************************************************************/
35
36
37 #include "config.h"
38
39 #include <stdio.h>
40 #include <sys/types.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <signal.h>
44 #include <fcntl.h>
45 #include <errno.h>
46 #include <assert.h>
47
48 #ifdef _WIN32
49 # ifndef FEATURE_PTHREAD
50 #  ifndef STRICT
51 #   define STRICT
52 #  endif
53 #  include <windows.h>
54 #  include <process.h>
55 # endif /* ndef FEATURE_PTHREAD */
56
57 # include "win32.h"
58 # ifndef _WIN_CONSOLE
59 #  include "w32log.h"
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
62
63 #else /* ifndef _WIN32 */
64
65 # if !defined (__OS2__)
66 # include <unistd.h>
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
72
73 #ifdef sun
74 #include <sys/termios.h>
75 #endif /* sun */
76
77 #ifdef unix
78 #include <pwd.h>
79 #include <grp.h>
80 #endif
81
82 # include <signal.h>
83
84 # ifdef __BEOS__
85 #  include <socket.h>  /* BeOS has select() for sockets only. */
86 #  include <OS.h>      /* declarations for threads and stuff. */
87 # endif
88
89 # if defined(__EMX__) || defined(__OS2__)
90 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
91 # endif
92 # ifdef __OS2__
93 #define INCL_DOS
94 # include <os2.h>
95 #define bzero(B,N) memset(B,0x00,n)
96 # endif
97
98 # ifndef FD_ZERO
99 #  include <select.h>
100 # endif
101
102 #endif
103
104 #include "project.h"
105 #include "list.h"
106 #include "jcc.h"
107 #include "filters.h"
108 #include "loaders.h"
109 #include "parsers.h"
110 #include "miscutil.h"
111 #include "errlog.h"
112 #include "jbsockets.h"
113 #include "gateway.h"
114 #include "actions.h"
115 #include "cgi.h"
116 #include "loadcfg.h"
117 #include "urlmatch.h"
118
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
121
122 int no_daemon = 0;
123 struct client_state  clients[1];
124 struct file_list     files[1];
125
126 #ifdef FEATURE_STATISTICS
127 int urls_read     = 0;     /* total nr of urls read inc rejected */
128 int urls_rejected = 0;     /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
130
131 #ifdef FEATURE_GRACEFUL_TERMINATION
132 int g_terminate = 0;
133 #endif
134
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
137 #endif
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
152 #endif
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(struct configuration_spec *config);
155 static void listen_loop(void);
156
157 #ifdef AMIGA
158 void serve(struct client_state *csp);
159 #else /* ifndef AMIGA */
160 static void serve(struct client_state *csp);
161 #endif /* def AMIGA */
162
163 #ifdef __BEOS__
164 static int32 server_thread(void *data);
165 #endif /* def __BEOS__ */
166
167 #ifdef _WIN32
168 #define sleep(N)  Sleep(((N) * 1000))
169 #endif
170
171 #ifdef __OS2__
172 #define sleep(N)  DosSleep(((N) * 100))
173 #endif
174
175 #ifdef MUTEX_LOCKS_AVAILABLE
176 /*
177  * XXX: Does the locking stuff really belong in this file?
178  */
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
182
183 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
184 privoxy_mutex_t resolver_mutex;
185 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
186
187 #ifndef HAVE_GMTIME_R
188 privoxy_mutex_t gmtime_mutex;
189 #endif /* ndef HAVE_GMTIME_R */
190
191 #ifndef HAVE_LOCALTIME_R
192 privoxy_mutex_t localtime_mutex;
193 #endif /* ndef HAVE_GMTIME_R */
194
195 #ifndef HAVE_RANDOM
196 privoxy_mutex_t rand_mutex;
197 #endif /* ndef HAVE_RANDOM */
198
199 #endif /* def MUTEX_LOCKS_AVAILABLE */
200
201 #if defined(unix)
202 const char *basedir = NULL;
203 const char *pidfile = NULL;
204 static int received_hup_signal = 0;
205 #endif /* defined unix */
206
207 /* HTTP snipplets. */
208 static const char CSUCCEED[] =
209    "HTTP/1.0 200 Connection established\r\n"
210    "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
211
212 static const char CHEADER[] =
213    "HTTP/1.0 400 Invalid header received from client\r\n"
214    "Proxy-Agent: Privoxy " VERSION "\r\n"
215    "Content-Type: text/plain\r\n"
216    "Connection: close\r\n\r\n"
217    "Invalid header received from client.\r\n";
218
219 static const char FTP_RESPONSE[] =
220    "HTTP/1.0 400 Invalid request received from client\r\n"
221    "Content-Type: text/plain\r\n"
222    "Connection: close\r\n\r\n"
223    "Invalid request. Privoxy doesn't support FTP.\r\n";
224
225 static const char GOPHER_RESPONSE[] =
226    "HTTP/1.0 400 Invalid request received from client\r\n"
227    "Content-Type: text/plain\r\n"
228    "Connection: close\r\n\r\n"
229    "Invalid request. Privoxy doesn't support gopher.\r\n";
230
231 /* XXX: should be a template */
232 static const char MISSING_DESTINATION_RESPONSE[] =
233    "HTTP/1.0 400 Bad request received from client\r\n"
234    "Proxy-Agent: Privoxy " VERSION "\r\n"
235    "Content-Type: text/plain\r\n"
236    "Connection: close\r\n\r\n"
237    "Bad request. Privoxy was unable to extract the destination.\r\n";
238
239 /* XXX: should be a template */
240 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
241    "HTTP/1.0 502 Server or forwarder response invalid\r\n"
242    "Proxy-Agent: Privoxy " VERSION "\r\n"
243    "Content-Type: text/plain\r\n"
244    "Connection: close\r\n\r\n"
245    "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
246
247 #if 0
248 /* XXX: should be a template */
249 static const char NULL_BYTE_RESPONSE[] =
250    "HTTP/1.0 400 Bad request received from client\r\n"
251    "Proxy-Agent: Privoxy " VERSION "\r\n"
252    "Content-Type: text/plain\r\n"
253    "Connection: close\r\n\r\n"
254    "Bad request. Null byte(s) before end of request.\r\n";
255 #endif
256
257 /* XXX: should be a template */
258 static const char MESSED_UP_REQUEST_RESPONSE[] =
259    "HTTP/1.0 400 Malformed request after rewriting\r\n"
260    "Proxy-Agent: Privoxy " VERSION "\r\n"
261    "Content-Type: text/plain\r\n"
262    "Connection: close\r\n\r\n"
263    "Bad request. Messed up with header filters.\r\n";
264
265 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
266    "HTTP/1.0 503 Too many open connections\r\n"
267    "Proxy-Agent: Privoxy " VERSION "\r\n"
268    "Content-Type: text/plain\r\n"
269    "Connection: close\r\n\r\n"
270    "Maximum number of open connections reached.\r\n";
271
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273    "HTTP/1.0 504 Connection timeout\r\n"
274    "Proxy-Agent: Privoxy " VERSION "\r\n"
275    "Content-Type: text/plain\r\n"
276    "Connection: close\r\n\r\n"
277    "The connection timed out because the client request didn't arrive in time.\r\n";
278
279 /* A function to crunch a response */
280 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
281
282 /* Crunch function flags */
283 #define CF_NO_FLAGS        0
284 /* Cruncher applies to forced requests as well */
285 #define CF_IGNORE_FORCE    1
286 /* Crunched requests are counted for the block statistics */
287 #define CF_COUNT_AS_REJECT 2
288
289 /* A crunch function and its flags */
290 struct cruncher
291 {
292    const crunch_func_ptr cruncher;
293    const int flags;
294 };
295
296 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
297
298 /* Complete list of cruncher functions */
299 static const struct cruncher crunchers_all[] = {
300    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
301    { block_url,       CF_COUNT_AS_REJECT },
302 #ifdef FEATURE_TRUST
303    { trust_url,       CF_COUNT_AS_REJECT },
304 #endif /* def FEATURE_TRUST */
305    { redirect_url,    CF_NO_FLAGS  },
306    { dispatch_cgi,    CF_IGNORE_FORCE},
307    { NULL,            0 }
308 };
309
310 /* Light version, used after tags are applied */
311 static const struct cruncher crunchers_light[] = {
312    { block_url,       CF_COUNT_AS_REJECT },
313    { redirect_url,    CF_NO_FLAGS },
314    { NULL,            0 }
315 };
316
317
318 /*
319  * XXX: Don't we really mean
320  *
321  * #if defined(unix)
322  *
323  * here?
324  */
325 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
326 /*********************************************************************
327  *
328  * Function    :  sig_handler 
329  *
330  * Description :  Signal handler for different signals.
331  *                Exit gracefully on TERM and INT
332  *                or set a flag that will cause the errlog
333  *                to be reopened by the main thread on HUP.
334  *
335  * Parameters  :
336  *          1  :  the_signal = the signal cause this function to call
337  *
338  * Returns     :  - 
339  *
340  *********************************************************************/
341 static void sig_handler(int the_signal)
342 {
343    switch(the_signal)
344    {
345       case SIGTERM:
346       case SIGINT:
347          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
348 #if defined(unix)
349          if(pidfile)
350          {
351             unlink(pidfile);
352          }
353 #endif /* unix */
354          exit(the_signal);
355          break;
356
357       case SIGHUP:
358 #if defined(unix)
359          received_hup_signal = 1;
360 #endif
361          break;         
362
363       default:
364          /* 
365           * We shouldn't be here, unless we catch signals
366           * in main() that we can't handle here!
367           */
368          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
369    }
370    return;
371
372 }
373 #endif
374
375
376 /*********************************************************************
377  *
378  * Function    :  client_protocol_is_unsupported
379  *
380  * Description :  Checks if the client used a known unsupported
381  *                protocol and deals with it by sending an error
382  *                response.
383  *
384  * Parameters  :
385  *          1  :  csp = Current client state (buffers, headers, etc...)
386  *          2  :  req = the first request line send by the client
387  *
388  * Returns     :  TRUE if an error response has been generated, or
389  *                FALSE if the request doesn't look invalid.
390  *
391  *********************************************************************/
392 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
393 {
394    /*
395     * If it's a FTP or gopher request, we don't support it.
396     *
397     * These checks are better than nothing, but they might
398     * not work in all configurations and some clients might
399     * have problems digesting the answer.
400     *
401     * They should, however, never cause more problems than
402     * Privoxy's old behaviour (returning the misleading HTML
403     * error message:
404     *
405     * "Could not resolve http://(ftp|gopher)://example.org").
406     */
407    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
408    {
409       const char *response = NULL;
410       const char *protocol = NULL;
411
412       if (!strncmpic(req, "GET ftp://", 10))
413       {
414          response = FTP_RESPONSE;
415          protocol = "FTP";
416       }
417       else
418       {
419          response = GOPHER_RESPONSE;
420          protocol = "GOPHER";
421       }
422       log_error(LOG_LEVEL_ERROR,
423          "%s tried to use Privoxy as %s proxy: %s",
424          csp->ip_addr_str, protocol, req);
425       log_error(LOG_LEVEL_CLF,
426          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
427       freez(req);
428       write_socket(csp->cfd, response, strlen(response));
429
430       return TRUE;
431    }
432
433    return FALSE;
434 }
435
436
437 /*********************************************************************
438  *
439  * Function    :  get_request_destination_elsewhere
440  *
441  * Description :  If the client's request was redirected into
442  *                Privoxy without the client's knowledge,
443  *                the request line lacks the destination host.
444  *
445  *                This function tries to get it elsewhere,
446  *                provided accept-intercepted-requests is enabled.
447  *
448  *                "Elsewhere" currently only means "Host: header",
449  *                but in the future we may ask the redirecting
450  *                packet filter to look the destination up.
451  *
452  *                If the destination stays unknown, an error
453  *                response is send to the client and headers
454  *                are freed so that chat() can return directly.
455  *
456  * Parameters  :
457  *          1  :  csp = Current client state (buffers, headers, etc...)
458  *          2  :  headers = a header list
459  *
460  * Returns     :  JB_ERR_OK if the destination is now known, or
461  *                JB_ERR_PARSE if it isn't.
462  *
463  *********************************************************************/
464 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
465 {
466    char *req;
467
468    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
469    {
470       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
471          " Privoxy isn't configured to accept intercepted requests.",
472          csp->ip_addr_str, csp->http->cmd);
473       /* XXX: Use correct size */
474       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
475          csp->ip_addr_str, csp->http->cmd);
476
477       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
478       destroy_list(headers);
479
480       return JB_ERR_PARSE;
481    }
482    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
483    {
484 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
485       /* Split the domain we just got for pattern matching */
486       init_domain_components(csp->http);
487 #endif
488
489       return JB_ERR_OK;
490    }
491    else
492    {
493       /* We can't work without destination. Go spread the news.*/
494
495       req = list_to_text(headers);
496       chomp(req);
497       /* XXX: Use correct size */
498       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
499          csp->ip_addr_str, csp->http->cmd);
500       log_error(LOG_LEVEL_ERROR,
501          "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
502          csp->ip_addr_str, csp->http->cmd, req);
503       freez(req);
504
505       write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
506       destroy_list(headers);
507
508       return JB_ERR_PARSE;
509    }
510    /*
511     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
512     * to get the destination IP address, use it as host directly
513     * or do a reverse DNS lookup first.
514     */
515 }
516
517
518 /*********************************************************************
519  *
520  * Function    :  get_server_headers
521  *
522  * Description :  Parses server headers in iob and fills them
523  *                into csp->headers so that they can later be
524  *                handled by sed().
525  *
526  * Parameters  :
527  *          1  :  csp = Current client state (buffers, headers, etc...)
528  *
529  * Returns     :  JB_ERR_OK if everything went fine, or
530  *                JB_ERR_PARSE if the headers were incomplete.
531  *
532  *********************************************************************/
533 static jb_err get_server_headers(struct client_state *csp)
534 {
535    int continue_hack_in_da_house = 0;
536    char * header;
537
538    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
539    {
540       if (header == NULL)
541       {
542          /*
543           * continue hack in da house. Ignore the ending of
544           * this head and continue enlisting header lines.
545           * The reason is described below.
546           */
547          enlist(csp->headers, "");
548          continue_hack_in_da_house = 0;
549          continue;
550       }
551       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
552       {
553          /*
554           * It's a bodyless continue response, don't
555           * stop header parsing after reaching its end.
556           *
557           * As a result Privoxy will concatenate the
558           * next response's head and parse and deliver
559           * the headers as if they belonged to one request.
560           *
561           * The client will separate them because of the
562           * empty line between them.
563           *
564           * XXX: What we're doing here is clearly against
565           * the intended purpose of the continue header,
566           * and under some conditions (HTTP/1.0 client request)
567           * it's a standard violation.
568           *
569           * Anyway, "sort of against the spec" is preferable
570           * to "always getting confused by Continue responses"
571           * (Privoxy's behaviour before this hack was added)
572           */
573          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
574          continue_hack_in_da_house = 1;
575       }
576       else if (*header == '\0') 
577       {
578          /*
579           * If the header is empty, but the Continue hack
580           * isn't active, we can assume that we reached the
581           * end of the buffer before we hit the end of the
582           * head.
583           *
584           * Inform the caller an let it decide how to handle it.
585           */
586          return JB_ERR_PARSE;
587       }
588
589       if (JB_ERR_MEMORY == enlist(csp->headers, header))
590       {
591          /*
592           * XXX: Should we quit the request and return a
593           * out of memory error page instead?
594           */
595          log_error(LOG_LEVEL_ERROR,
596             "Out of memory while enlisting server headers. %s lost.",
597             header);
598       }
599       freez(header);
600    }
601
602    return JB_ERR_OK;
603 }
604
605
606 /*********************************************************************
607  *
608  * Function    :  crunch_reason
609  *
610  * Description :  Translates the crunch reason code into a string.
611  *
612  * Parameters  :
613  *          1  :  rsp = a http_response
614  *
615  * Returns     :  A string with the crunch reason or an error description.
616  *
617  *********************************************************************/
618 static const char *crunch_reason(const struct http_response *rsp)
619 {
620    char * reason = NULL;
621
622    assert(rsp != NULL);
623    if (rsp == NULL)
624    {
625       return "Internal error while searching for crunch reason";
626    }
627
628    switch (rsp->reason)
629    {
630       case RSP_REASON_UNSUPPORTED:
631          reason = "Unsupported HTTP feature";
632          break;
633       case RSP_REASON_BLOCKED:
634          reason = "Blocked";
635          break;
636       case RSP_REASON_UNTRUSTED:
637          reason = "Untrusted";
638          break;
639       case RSP_REASON_REDIRECTED:
640          reason = "Redirected";
641          break;
642       case RSP_REASON_CGI_CALL:
643          reason = "CGI Call";
644          break;
645       case RSP_REASON_NO_SUCH_DOMAIN:
646          reason = "DNS failure";
647          break;
648       case RSP_REASON_FORWARDING_FAILED:
649          reason = "Forwarding failed";
650          break;
651       case RSP_REASON_CONNECT_FAILED:
652          reason = "Connection failure";
653          break;
654       case RSP_REASON_OUT_OF_MEMORY:
655          reason = "Out of memory (may mask other reasons)";
656          break;
657       case RSP_REASON_CONNECTION_TIMEOUT:
658          reason = "Connection timeout";
659          break;
660       case RSP_REASON_NO_SERVER_DATA:
661          reason = "No server data received";
662          break;
663       default:
664          reason = "No reason recorded";
665          break;
666    }
667
668    return reason;
669 }
670
671
672 /*********************************************************************
673  *
674  * Function    :  send_crunch_response
675  *
676  * Description :  Delivers already prepared response for
677  *                intercepted requests, logs the interception
678  *                and frees the response.
679  *
680  * Parameters  :
681  *          1  :  csp = Current client state (buffers, headers, etc...)
682  *          1  :  rsp = Fully prepared response. Will be freed on exit.
683  *
684  * Returns     :  Nothing.
685  *
686  *********************************************************************/
687 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
688 {
689       const struct http_request *http = csp->http;
690       char status_code[4];
691
692       assert(rsp != NULL);
693       assert(rsp->head != NULL);
694
695       if (rsp == NULL)
696       {
697          /*
698           * Not supposed to happen. If it does
699           * anyway, treat it as an unknown error.
700           */
701          cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
702          /* return code doesn't matter */
703       }
704
705       if (rsp == NULL)
706       {
707          /* If rsp is still NULL, we have serious internal problems. */
708          log_error(LOG_LEVEL_FATAL,
709             "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
710       }
711
712       /*
713        * Extract the status code from the actual head
714        * that was send to the client. It is the only
715        * way to get it right for all requests, including
716        * the fixed ones for out-of-memory problems.
717        *
718        * A head starts like this: 'HTTP/1.1 200...'
719        *                           0123456789|11
720        *                                     10
721        */
722       status_code[0] = rsp->head[9];
723       status_code[1] = rsp->head[10];
724       status_code[2] = rsp->head[11];
725       status_code[3] = '\0';
726
727       /* Write the answer to the client */
728       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
729        || write_socket(csp->cfd, rsp->body, rsp->content_length))
730       {
731          /* There is nothing we can do about it. */
732          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
733       }
734
735       /* Log that the request was crunched and why. */
736       log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
737       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
738          csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
739
740       /* Clean up and return */
741       if (cgi_error_memory() != rsp)
742       {
743          free_http_response(rsp);
744       } 
745       return;
746 }
747
748
749 #if 0
750 /*********************************************************************
751  *
752  * Function    :  request_contains_null_bytes
753  *
754  * Description :  Checks for NULL bytes in the request and sends
755  *                an error message to the client if any were found.
756  *
757  *                XXX: currently not used, see comment in chat().
758  *
759  * Parameters  :
760  *          1  :  csp = Current client state (buffers, headers, etc...)
761  *          2  :  buf = Data from the client's request to check.
762  *          3  :  len = The data length.
763  *
764  * Returns     :  TRUE if the request contained one or more NULL bytes, or
765  *                FALSE otherwise.
766  *
767  *********************************************************************/
768 static int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
769 {
770    size_t c_len; /* Request lenght when treated as C string */
771
772    c_len = strlen(buf);
773
774    if (c_len < len)
775    {
776       /*
777        * Null byte(s) found. Log the request,
778        * return an error response and hang up.
779        */
780       size_t tmp_len = c_len;
781
782       do
783       {
784         /*
785          * Replace NULL byte(s) with '°' characters
786          * so the request can be logged as string.
787          * XXX: Is there a better replacement character?
788          */
789          buf[tmp_len]='°';
790          tmp_len += strlen(buf+tmp_len);
791       } while (tmp_len < len);
792
793       log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
794          "(length=%d, strlen=%u).", csp->ip_addr_str, len, c_len);
795       log_error(LOG_LEVEL_HEADER, 
796          "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
797
798       write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
799
800       /* XXX: Log correct size */
801       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
802
803       return TRUE;
804    }
805
806    return FALSE;
807 }
808 #endif
809
810
811 /*********************************************************************
812  *
813  * Function    :  crunch_response_triggered
814  *
815  * Description :  Checks if the request has to be crunched,
816  *                and delivers the crunch response if necessary.
817  *
818  * Parameters  :
819  *          1  :  csp = Current client state (buffers, headers, etc...)
820  *          2  :  crunchers = list of cruncher functions to run
821  *
822  * Returns     :  TRUE if the request was answered with a crunch response
823  *                FALSE otherwise.
824  *
825  *********************************************************************/
826 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
827 {
828    struct http_response *rsp = NULL;
829    const struct cruncher *c;
830
831    /*
832     * If CGI request crunching is disabled,
833     * check the CGI dispatcher out of order to
834     * prevent unintentional blocks or redirects. 
835     */
836    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
837        && (NULL != (rsp = dispatch_cgi(csp))))
838    {
839       /* Deliver, log and free the interception response. */
840       send_crunch_response(csp, rsp);
841       return TRUE;
842    }
843
844    for (c = crunchers; c->cruncher != NULL; c++)
845    {
846       /*
847        * Check the cruncher if either Privoxy is toggled
848        * on and the request isn't forced, or if the cruncher
849        * applies to forced requests as well.
850        */
851       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
852           !(csp->flags & CSP_FLAG_FORCED)) ||
853           (c->flags & CF_IGNORE_FORCE))
854       {
855          rsp = c->cruncher(csp);
856          if (NULL != rsp)
857          {
858             /* Deliver, log and free the interception response. */
859             send_crunch_response(csp, rsp);
860 #ifdef FEATURE_STATISTICS
861             if (c->flags & CF_COUNT_AS_REJECT)
862             {
863                csp->flags |= CSP_FLAG_REJECTED;
864             }
865 #endif /* def FEATURE_STATISTICS */
866
867             return TRUE;
868          }
869       }
870    }
871
872    return FALSE;
873 }
874
875
876 /*********************************************************************
877  *
878  * Function    :  build_request_line
879  *
880  * Description :  Builds the HTTP request line.
881  *
882  *                If a HTTP forwarder is used it expects the whole URL,
883  *                web servers only get the path.
884  *
885  * Parameters  :
886  *          1  :  csp = Current client state (buffers, headers, etc...)
887  *          2  :  fwd = The forwarding spec used for the request
888  *                XXX: Should use http->fwd instead.
889  *          3  :  request_line = The old request line which will be replaced.
890  *
891  * Returns     :  Nothing. Terminates in case of memory problems.
892  *
893  *********************************************************************/
894 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
895 {
896    struct http_request *http = csp->http;
897
898    assert(http->ssl == 0);
899
900    /*
901     * Downgrade http version from 1.1 to 1.0
902     * if +downgrade action applies.
903     */
904    if ( (csp->action->flags & ACTION_DOWNGRADE)
905      && (!strcmpic(http->ver, "HTTP/1.1")))
906    {
907       freez(http->ver);
908       http->ver = strdup("HTTP/1.0");
909
910       if (http->ver == NULL)
911       {
912          log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
913       }
914    }
915
916    /*
917     * Rebuild the request line.
918     */
919    freez(*request_line);
920    *request_line = strdup(http->gpc);
921    string_append(request_line, " ");
922
923    if (fwd->forward_host)
924    {
925       string_append(request_line, http->url);
926    }
927    else
928    {
929       string_append(request_line, http->path);
930    }
931    string_append(request_line, " ");
932    string_append(request_line, http->ver);
933
934    if (*request_line == NULL)
935    {
936       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
937    }
938    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
939 }
940
941
942 /*********************************************************************
943  *
944  * Function    :  change_request_destination
945  *
946  * Description :  Parse a (rewritten) request line and regenerate
947  *                the http request data.
948  *
949  * Parameters  :
950  *          1  :  csp = Current client state (buffers, headers, etc...)
951  *
952  * Returns     :  Forwards the parse_http_request() return code.
953  *                Terminates in case of memory problems.
954  *
955  *********************************************************************/
956 static jb_err change_request_destination(struct client_state *csp)
957 {
958    struct http_request *http = csp->http;
959    jb_err err;
960
961    log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
962    free_http_request(http);
963    err = parse_http_request(csp->headers->first->str, http);
964    if (JB_ERR_OK != err)
965    {
966       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
967          jb_err_to_string(err));
968    }
969    else
970    {
971       /* XXX: ocmd is a misleading name */
972       http->ocmd = strdup(http->cmd);
973       if (http->ocmd == NULL)
974       {
975          log_error(LOG_LEVEL_FATAL,
976             "Out of memory copying rewritten HTTP request line");
977       }
978    }
979
980    return err;
981 }
982
983
984 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
985 /*********************************************************************
986  *
987  * Function    :  server_response_is_complete
988  *
989  * Description :  Determines whether we should stop reading
990  *                from the server socket.
991  *
992  * Parameters  :
993  *          1  :  csp = Current client state (buffers, headers, etc...)
994  *          2  :  content_length = Length of content received so far.
995  *
996  * Returns     :  TRUE if the response is complete,
997  *                FALSE otherwise.
998  *
999  *********************************************************************/
1000 static int server_response_is_complete(struct client_state *csp,
1001    unsigned long long content_length)
1002 {
1003    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1004
1005    if (!strcmpic(csp->http->gpc, "HEAD"))
1006    {
1007       /*
1008        * "HEAD" implies no body, we are thus expecting
1009        * no content. XXX: incomplete "list" of methods?
1010        */
1011       csp->expected_content_length = 0;
1012       content_length_known = TRUE;
1013    }
1014
1015    if (csp->http->status == 304)
1016    {
1017       /*
1018        * Expect no body. XXX: incomplete "list" of status codes?
1019        */
1020       csp->expected_content_length = 0;
1021       content_length_known = TRUE;
1022    }
1023
1024    return (content_length_known && ((0 == csp->expected_content_length)
1025             || (csp->expected_content_length <= content_length)));
1026 }
1027
1028
1029 /*********************************************************************
1030  *
1031  * Function    :  wait_for_alive_connections
1032  *
1033  * Description :  Waits for alive connections to timeout.
1034  *
1035  * Parameters  :  N/A
1036  *
1037  * Returns     :  N/A
1038  *
1039  *********************************************************************/
1040 static void wait_for_alive_connections(void)
1041 {
1042    int connections_alive = close_unusable_connections();
1043
1044    while (0 < connections_alive)
1045    {
1046       log_error(LOG_LEVEL_CONNECT,
1047          "Waiting for %d connections to timeout.",
1048          connections_alive);
1049       sleep(60);
1050       connections_alive = close_unusable_connections();
1051    }
1052
1053    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1054
1055 }
1056
1057
1058 /*********************************************************************
1059  *
1060  * Function    :  save_connection_destination
1061  *
1062  * Description :  Remembers a connection for reuse later on.
1063  *
1064  * Parameters  :
1065  *          1  :  sfd  = Open socket to remember.
1066  *          2  :  http = The destination for the connection.
1067  *          3  :  fwd  = The forwarder settings used.
1068  *          3  :  server_connection  = storage.
1069  *
1070  * Returns     : void
1071  *
1072  *********************************************************************/
1073 void save_connection_destination(jb_socket sfd,
1074                                  const struct http_request *http,
1075                                  const struct forward_spec *fwd,
1076                                  struct reusable_connection *server_connection)
1077 {
1078    assert(sfd != JB_INVALID_SOCKET);
1079    assert(NULL != http->host);
1080    server_connection->host = strdup(http->host);
1081    if (NULL == server_connection->host)
1082    {
1083       log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1084    }
1085    server_connection->port = http->port;
1086
1087    assert(NULL != fwd);
1088    assert(server_connection->gateway_host == NULL);
1089    assert(server_connection->gateway_port == 0);
1090    assert(server_connection->forwarder_type == 0);
1091    assert(server_connection->forward_host == NULL);
1092    assert(server_connection->forward_port == 0);
1093
1094    server_connection->forwarder_type = fwd->type;
1095    if (NULL != fwd->gateway_host)
1096    {
1097       server_connection->gateway_host = strdup(fwd->gateway_host);
1098       if (NULL == server_connection->gateway_host)
1099       {
1100          log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1101       }
1102    }
1103    else
1104    {
1105       server_connection->gateway_host = NULL;
1106    }
1107    server_connection->gateway_port = fwd->gateway_port;
1108
1109    if (NULL != fwd->forward_host)
1110    {
1111       server_connection->forward_host = strdup(fwd->forward_host);
1112       if (NULL == server_connection->forward_host)
1113       {
1114          log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1115       }
1116    }
1117    else
1118    {
1119       server_connection->forward_host = NULL;
1120    }
1121    server_connection->forward_port = fwd->forward_port;
1122 }
1123 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1124
1125
1126 /*********************************************************************
1127  *
1128  * Function    :  mark_server_socket_tainted
1129  *
1130  * Description :  Makes sure we don't reuse a server socket
1131  *                (if we didn't read everything the server sent
1132  *                us reusing the socket would lead to garbage).
1133  *
1134  * Parameters  :
1135  *          1  :  csp = Current client state (buffers, headers, etc...)
1136  *
1137  * Returns     :  void.
1138  *
1139  *********************************************************************/
1140 static void mark_server_socket_tainted(struct client_state *csp)
1141 {
1142    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
1143    {
1144       log_error(LOG_LEVEL_CONNECT,
1145          "Marking the connection to the server tainted.");
1146       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1147    }
1148 }
1149
1150 /*********************************************************************
1151  *
1152  * Function    :  get_request_line
1153  *
1154  * Description : Read the client request line.
1155  *
1156  * Parameters  :
1157  *          1  :  csp = Current client state (buffers, headers, etc...)
1158  *
1159  * Returns     :  Pointer to request line or NULL in case of errors.
1160  *
1161  *********************************************************************/
1162 static char *get_request_line(struct client_state *csp)
1163 {
1164    char buf[BUFFER_SIZE];
1165    char *request_line = NULL;
1166    int len;
1167
1168    memset(buf, 0, sizeof(buf));
1169
1170    do
1171    {
1172       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1173       {
1174          log_error(LOG_LEVEL_ERROR,
1175             "Stopped waiting for the request line.");
1176          write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1177             strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1178          return NULL;
1179       }
1180
1181       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1182
1183       if (len <= 0) return NULL;
1184
1185       /*
1186        * If there is no memory left for buffering the
1187        * request, there is nothing we can do but hang up
1188        */
1189       if (add_to_iob(csp, buf, len))
1190       {
1191          return NULL;
1192       }
1193
1194       request_line = get_header(csp->iob);
1195
1196    } while ((NULL != request_line) && ('\0' == *request_line));
1197
1198    return request_line;
1199
1200 }
1201
1202
1203 /*********************************************************************
1204  *
1205  * Function    :  receive_client_request
1206  *
1207  * Description : Read the client's request (more precisely the
1208  *               client headers) and answer it if necessary.
1209  *
1210  *               Note that since we're not using select() we could get
1211  *               blocked here if a client connected, then didn't say
1212  *               anything!
1213  *
1214  * Parameters  :
1215  *          1  :  csp = Current client state (buffers, headers, etc...)
1216  *
1217  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1218  *
1219  *********************************************************************/
1220 static jb_err receive_client_request(struct client_state *csp)
1221 {
1222    char buf[BUFFER_SIZE];
1223    char *p;
1224    char *req = NULL;
1225    struct http_request *http;
1226    int len;
1227    jb_err err;
1228
1229    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1230    struct list header_list;
1231    struct list *headers = &header_list;
1232
1233    http = csp->http;
1234
1235    memset(buf, 0, sizeof(buf));
1236
1237    req = get_request_line(csp);
1238    if (req == NULL)
1239    {
1240       return JB_ERR_PARSE;
1241    }
1242    assert(*req != '\0');
1243
1244    if (client_protocol_is_unsupported(csp, req))
1245    {
1246       return JB_ERR_PARSE;
1247    }
1248
1249 #ifdef FEATURE_FORCE_LOAD
1250    /*
1251     * If this request contains the FORCE_PREFIX and blocks
1252     * aren't enforced, get rid of it and set the force flag.
1253     */
1254    if (strstr(req, FORCE_PREFIX))
1255    {
1256       if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1257       {
1258          log_error(LOG_LEVEL_FORCE,
1259             "Ignored force prefix in request: \"%s\".", req);
1260       }
1261       else
1262       {
1263          strclean(req, FORCE_PREFIX);
1264          log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1265          csp->flags |= CSP_FLAG_FORCED;
1266       }
1267    }
1268 #endif /* def FEATURE_FORCE_LOAD */
1269
1270    err = parse_http_request(req, http);
1271    freez(req);
1272    if (JB_ERR_OK != err)
1273    {
1274       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1275       /* XXX: Use correct size */
1276       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1277       log_error(LOG_LEVEL_ERROR,
1278          "Couldn't parse request line received from %s: %s",
1279          csp->ip_addr_str, jb_err_to_string(err));
1280
1281       free_http_request(http);
1282       return JB_ERR_PARSE;
1283    }
1284
1285    /* grab the rest of the client's headers */
1286    init_list(headers);
1287    for (;;)
1288    {
1289       p = get_header(csp->iob);
1290
1291       if (p == NULL)
1292       {
1293          /* There are no additional headers to read. */
1294          break;
1295       }
1296
1297       if (*p == '\0')
1298       {
1299          /*
1300           * We didn't receive a complete header
1301           * line yet, get the rest of it.
1302           */
1303          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1304          {
1305             log_error(LOG_LEVEL_ERROR,
1306                "Stopped grabbing the client headers.");
1307             destroy_list(headers);
1308             return JB_ERR_PARSE;
1309          }
1310
1311          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1312          if (len <= 0)
1313          {
1314             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1315             destroy_list(headers);
1316             return JB_ERR_PARSE;
1317          }
1318          
1319          if (add_to_iob(csp, buf, len))
1320          {
1321             /*
1322              * If there is no memory left for buffering the
1323              * request, there is nothing we can do but hang up
1324              */
1325             destroy_list(headers);
1326             return JB_ERR_MEMORY;
1327          }
1328       }
1329       else
1330       {
1331          /*
1332           * We were able to read a complete
1333           * header and can finaly enlist it.
1334           */
1335          enlist(headers, p);
1336          freez(p);
1337       }
1338    }
1339
1340    if (http->host == NULL)
1341    {
1342       /*
1343        * If we still don't know the request destination,
1344        * the request is invalid or the client uses
1345        * Privoxy without its knowledge.
1346        */
1347       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1348       {
1349          /*
1350           * Our attempts to get the request destination
1351           * elsewhere failed or Privoxy is configured
1352           * to only accept proxy requests.
1353           *
1354           * An error response has already been send
1355           * and we're done here.
1356           */
1357          return JB_ERR_PARSE;
1358       }
1359    }
1360
1361    /*
1362     * Determine the actions for this URL
1363     */
1364 #ifdef FEATURE_TOGGLE
1365    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1366    {
1367       /* Most compatible set of actions (i.e. none) */
1368       init_current_action(csp->action);
1369    }
1370    else
1371 #endif /* ndef FEATURE_TOGGLE */
1372    {
1373       get_url_actions(csp, http);
1374    }
1375
1376    /* 
1377     * Save a copy of the original request for logging
1378     */
1379    http->ocmd = strdup(http->cmd);
1380    if (http->ocmd == NULL)
1381    {
1382       log_error(LOG_LEVEL_FATAL,
1383          "Out of memory copying HTTP request line");
1384    }
1385    enlist(csp->headers, http->cmd);
1386
1387    /* Append the previously read headers */
1388    list_append_list_unique(csp->headers, headers);
1389    destroy_list(headers);
1390
1391    return JB_ERR_OK;
1392
1393 }
1394
1395
1396 /*********************************************************************
1397  *
1398  * Function    : parse_client_request
1399  *
1400  * Description : Parses the client's request and decides what to do
1401  *               with it.
1402  *
1403  *               Note that since we're not using select() we could get
1404  *               blocked here if a client connected, then didn't say
1405  *               anything!
1406  *
1407  * Parameters  :
1408  *          1  :  csp = Current client state (buffers, headers, etc...)
1409  *
1410  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1411  *
1412  *********************************************************************/
1413 static jb_err parse_client_request(struct client_state *csp)
1414 {
1415    struct http_request *http = csp->http;
1416    jb_err err;
1417
1418    err = sed(csp, FILTER_CLIENT_HEADERS);
1419    if (JB_ERR_OK != err)
1420    {
1421       /* XXX: Should be handled in sed(). */
1422       assert(err == JB_ERR_PARSE);
1423       log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1424    }
1425    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1426
1427    /* Check request line for rewrites. */
1428    if ((NULL == csp->headers->first->str)
1429       || (strcmp(http->cmd, csp->headers->first->str) &&
1430          (JB_ERR_OK != change_request_destination(csp))))
1431    {
1432       /*
1433        * A header filter broke the request line - bail out.
1434        */
1435       write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1436       /* XXX: Use correct size */
1437       log_error(LOG_LEVEL_CLF,
1438          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1439       log_error(LOG_LEVEL_ERROR,
1440          "Invalid request line after applying header filters.");
1441       free_http_request(http);
1442
1443       return JB_ERR_PARSE;
1444    }
1445
1446 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1447    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1448    {
1449       if (csp->iob->cur[0] != '\0')
1450       {
1451          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1452          if (!strcmpic(csp->http->gpc, "POST"))
1453          {
1454             /* XXX: this is an incomplete hack */
1455             csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1456             log_error(LOG_LEVEL_CONNECT,
1457                "POST request detected. The connection will not be kept alive.");
1458          }
1459          else
1460          {
1461             /* XXX: and so is this */
1462             csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1463             log_error(LOG_LEVEL_CONNECT,
1464                "Possible pipeline attempt detected. The connection will not "
1465                "be kept alive and we will only serve the first request.");
1466             /* Nuke the pipelined requests from orbit, just to be sure. */
1467             csp->iob->buf[0] = '\0';
1468             csp->iob->eod = csp->iob->cur = csp->iob->buf;
1469          }
1470       }
1471       else
1472       {
1473          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1474          log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1475       }
1476    }
1477 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1478
1479    return JB_ERR_OK;
1480
1481 }
1482
1483
1484 /*********************************************************************
1485  *
1486  * Function    :  chat
1487  *
1488  * Description :  Once a connection to the client has been accepted,
1489  *                this function is called (via serve()) to handle the
1490  *                main business of the communication.  When this
1491  *                function returns, the caller must close the client
1492  *                socket handle.
1493  *
1494  *                FIXME: chat is nearly thousand lines long.
1495  *                Ridiculous.
1496  *
1497  * Parameters  :
1498  *          1  :  csp = Current client state (buffers, headers, etc...)
1499  *
1500  * Returns     :  Nothing.
1501  *
1502  *********************************************************************/
1503 static void chat(struct client_state *csp)
1504 {
1505    char buf[BUFFER_SIZE];
1506    char *hdr;
1507    char *p;
1508    fd_set rfds;
1509    int n;
1510    jb_socket maxfd;
1511    int server_body;
1512    int ms_iis5_hack = 0;
1513    unsigned long long byte_count = 0;
1514    int forwarded_connect_retries = 0;
1515    int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1516    const struct forward_spec *fwd;
1517    struct http_request *http;
1518    long len = 0; /* for buffer sizes (and negative error codes) */
1519
1520    /* Function that does the content filtering for the current request */
1521    filter_function_ptr content_filter = NULL;
1522
1523    /* Skeleton for HTTP response, if we should intercept the request */
1524    struct http_response *rsp;
1525    struct timeval timeout;
1526
1527    memset(buf, 0, sizeof(buf));
1528
1529    http = csp->http;
1530
1531    if (receive_client_request(csp) != JB_ERR_OK)
1532    {
1533       return;
1534    }
1535    if (parse_client_request(csp) != JB_ERR_OK)
1536    {
1537       return;
1538    }
1539
1540    /* decide how to route the HTTP request */
1541    fwd = forward_url(csp, http);
1542    if (NULL == fwd)
1543    {
1544       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
1545       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1546       return;
1547    }
1548
1549    /*
1550     * build the http request to send to the server
1551     * we have to do one of the following:
1552     *
1553     * create = use the original HTTP request to create a new
1554     *          HTTP request that has either the path component
1555     *          without the http://domainspec (w/path) or the
1556     *          full orininal URL (w/url)
1557     *          Note that the path and/or the HTTP version may
1558     *          have been altered by now.
1559     *
1560     * connect = Open a socket to the host:port of the server
1561     *           and short-circuit server and client socket.
1562     *
1563     * pass =  Pass the request unchanged if forwarding a CONNECT
1564     *         request to a parent proxy. Note that we'll be sending
1565     *         the CFAIL message ourselves if connecting to the parent
1566     *         fails, but we won't send a CSUCCEED message if it works,
1567     *         since that would result in a double message (ours and the
1568     *         parent's). After sending the request to the parent, we simply
1569     *         tunnel.
1570     *
1571     * here's the matrix:
1572     *                        SSL
1573     *                    0        1
1574     *                +--------+--------+
1575     *                |        |        |
1576     *             0  | create | connect|
1577     *                | w/path |        |
1578     *  Forwarding    +--------+--------+
1579     *                |        |        |
1580     *             1  | create | pass   |
1581     *                | w/url  |        |
1582     *                +--------+--------+
1583     *
1584     */
1585
1586    if (http->ssl && connect_port_is_forbidden(csp))
1587    {
1588       const char *acceptable_connect_ports =
1589          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1590       assert(NULL != acceptable_connect_ports);
1591       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1592          "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
1593          csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
1594       csp->action->flags |= ACTION_BLOCK;
1595       http->ssl = 0;
1596    }
1597
1598    if (http->ssl == 0)
1599    {
1600       freez(csp->headers->first->str);
1601       build_request_line(csp, fwd, &csp->headers->first->str);
1602    }
1603
1604    /*
1605     * We have a request. Check if one of the crunchers wants it.
1606     */
1607    if (crunch_response_triggered(csp, crunchers_all))
1608    {
1609       /*
1610        * Yes. The client got the crunch response
1611        * and we are done here after cleaning up.
1612        */
1613       /* XXX: why list_remove_all()? */
1614       list_remove_all(csp->headers);
1615
1616       return;
1617    }
1618
1619    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1620
1621    if (fwd->forward_host)
1622    {
1623       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1624          fwd->forward_host, fwd->forward_port, http->hostport);
1625    }
1626    else
1627    {
1628       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1629    }
1630
1631    /* here we connect to the server, gateway, or the forwarder */
1632
1633 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1634    if ((csp->sfd != JB_INVALID_SOCKET)
1635       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1636       && socket_is_still_usable(csp->sfd)
1637       && connection_destination_matches(&csp->server_connection, http, fwd))
1638    {
1639       log_error(LOG_LEVEL_CONNECT,
1640          "Reusing server socket %u. Opened for %s.",
1641          csp->sfd, csp->server_connection.host);
1642    }
1643    else
1644    {
1645       if (csp->sfd != JB_INVALID_SOCKET)
1646       {
1647          log_error(LOG_LEVEL_CONNECT,
1648             "Closing server socket %u. Opened for %s.",
1649             csp->sfd, csp->server_connection.host);
1650          close_socket(csp->sfd);
1651          mark_connection_closed(&csp->server_connection);
1652       }
1653 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1654
1655       while ((csp->sfd = forwarded_connect(fwd, http, csp))
1656          && (errno == EINVAL)
1657          && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1658       {
1659          log_error(LOG_LEVEL_ERROR,
1660             "failed request #%u to connect to %s. Trying again.",
1661             forwarded_connect_retries, http->hostport);
1662       }
1663
1664       if (csp->sfd == JB_INVALID_SOCKET)
1665       {
1666          if (fwd->type != SOCKS_NONE)
1667          {
1668             /* Socks error. */
1669             rsp = error_response(csp, "forwarding-failed");
1670          }
1671          else if (errno == EINVAL)
1672          {
1673             rsp = error_response(csp, "no-such-domain");
1674          }
1675          else
1676          {
1677             rsp = error_response(csp, "connect-failed");
1678             log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1679                http->hostport);
1680          }
1681
1682          /* Write the answer to the client */
1683          if (rsp != NULL)
1684          {
1685             send_crunch_response(csp, rsp);
1686          }
1687
1688          return;
1689       }
1690 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1691       save_connection_destination(csp->sfd, http, fwd, &csp->server_connection);
1692       csp->server_connection.keep_alive_timeout = (unsigned)csp->config->keep_alive_timeout;
1693    }
1694 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1695
1696    hdr = list_to_text(csp->headers);
1697    if (hdr == NULL)
1698    {
1699       /* FIXME Should handle error properly */
1700       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1701    }
1702    list_remove_all(csp->headers);
1703
1704    if (fwd->forward_host || (http->ssl == 0))
1705    {
1706       /*
1707        * Write the client's (modified) header to the server
1708        * (along with anything else that may be in the buffer)
1709        */
1710       if (write_socket(csp->sfd, hdr, strlen(hdr))
1711        || (flush_socket(csp->sfd, csp->iob) <  0))
1712       {
1713          log_error(LOG_LEVEL_CONNECT,
1714             "write header to: %s failed: %E", http->hostport);
1715
1716          rsp = error_response(csp, "connect-failed");
1717          if (rsp)
1718          {
1719             send_crunch_response(csp, rsp);
1720          }
1721
1722          freez(hdr);
1723          return;
1724       }
1725    }
1726    else
1727    {
1728       /*
1729        * We're running an SSL tunnel and we're not forwarding,
1730        * so just send the "connect succeeded" message to the
1731        * client, flush the rest, and get out of the way.
1732        */
1733       if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1734       {
1735          freez(hdr);
1736          return;
1737       }
1738       IOB_RESET(csp);
1739    }
1740
1741    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1742
1743    /* we're finished with the client's header */
1744    freez(hdr);
1745
1746    maxfd = (csp->cfd > csp->sfd) ? csp->cfd : csp->sfd;
1747
1748    /* pass data between the client and server
1749     * until one or the other shuts down the connection.
1750     */
1751
1752    server_body = 0;
1753
1754    for (;;)
1755    {
1756 #ifdef __OS2__
1757       /*
1758        * FD_ZERO here seems to point to an errant macro which crashes.
1759        * So do this by hand for now...
1760        */
1761       memset(&rfds,0x00,sizeof(fd_set));
1762 #else
1763       FD_ZERO(&rfds);
1764 #endif
1765 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1766       if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1767       {
1768          maxfd = csp->sfd;
1769       }
1770       else
1771 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1772       {
1773          FD_SET(csp->cfd, &rfds);
1774       }
1775
1776       FD_SET(csp->sfd, &rfds);
1777
1778 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1779       if ((csp->flags & CSP_FLAG_CHUNKED)
1780          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1781          && ((csp->iob->eod - csp->iob->cur) >= 5)
1782          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1783       {
1784          log_error(LOG_LEVEL_CONNECT,
1785             "Looks like we read the last chunk together with "
1786             "the server headers. We better stop reading.");
1787          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1788          csp->expected_content_length = byte_count;
1789          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1790       }
1791       if (server_body && server_response_is_complete(csp, byte_count))
1792       {
1793          log_error(LOG_LEVEL_CONNECT,
1794             "Done reading from server. Expected content length: %llu. "
1795             "Actual content length: %llu. Most recently received: %d.",
1796             csp->expected_content_length, byte_count, len);
1797          len = 0;
1798          /*
1799           * XXX: should not jump around,
1800           * chat() is complicated enough already.
1801           */
1802          goto reading_done;
1803       }
1804 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
1805
1806       timeout.tv_sec = csp->config->socket_timeout;
1807       timeout.tv_usec = 0;
1808       n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1809
1810       if (n == 0)
1811       {
1812          log_error(LOG_LEVEL_ERROR,
1813             "Didn't receive data in time: %s", http->url);
1814          if ((byte_count == 0) && (http->ssl == 0))
1815          {
1816             send_crunch_response(csp, error_response(csp, "connection-timeout"));
1817          }
1818          mark_server_socket_tainted(csp);
1819          return;
1820       }
1821       else if (n < 0)
1822       {
1823          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1824          mark_server_socket_tainted(csp);
1825          return;
1826       }
1827
1828       /*
1829        * This is the body of the browser's request,
1830        * just read and write it.
1831        *
1832        * XXX: Make sure the client doesn't use pipelining
1833        * behind Privoxy's back.
1834        */
1835       if (FD_ISSET(csp->cfd, &rfds))
1836       {
1837          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1838
1839          if (len <= 0)
1840          {
1841             /* XXX: not sure if this is necessary. */
1842             mark_server_socket_tainted(csp);
1843             break; /* "game over, man" */
1844          }
1845
1846          if (write_socket(csp->sfd, buf, (size_t)len))
1847          {
1848             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1849             mark_server_socket_tainted(csp);
1850             return;
1851          }
1852          continue;
1853       }
1854
1855       /*
1856        * The server wants to talk. It could be the header or the body.
1857        * If `hdr' is null, then it's the header otherwise it's the body.
1858        * FIXME: Does `hdr' really mean `host'? No.
1859        */
1860       if (FD_ISSET(csp->sfd, &rfds))
1861       {
1862          fflush(NULL);
1863          len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1864
1865          if (len < 0)
1866          {
1867             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1868
1869             if (http->ssl && (fwd->forward_host == NULL))
1870             {
1871                /*
1872                 * Just hang up. We already confirmed the client's CONNECT
1873                 * request with status code 200 and unencrypted content is
1874                 * no longer welcome.
1875                 */
1876                log_error(LOG_LEVEL_ERROR,
1877                   "CONNECT already confirmed. Unable to tell the client about the problem.");
1878                return;
1879             }
1880             else if (byte_count)
1881             {
1882                /*
1883                 * Just hang up. We already transmitted the original headers
1884                 * and parts of the original content and therefore missed the
1885                 * chance to send an error message (without risking data corruption).
1886                 *
1887                 * XXX: we could retry with a fancy range request here.
1888                 */
1889                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1890                   "Unable to tell the client about the problem.");
1891                mark_server_socket_tainted(csp);
1892                return;
1893             }
1894             /*
1895              * XXX: Consider handling the cases above the same.
1896              */
1897             mark_server_socket_tainted(csp);
1898             len = 0;
1899          }
1900
1901 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1902          if (csp->flags & CSP_FLAG_CHUNKED)
1903          {
1904             if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
1905             {
1906                /* XXX: this is a temporary hack */
1907                log_error(LOG_LEVEL_CONNECT,
1908                   "Looks like we reached the end of the last chunk. "
1909                   "We better stop reading.");
1910                csp->expected_content_length = byte_count + (unsigned long long)len;
1911                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1912             }
1913          }
1914          reading_done:
1915 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
1916
1917          /*
1918           * Add a trailing zero to let be able to use string operations.
1919           * XXX: do we still need this with filter_popups gone?
1920           */
1921          buf[len] = '\0';
1922
1923          /*
1924           * Normally, this would indicate that we've read
1925           * as much as the server has sent us and we can
1926           * close the client connection.  However, Microsoft
1927           * in its wisdom has released IIS/5 with a bug that
1928           * prevents it from sending the trailing \r\n in
1929           * a 302 redirect header (and possibly other headers).
1930           * To work around this if we've haven't parsed
1931           * a full header we'll append a trailing \r\n
1932           * and see if this now generates a valid one.
1933           *
1934           * This hack shouldn't have any impacts.  If we've
1935           * already transmitted the header or if this is a
1936           * SSL connection, then we won't bother with this
1937           * hack.  So we only work on partially received
1938           * headers.  If we append a \r\n and this still
1939           * doesn't generate a valid header, then we won't
1940           * transmit anything to the client.
1941           */
1942          if (len == 0)
1943          {
1944
1945             if (server_body || http->ssl)
1946             {
1947                /*
1948                 * If we have been buffering up the document,
1949                 * now is the time to apply content modification
1950                 * and send the result to the client.
1951                 */
1952                if (content_filter)
1953                {
1954                   p = execute_content_filter(csp, content_filter);
1955                   /*
1956                    * If the content filter fails, use the original
1957                    * buffer and length.
1958                    * (see p != NULL ? p : csp->iob->cur below)
1959                    */
1960                   if (NULL == p)
1961                   {
1962                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
1963                   }
1964
1965                   if (JB_ERR_OK != update_server_headers(csp))
1966                   {
1967                      log_error(LOG_LEVEL_FATAL,
1968                         "Failed to update server headers. after filtering.");
1969                   }
1970
1971                   hdr = list_to_text(csp->headers);
1972                   if (hdr == NULL)
1973                   {
1974                      /* FIXME Should handle error properly */
1975                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1976                   }
1977
1978                   if (write_socket(csp->cfd, hdr, strlen(hdr))
1979                    || write_socket(csp->cfd,
1980                          ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
1981                   {
1982                      log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1983                      freez(hdr);
1984                      freez(p);
1985                      mark_server_socket_tainted(csp);
1986                      return;
1987                   }
1988
1989                   freez(hdr);
1990                   freez(p);
1991                }
1992
1993                break; /* "game over, man" */
1994             }
1995
1996             /*
1997              * This is NOT the body, so
1998              * Let's pretend the server just sent us a blank line.
1999              */
2000             snprintf(buf, sizeof(buf), "\r\n");
2001             len = (int)strlen(buf);
2002
2003             /*
2004              * Now, let the normal header parsing algorithm below do its
2005              * job.  If it fails, we'll exit instead of continuing.
2006              */
2007
2008             ms_iis5_hack = 1;
2009          }
2010
2011          /*
2012           * If this is an SSL connection or we're in the body
2013           * of the server document, just write it to the client,
2014           * unless we need to buffer the body for later content-filtering
2015           */
2016          if (server_body || http->ssl)
2017          {
2018             if (content_filter)
2019             {
2020                /*
2021                 * If there is no memory left for buffering the content, or the buffer limit
2022                 * has been reached, switch to non-filtering mode, i.e. make & write the
2023                 * header, flush the iob and buf, and get out of the way.
2024                 */
2025                if (add_to_iob(csp, buf, len))
2026                {
2027                   size_t hdrlen;
2028                   long flushed;
2029
2030                   log_error(LOG_LEVEL_INFO,
2031                      "Flushing header and buffers. Stepping back from filtering.");
2032
2033                   hdr = list_to_text(csp->headers);
2034                   if (hdr == NULL)
2035                   {
2036                      /* 
2037                       * Memory is too tight to even generate the header.
2038                       * Send our static "Out-of-memory" page.
2039                       */
2040                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2041                      rsp = cgi_error_memory();
2042                      send_crunch_response(csp, rsp);
2043                      mark_server_socket_tainted(csp);
2044                      return;
2045                   }
2046                   hdrlen = strlen(hdr);
2047
2048                   if (write_socket(csp->cfd, hdr, hdrlen)
2049                    || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2050                    || (write_socket(csp->cfd, buf, (size_t)len)))
2051                   {
2052                      log_error(LOG_LEVEL_CONNECT,
2053                         "Flush header and buffers to client failed: %E");
2054                      freez(hdr);
2055                      mark_server_socket_tainted(csp);
2056                      return;
2057                   }
2058
2059                   /*
2060                    * Reset the byte_count to the amount of bytes
2061                    * we just flushed. len will be added a few lines below,
2062                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
2063                    */
2064                   byte_count = (unsigned long long)flushed;
2065                   freez(hdr);
2066                   content_filter = NULL;
2067                   server_body = 1;
2068                }
2069             }
2070             else
2071             {
2072                if (write_socket(csp->cfd, buf, (size_t)len))
2073                {
2074                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2075                   mark_server_socket_tainted(csp);
2076                   return;
2077                }
2078             }
2079             byte_count += (unsigned long long)len;
2080             continue;
2081          }
2082          else
2083          {
2084             const char *header_start;
2085             /*
2086              * We're still looking for the end of the server's header.
2087              * Buffer up the data we just read.  If that fails, there's
2088              * little we can do but send our static out-of-memory page.
2089              */
2090             if (add_to_iob(csp, buf, len))
2091             {
2092                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2093                rsp = cgi_error_memory();
2094                send_crunch_response(csp, rsp);               
2095                mark_server_socket_tainted(csp);
2096                return;
2097             }
2098
2099             header_start = csp->iob->cur;
2100
2101             /* Convert iob into something sed() can digest */
2102             if (JB_ERR_PARSE == get_server_headers(csp))
2103             {
2104                if (ms_iis5_hack)
2105                {
2106                   /*
2107                    * Well, we tried our MS IIS/5 hack and it didn't work.
2108                    * The header is incomplete and there isn't anything
2109                    * we can do about it.
2110                    */
2111                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2112                      "Applying the MS IIS5 hack didn't help.");
2113                   log_error(LOG_LEVEL_CLF,
2114                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2115                   write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2116                      strlen(INVALID_SERVER_HEADERS_RESPONSE));
2117                   mark_server_socket_tainted(csp);
2118                   return;
2119                }
2120                else
2121                {
2122                   /*
2123                    * Since we have to wait for more from the server before
2124                    * we can parse the headers we just continue here.
2125                    */
2126                   long header_offset = csp->iob->cur - header_start;
2127                   assert(csp->iob->cur >= header_start);
2128                   byte_count += (unsigned long long)(len - header_offset);
2129                   log_error(LOG_LEVEL_CONNECT, "Continuing buffering headers. "
2130                      "byte_count: %llu. header_offset: %d. len: %d.",
2131                      byte_count, header_offset, len);
2132                   continue;
2133                }
2134             }
2135
2136             /* Did we actually get anything? */
2137             if (NULL == csp->headers->first)
2138             {
2139                log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
2140                log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2141                send_crunch_response(csp, error_response(csp, "no-server-data"));
2142                free_http_request(http);
2143                mark_server_socket_tainted(csp);
2144                return;
2145             }
2146
2147             assert(csp->headers->first->str);
2148             assert(!http->ssl);
2149             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2150                 strncmpic(csp->headers->first->str, "ICY", 3))
2151             {
2152                /*
2153                 * It doesn't look like a HTTP (or Shoutcast) response:
2154                 * tell the client and log the problem.
2155                 */
2156                if (strlen(csp->headers->first->str) > 30)
2157                {
2158                   csp->headers->first->str[30] = '\0';
2159                }
2160                log_error(LOG_LEVEL_ERROR,
2161                   "Invalid server or forwarder response. Starts with: %s",
2162                   csp->headers->first->str);
2163                log_error(LOG_LEVEL_CLF,
2164                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2165                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2166                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2167                free_http_request(http);
2168                mark_server_socket_tainted(csp);
2169                return;
2170             }
2171
2172             /*
2173              * We have now received the entire server header,
2174              * filter it and send the result to the client
2175              */
2176             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2177             {
2178                log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2179             }
2180             hdr = list_to_text(csp->headers);
2181             if (hdr == NULL)
2182             {
2183                /* FIXME Should handle error properly */
2184                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2185             }
2186
2187             if (crunch_response_triggered(csp, crunchers_light))
2188             {
2189                /*
2190                 * One of the tags created by a server-header
2191                 * tagger triggered a crunch. We already
2192                 * delivered the crunch response to the client
2193                 * and are done here after cleaning up.
2194                 */
2195                 freez(hdr);
2196                 mark_server_socket_tainted(csp);
2197                 return;
2198             }
2199             /* Buffer and pcrs filter this if appropriate. */
2200
2201             if (!http->ssl) /* We talk plaintext */
2202             {
2203                content_filter = get_filter_function(csp);
2204             }
2205             /*
2206              * Only write if we're not buffering for content modification
2207              */
2208             if (!content_filter)
2209             {
2210                /*
2211                 * Write the server's (modified) header to
2212                 * the client (along with anything else that
2213                 * may be in the buffer)
2214                 */
2215
2216                if (write_socket(csp->cfd, hdr, strlen(hdr))
2217                 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2218                {
2219                   log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2220
2221                   /*
2222                    * The write failed, so don't bother mentioning it
2223                    * to the client... it probably can't hear us anyway.
2224                    */
2225                   freez(hdr);
2226                   mark_server_socket_tainted(csp);
2227                   return;
2228                }
2229
2230                byte_count += (unsigned long long)len;
2231             }
2232             else
2233             {
2234                /*
2235                 * XXX: the header lenght should probably
2236                 * be calculated by get_server_headers().
2237                 */
2238                long header_length = csp->iob->cur - header_start;
2239                assert(csp->iob->cur > header_start);
2240                byte_count += (unsigned long long)(len - header_length);
2241             }
2242
2243             /* we're finished with the server's header */
2244
2245             freez(hdr);
2246             server_body = 1;
2247
2248             /*
2249              * If this was a MS IIS/5 hack then it means the server
2250              * has already closed the connection. Nothing more to read.
2251              * Time to bail.
2252              */
2253             if (ms_iis5_hack)
2254             {
2255                log_error(LOG_LEVEL_ERROR,
2256                   "Closed server connection detected. "
2257                   "Applying the MS IIS5 hack didn't help.");
2258                log_error(LOG_LEVEL_CLF,
2259                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2260                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2261                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2262                mark_server_socket_tainted(csp);
2263                return;
2264             }
2265          }
2266          continue;
2267       }
2268       mark_server_socket_tainted(csp);
2269       return; /* huh? we should never get here */
2270    }
2271
2272    if (csp->content_length == 0)
2273    {
2274       /*
2275        * If Privoxy didn't recalculate the Content-Lenght,
2276        * byte_count is still correct.
2277        */
2278       csp->content_length = byte_count;
2279    }
2280
2281 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2282    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2283       && (csp->expected_content_length != byte_count))
2284    {
2285       log_error(LOG_LEVEL_CONNECT,
2286          "Received %llu bytes while expecting %llu.",
2287          byte_count, csp->expected_content_length);
2288       mark_server_socket_tainted(csp);
2289    }
2290 #endif
2291
2292    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2293       csp->ip_addr_str, http->ocmd, csp->content_length);
2294 }
2295
2296
2297 /*********************************************************************
2298  *
2299  * Function    :  serve
2300  *
2301  * Description :  This is little more than chat.  We only "serve" to
2302  *                to close (or remember) any socket that chat may have
2303  *                opened.
2304  *
2305  * Parameters  :
2306  *          1  :  csp = Current client state (buffers, headers, etc...)
2307  *
2308  * Returns     :  N/A
2309  *
2310  *********************************************************************/
2311 #ifdef AMIGA
2312 void serve(struct client_state *csp)
2313 #else /* ifndef AMIGA */
2314 static void serve(struct client_state *csp)
2315 #endif /* def AMIGA */
2316 {
2317 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2318    static int monitor_thread_running = 0;
2319    int continue_chatting = 0;
2320    do
2321    {
2322       chat(csp);
2323
2324       continue_chatting = (csp->config->feature_flags
2325          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2326          && (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2327          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2328          && (csp->cfd != JB_INVALID_SOCKET)
2329          && (csp->sfd != JB_INVALID_SOCKET)
2330          && socket_is_still_usable(csp->sfd);
2331
2332       if (continue_chatting)
2333       {
2334          log_error(LOG_LEVEL_CONNECT,
2335             "Waiting for the next client request. "
2336             "Keeping the server socket %d to %s open.",
2337             csp->sfd, csp->server_connection.host);
2338
2339          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2340             && data_is_available(csp->cfd, (int)csp->server_connection.keep_alive_timeout)
2341             && socket_is_still_usable(csp->cfd))
2342          {
2343             log_error(LOG_LEVEL_CONNECT, "Client request arrived in "
2344                "time or the client closed the connection.");
2345             /*
2346              * Get the csp in a mostly vergin state again.
2347              * XXX: Should be done elsewhere.
2348              */
2349             csp->content_type = 0;
2350             csp->content_length = 0;
2351             csp->expected_content_length = 0;
2352             list_remove_all(csp->headers);
2353             freez(csp->iob->buf);
2354             memset(csp->iob, 0, sizeof(csp->iob));
2355             freez(csp->error_message);
2356             free_http_request(csp->http);
2357             destroy_list(csp->headers);
2358             destroy_list(csp->tags);
2359             free_current_action(csp->action);
2360             if (NULL != csp->fwd)
2361             {
2362                unload_forward_spec(csp->fwd);
2363                csp->fwd = NULL;
2364             }
2365
2366             /* XXX: Store per-connection flags someplace else. */
2367             csp->flags = CSP_FLAG_ACTIVE | (csp->flags & CSP_FLAG_TOGGLED_ON);
2368          }
2369          else
2370          {
2371             log_error(LOG_LEVEL_CONNECT,
2372                "No additional client request received in time.");
2373             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
2374             {
2375                remember_connection(csp->sfd, csp->http,
2376                   forward_url(csp, csp->http),
2377                   csp->server_connection.keep_alive_timeout);
2378                csp->sfd = JB_INVALID_SOCKET;
2379                close_socket(csp->cfd);
2380                csp->cfd = JB_INVALID_SOCKET;
2381                privoxy_mutex_lock(&connection_reuse_mutex);
2382                if (!monitor_thread_running)
2383                {
2384                   monitor_thread_running = 1;
2385                   privoxy_mutex_unlock(&connection_reuse_mutex);
2386                   wait_for_alive_connections();
2387                   privoxy_mutex_lock(&connection_reuse_mutex);
2388                   monitor_thread_running = 0;
2389                }
2390                privoxy_mutex_unlock(&connection_reuse_mutex);
2391             }
2392             break;
2393          }
2394       }
2395       else if (csp->sfd != JB_INVALID_SOCKET)
2396       {
2397          log_error(LOG_LEVEL_CONNECT,
2398             "The connection on server socket %d to %s isn't reusable. "
2399             "Closing.", csp->sfd, csp->server_connection.host);
2400       }
2401    } while (continue_chatting);
2402
2403    mark_connection_closed(&csp->server_connection);
2404 #else
2405    chat(csp);
2406 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2407
2408    if (csp->sfd != JB_INVALID_SOCKET)
2409    {
2410 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2411       forget_connection(csp->sfd);
2412 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2413       close_socket(csp->sfd);
2414    }
2415
2416    if (csp->cfd != JB_INVALID_SOCKET)
2417    {
2418       close_socket(csp->cfd);
2419    }
2420
2421    csp->flags &= ~CSP_FLAG_ACTIVE;
2422
2423 }
2424
2425
2426 #ifdef __BEOS__
2427 /*********************************************************************
2428  *
2429  * Function    :  server_thread
2430  *
2431  * Description :  We only exist to call `serve' in a threaded environment.
2432  *
2433  * Parameters  :
2434  *          1  :  data = Current client state (buffers, headers, etc...)
2435  *
2436  * Returns     :  Always 0.
2437  *
2438  *********************************************************************/
2439 static int32 server_thread(void *data)
2440 {
2441    serve((struct client_state *) data);
2442    return 0;
2443
2444 }
2445 #endif
2446
2447
2448 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2449 /*********************************************************************
2450  *
2451  * Function    :  usage
2452  *
2453  * Description :  Print usage info & exit.
2454  *
2455  * Parameters  :  Pointer to argv[0] for identifying ourselves
2456  *
2457  * Returns     :  No. ,-)
2458  *
2459  *********************************************************************/
2460 static void usage(const char *myname)
2461 {
2462    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2463           "Usage: %s "
2464 #if defined(unix)
2465           "[--chroot] "
2466 #endif /* defined(unix) */
2467           "[--help] "
2468 #if defined(unix)
2469           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2470 #endif /* defined(unix) */
2471           "[--version] [configfile]\n"
2472           "Aborting\n", myname);
2473
2474    exit(2);
2475
2476 }
2477 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2478
2479
2480 #ifdef MUTEX_LOCKS_AVAILABLE
2481 /*********************************************************************
2482  *
2483  * Function    :  privoxy_mutex_lock
2484  *
2485  * Description :  Locks a mutex.
2486  *
2487  * Parameters  :
2488  *          1  :  mutex = The mutex to lock.
2489  *
2490  * Returns     :  Void. May exit in case of errors.
2491  *
2492  *********************************************************************/
2493 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2494 {
2495 #ifdef FEATURE_PTHREAD
2496    int err = pthread_mutex_lock(mutex);
2497    if (err)
2498    {
2499       if (mutex != &log_mutex)
2500       {
2501          log_error(LOG_LEVEL_FATAL,
2502             "Mutex locking failed: %s.\n", strerror(err));
2503       }
2504       exit(1);
2505    }
2506 #else
2507    EnterCriticalSection(mutex);
2508 #endif /* def FEATURE_PTHREAD */
2509 }
2510
2511
2512 /*********************************************************************
2513  *
2514  * Function    :  privoxy_mutex_unlock
2515  *
2516  * Description :  Unlocks a mutex.
2517  *
2518  * Parameters  :
2519  *          1  :  mutex = The mutex to unlock.
2520  *
2521  * Returns     :  Void. May exit in case of errors.
2522  *
2523  *********************************************************************/
2524 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2525 {
2526 #ifdef FEATURE_PTHREAD
2527    int err = pthread_mutex_unlock(mutex);
2528    if (err)
2529    {
2530       if (mutex != &log_mutex)
2531       {
2532          log_error(LOG_LEVEL_FATAL,
2533             "Mutex unlocking failed: %s.\n", strerror(err));
2534       }
2535       exit(1);
2536    }
2537 #else
2538    LeaveCriticalSection(mutex);
2539 #endif /* def FEATURE_PTHREAD */
2540 }
2541
2542
2543 /*********************************************************************
2544  *
2545  * Function    :  privoxy_mutex_init
2546  *
2547  * Description :  Prepares a mutex.
2548  *
2549  * Parameters  :
2550  *          1  :  mutex = The mutex to initialize.
2551  *
2552  * Returns     :  Void. May exit in case of errors.
2553  *
2554  *********************************************************************/
2555 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2556 {
2557 #ifdef FEATURE_PTHREAD
2558    int err = pthread_mutex_init(mutex, 0);
2559    if (err)
2560    {
2561       printf("Fatal error. Mutex initialization failed: %s.\n",
2562          strerror(err));
2563       exit(1);
2564    }
2565 #else
2566    InitializeCriticalSection(mutex);
2567 #endif /* def FEATURE_PTHREAD */
2568 }
2569 #endif /* def MUTEX_LOCKS_AVAILABLE */
2570
2571 /*********************************************************************
2572  *
2573  * Function    :  initialize_mutexes
2574  *
2575  * Description :  Prepares mutexes if mutex support is available.
2576  *
2577  * Parameters  :  None
2578  *
2579  * Returns     :  Void, exits in case of errors.
2580  *
2581  *********************************************************************/
2582 static void initialize_mutexes(void)
2583 {
2584 #ifdef MUTEX_LOCKS_AVAILABLE
2585    /*
2586     * Prepare global mutex semaphores
2587     */
2588    privoxy_mutex_init(&log_mutex);
2589    privoxy_mutex_init(&log_init_mutex);
2590    privoxy_mutex_init(&connection_reuse_mutex);
2591
2592    /*
2593     * XXX: The assumptions below are a bit naive
2594     * and can cause locks that aren't necessary.
2595     *
2596     * For example older FreeBSD versions (< 6.x?)
2597     * have no gethostbyname_r, but gethostbyname is
2598     * thread safe.
2599     */
2600 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2601    privoxy_mutex_init(&resolver_mutex);
2602 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2603    /*
2604     * XXX: should we use a single mutex for
2605     * localtime() and gmtime() as well?
2606     */
2607 #ifndef HAVE_GMTIME_R
2608    privoxy_mutex_init(&gmtime_mutex);
2609 #endif /* ndef HAVE_GMTIME_R */
2610
2611 #ifndef HAVE_LOCALTIME_R
2612    privoxy_mutex_init(&localtime_mutex);
2613 #endif /* ndef HAVE_GMTIME_R */
2614
2615 #ifndef HAVE_RANDOM
2616    privoxy_mutex_init(&rand_mutex);
2617 #endif /* ndef HAVE_RANDOM */
2618 #endif /* def MUTEX_LOCKS_AVAILABLE */
2619 }
2620
2621
2622 /*********************************************************************
2623  *
2624  * Function    :  main
2625  *
2626  * Description :  Load the config file and start the listen loop.
2627  *                This function is a lot more *sane* with the `load_config'
2628  *                and `listen_loop' functions; although it stills does
2629  *                a *little* too much for my taste.
2630  *
2631  * Parameters  :
2632  *          1  :  argc = Number of parameters (including $0).
2633  *          2  :  argv = Array of (char *)'s to the parameters.
2634  *
2635  * Returns     :  1 if : can't open config file, unrecognized directive,
2636  *                stats requested in multi-thread mode, can't open the
2637  *                log file, can't open the jar file, listen port is invalid,
2638  *                any load fails, and can't bind port.
2639  *
2640  *                Else main never returns, the process must be signaled
2641  *                to terminate execution.  Or, on Windows, use the
2642  *                "File", "Exit" menu option.
2643  *
2644  *********************************************************************/
2645 #ifdef __MINGW32__
2646 int real_main(int argc, const char *argv[])
2647 #else
2648 int main(int argc, const char *argv[])
2649 #endif
2650 {
2651    int argc_pos = 0;
2652    unsigned int random_seed;
2653 #ifdef unix
2654    struct passwd *pw = NULL;
2655    struct group *grp = NULL;
2656    char *p;
2657    int do_chroot = 0;
2658    char *pre_chroot_nslookup_to_load_resolver = NULL;
2659 #endif
2660
2661    Argc = argc;
2662    Argv = argv;
2663
2664    configfile =
2665 #if !defined(_WIN32)
2666    "config"
2667 #else
2668    "config.txt"
2669 #endif
2670       ;
2671
2672    /* Prepare mutexes if supported and necessary. */
2673    initialize_mutexes();
2674
2675    /* Enable logging until further notice. */
2676    init_log_module();
2677
2678    /*
2679     * Parse the command line arguments
2680     *
2681     * XXX: simply printing usage information in case of
2682     * invalid arguments isn't particularly user friendly.
2683     */
2684    while (++argc_pos < argc)
2685    {
2686 #ifdef _WIN32
2687       /* Check to see if the service must be installed or uninstalled */
2688       if (strncmp(argv[argc_pos], "--install", 9) == 0)
2689       {
2690          const char *pName = argv[argc_pos] + 9;
2691          if (*pName == ':')
2692             pName++;
2693          exit( (install_service(pName)) ? 0 : 1 );
2694       }
2695       else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2696       {
2697          const char *pName = argv[argc_pos] + 11;
2698          if (*pName == ':')
2699             pName++;
2700          exit((uninstall_service(pName)) ? 0 : 1);
2701       }
2702       else if (strcmp(argv[argc_pos], "--service" ) == 0)
2703       {
2704          bRunAsService = TRUE;
2705          w32_set_service_cwd();
2706          atexit(w32_service_exit_notify);
2707       }
2708       else
2709 #endif /* defined(_WIN32) */
2710
2711
2712 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2713
2714       if (strcmp(argv[argc_pos], "--help") == 0)
2715       {
2716          usage(argv[0]);
2717       }
2718
2719       else if(strcmp(argv[argc_pos], "--version") == 0)
2720       {
2721          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2722          exit(0);
2723       }
2724
2725 #if defined(unix)
2726
2727       else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2728       {
2729          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2730          no_daemon = 1;
2731       }
2732
2733       else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2734       {
2735          if (++argc_pos == argc) usage(argv[0]);
2736          pidfile = strdup(argv[argc_pos]);
2737       }
2738
2739       else if (strcmp(argv[argc_pos], "--user" ) == 0)
2740       {
2741          if (++argc_pos == argc) usage(argv[argc_pos]);
2742
2743          if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2744          {
2745             *p++ = '\0';
2746             if (NULL == (grp = getgrnam(p)))
2747             {
2748                log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2749             }
2750          }
2751
2752          if (NULL == (pw = getpwnam(argv[argc_pos])))
2753          {
2754             log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2755          }
2756
2757          if (p != NULL) *--p = '\0';
2758       }
2759
2760       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
2761       {
2762          if (++argc_pos == argc) usage(argv[0]);
2763          pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
2764       }
2765
2766       else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2767       {
2768          do_chroot = 1;
2769       }
2770 #endif /* defined(unix) */
2771
2772       else if (argc_pos + 1 != argc)
2773       {
2774          /*
2775           * This is neither the last command line
2776           * option, nor was it recognized before,
2777           * therefore it must be invalid.
2778           */
2779          usage(argv[0]);
2780       }
2781       else
2782
2783 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2784       {
2785          configfile = argv[argc_pos];
2786       }
2787
2788    } /* -END- while (more arguments) */
2789
2790    show_version(Argv[0]);
2791
2792 #if defined(unix)
2793    if ( *configfile != '/' )
2794    {
2795       char cwd[BUFFER_SIZE];
2796       char *abs_file;
2797       size_t abs_file_size; 
2798
2799       /* make config-filename absolute here */
2800       if (NULL == getcwd(cwd, sizeof(cwd)))
2801       {
2802          perror("failed to get current working directory");
2803          exit( 1 );
2804       }
2805
2806       /* XXX: why + 5? */
2807       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2808       basedir = strdup(cwd);
2809
2810       if (NULL == basedir ||
2811           NULL == (abs_file = malloc(abs_file_size)))
2812       {
2813          perror("malloc failed");
2814          exit( 1 );
2815       }
2816       strlcpy(abs_file, basedir, abs_file_size);
2817       strlcat(abs_file, "/", abs_file_size );
2818       strlcat(abs_file, configfile, abs_file_size);
2819       configfile = abs_file;
2820    }
2821 #endif /* defined unix */
2822
2823
2824    files->next = NULL;
2825    clients->next = NULL;
2826
2827    /* XXX: factor out initialising after the next stable release. */
2828 #ifdef AMIGA
2829    InitAmiga();
2830 #elif defined(_WIN32)
2831    InitWin32();
2832 #endif
2833
2834    random_seed = (unsigned int)time(NULL);
2835 #ifdef HAVE_RANDOM
2836    srandom(random_seed);
2837 #else
2838    srand(random_seed);
2839 #endif /* ifdef HAVE_RANDOM */
2840
2841    /*
2842     * Unix signal handling
2843     *
2844     * Catch the abort, interrupt and terminate signals for a graceful exit
2845     * Catch the hangup signal so the errlog can be reopened.
2846     * Ignore the broken pipe signals (FIXME: Why?)
2847     */
2848 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2849 {
2850    int idx;
2851    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2852    const int ignored_signals[] = { SIGPIPE, 0 };
2853
2854    for (idx = 0; catched_signals[idx] != 0; idx++)
2855    {
2856 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */ 
2857       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2858 #else
2859       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2860 #endif /* ifdef sun */
2861       {
2862          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2863       }
2864    }
2865
2866    for (idx = 0; ignored_signals[idx] != 0; idx++)
2867    {
2868       if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2869       {
2870          log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2871       }
2872    }
2873
2874 }
2875 #else /* ifdef _WIN32 */
2876 # ifdef _WIN_CONSOLE
2877    /*
2878     * We *are* in a windows console app.
2879     * Print a verbose messages about FAQ's and such
2880     */
2881    printf("%s", win32_blurb);
2882 # endif /* def _WIN_CONSOLE */
2883 #endif /* def _WIN32 */
2884
2885
2886    /* Initialize the CGI subsystem */
2887    cgi_init_error_messages();
2888
2889    /*
2890     * If runnig on unix and without the --nodaemon
2891     * option, become a daemon. I.e. fork, detach
2892     * from tty and get process group leadership
2893     */
2894 #if defined(unix)
2895 {
2896    pid_t pid = 0;
2897 #if 0
2898    int   fd;
2899 #endif
2900
2901    if (!no_daemon)
2902    {
2903       pid  = fork();
2904
2905       if ( pid < 0 ) /* error */
2906       {
2907          perror("fork");
2908          exit( 3 );
2909       }
2910       else if ( pid != 0 ) /* parent */
2911       {
2912          int status;
2913          pid_t wpid;
2914          /*
2915           * must check for errors
2916           * child died due to missing files aso
2917           */
2918          sleep( 1 );
2919          wpid = waitpid( pid, &status, WNOHANG );
2920          if ( wpid != 0 )
2921          {
2922             exit( 1 );
2923          }
2924          exit( 0 );
2925       }
2926       /* child */
2927 #if 1
2928       /* Should be more portable, but not as well tested */
2929       setsid();
2930 #else /* !1 */
2931 #ifdef __FreeBSD__
2932       setpgrp(0,0);
2933 #else /* ndef __FreeBSD__ */
2934       setpgrp();
2935 #endif /* ndef __FreeBSD__ */
2936       fd = open("/dev/tty", O_RDONLY);
2937       if ( fd )
2938       {
2939          /* no error check here */
2940          ioctl( fd, TIOCNOTTY,0 );
2941          close ( fd );
2942       }
2943 #endif /* 1 */
2944       /*
2945        * stderr (fd 2) will be closed later on,
2946        * when the config file has been parsed.
2947        */
2948
2949       close( 0 );
2950       close( 1 );
2951       chdir("/");
2952
2953    } /* -END- if (!no_daemon) */
2954
2955    /*
2956     * As soon as we have written the PID file, we can switch
2957     * to the user and group ID indicated by the --user option
2958     */
2959    write_pid_file();
2960
2961    if (NULL != pw)
2962    {
2963       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2964       {
2965          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2966       }
2967       if (NULL != grp)
2968       {
2969          if (setgroups(1, &grp->gr_gid))
2970          {
2971             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
2972          }
2973       }
2974       else if (initgroups(pw->pw_name, pw->pw_gid))
2975       {
2976          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
2977       }
2978       if (do_chroot)
2979       {
2980          if (!pw->pw_dir)
2981          {
2982             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2983          }
2984          /* Read the time zone file from /etc before doing chroot. */
2985          tzset();
2986          if (NULL != pre_chroot_nslookup_to_load_resolver
2987              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
2988          {
2989             /* Initialize resolver library. */
2990             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
2991          }
2992          if (chroot(pw->pw_dir) < 0)
2993          {
2994             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2995          }
2996          if (chdir ("/"))
2997          {
2998             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2999          }
3000       }
3001       if (setuid(pw->pw_uid))
3002       {
3003          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3004       }
3005       if (do_chroot)
3006       {
3007          char putenv_dummy[64];
3008
3009          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3010          if (putenv(putenv_dummy) != 0)
3011          {
3012             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3013          }                
3014
3015          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3016          if (putenv(putenv_dummy) != 0)
3017          {
3018             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3019          }
3020       }
3021    }
3022    else if (do_chroot)
3023    {
3024       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3025    }
3026 }
3027 #endif /* defined unix */
3028
3029 #ifdef _WIN32
3030    /* This will be FALSE unless the command line specified --service
3031     */
3032    if (bRunAsService)
3033    {
3034       /* Yup, so now we must attempt to establish a connection 
3035        * with the service dispatcher. This will only work if this
3036        * process was launched by the service control manager to
3037        * actually run as a service. If this isn't the case, i've
3038        * known it take around 30 seconds or so for the call to return.
3039        */
3040
3041       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3042       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3043       {
3044          /* Service has run, and at this point is now being stopped, so just return */
3045          return 0;
3046       }
3047
3048 #ifdef _WIN_CONSOLE
3049       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3050 #endif
3051       /* An error occurred. Usually it's because --service was wrongly specified
3052        * and we were unable to connect to the Service Control Dispatcher because
3053        * it wasn't expecting us and is therefore not listening.
3054        *
3055        * For now, just continue below to call the listen_loop function.
3056        */
3057    }
3058 #endif /* def _WIN32 */
3059
3060    listen_loop();
3061
3062    /* NOTREACHED */
3063    return(-1);
3064
3065 }
3066
3067
3068 /*********************************************************************
3069  *
3070  * Function    :  bind_port_helper
3071  *
3072  * Description :  Bind the listen port.  Handles logging, and aborts
3073  *                on failure.
3074  *
3075  * Parameters  :
3076  *          1  :  config = Privoxy configuration.  Specifies port
3077  *                         to bind to.
3078  *
3079  * Returns     :  Port that was opened.
3080  *
3081  *********************************************************************/
3082 static jb_socket bind_port_helper(struct configuration_spec * config)
3083 {
3084    int result;
3085    jb_socket bfd;
3086
3087    if (config->haddr == NULL)
3088    {
3089       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3090                 config->hport);
3091    }
3092    else
3093    {
3094       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3095                 config->hport, config->haddr);
3096    }
3097
3098    result = bind_port(config->haddr, config->hport, &bfd);
3099
3100    if (result < 0)
3101    {
3102       switch(result)
3103       {
3104          case -3 :
3105             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3106                "There may be another Privoxy or some other "
3107                "proxy running on port %d",
3108                (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3109                       config->hport, config->hport);
3110
3111          case -2 :
3112             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: " 
3113                "The hostname is not resolvable",
3114                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3115
3116          default :
3117             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3118                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3119       }
3120
3121       /* shouldn't get here */
3122       return JB_INVALID_SOCKET;
3123    }
3124
3125    config->need_bind = 0;
3126
3127    return bfd;
3128 }
3129
3130
3131 #ifdef _WIN32
3132 /* Without this simple workaround we get this compiler warning from _beginthread
3133  *     warning C4028: formal parameter 1 different from declaration
3134  */
3135 void w32_service_listen_loop(void *p)
3136 {
3137    listen_loop();
3138 }
3139 #endif /* def _WIN32 */
3140
3141
3142 /*********************************************************************
3143  *
3144  * Function    :  listen_loop
3145  *
3146  * Description :  bind the listen port and enter a "FOREVER" listening loop.
3147  *
3148  * Parameters  :  N/A
3149  *
3150  * Returns     :  Never.
3151  *
3152  *********************************************************************/
3153 static void listen_loop(void)
3154 {
3155    struct client_state *csp = NULL;
3156    jb_socket bfd;
3157    struct configuration_spec *config;
3158    unsigned int active_threads = 0;
3159
3160    config = load_config();
3161
3162 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3163    /*
3164     * XXX: Should be relocated once it no
3165     * longer needs to emit log messages.
3166     */
3167    initialize_reusable_connections();
3168 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3169
3170    bfd = bind_port_helper(config);
3171
3172 #ifdef FEATURE_GRACEFUL_TERMINATION
3173    while (!g_terminate)
3174 #else
3175    for (;;)
3176 #endif
3177    {
3178 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3179       while (waitpid(-1, NULL, WNOHANG) > 0)
3180       {
3181          /* zombie children */
3182       }
3183 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3184
3185       /*
3186        * Free data that was used by died threads
3187        */
3188       active_threads = sweep();
3189
3190 #if defined(unix)
3191       /*
3192        * Re-open the errlog after HUP signal
3193        */
3194       if (received_hup_signal)
3195       {
3196          if (NULL != config->logfile)
3197          {
3198             init_error_log(Argv[0], config->logfile);
3199          }
3200          received_hup_signal = 0;
3201       }
3202 #endif
3203
3204       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3205       {
3206          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3207          continue;
3208       }
3209
3210       csp->flags |= CSP_FLAG_ACTIVE;
3211       csp->sfd    = JB_INVALID_SOCKET;
3212
3213       csp->config = config = load_config();
3214
3215       if ( config->need_bind )
3216       {
3217          /*
3218           * Since we were listening to the "old port", we will not see
3219           * a "listen" param change until the next request.  So, at
3220           * least 1 more request must be made for us to find the new
3221           * setting.  I am simply closing the old socket and binding the
3222           * new one.
3223           *
3224           * Which-ever is correct, we will serve 1 more page via the
3225           * old settings.  This should probably be a "show-proxy-args"
3226           * request.  This should not be a so common of an operation
3227           * that this will hurt people's feelings.
3228           */
3229
3230          close_socket(bfd);
3231
3232          bfd = bind_port_helper(config);
3233       }
3234
3235       log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3236
3237       if (!accept_connection(csp, bfd))
3238       {
3239          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3240
3241 #ifdef AMIGA
3242          if(!childs)
3243          {
3244             exit(1);
3245          }
3246 #endif
3247          freez(csp);
3248          continue;
3249       }
3250       else
3251       {
3252          log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3253       }
3254
3255 #ifdef FEATURE_TOGGLE
3256       if (global_toggle_state)
3257 #endif /* def FEATURE_TOGGLE */
3258       {
3259          csp->flags |= CSP_FLAG_TOGGLED_ON;
3260       }
3261
3262       if (run_loader(csp))
3263       {
3264          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3265          /* Never get here - LOG_LEVEL_FATAL causes program exit */
3266       }
3267
3268 #ifdef FEATURE_ACL
3269       if (block_acl(NULL,csp))
3270       {
3271          log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3272          close_socket(csp->cfd);
3273          freez(csp->ip_addr_str);
3274          freez(csp);
3275          continue;
3276       }
3277 #endif /* def FEATURE_ACL */
3278
3279       if ((0 != config->max_client_connections)
3280          && (active_threads >= config->max_client_connections))
3281       {
3282          log_error(LOG_LEVEL_CONNECT,
3283             "Rejecting connection from %s. Maximum number of connections reached.",
3284             csp->ip_addr_str);
3285          write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3286             strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3287          close_socket(csp->cfd);
3288          freez(csp->ip_addr_str);
3289          freez(csp);
3290          continue;
3291       }
3292
3293       /* add it to the list of clients */
3294       csp->next = clients->next;
3295       clients->next = csp;
3296
3297       if (config->multi_threaded)
3298       {
3299          int child_id;
3300
3301 /* this is a switch () statment in the C preprocessor - ugh */
3302 #undef SELECTED_ONE_OPTION
3303
3304 /* Use Pthreads in preference to native code */
3305 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3306 #define SELECTED_ONE_OPTION
3307          {
3308             pthread_t the_thread;
3309             pthread_attr_t attrs;
3310
3311             pthread_attr_init(&attrs);
3312             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3313             errno = pthread_create(&the_thread, &attrs,
3314                (void * (*)(void *))serve, csp);
3315             child_id = errno ? -1 : 0;
3316             pthread_attr_destroy(&attrs);
3317          }
3318 #endif
3319
3320 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3321 #define SELECTED_ONE_OPTION
3322          child_id = _beginthread(
3323             (void (*)(void *))serve,
3324             64 * 1024,
3325             csp);
3326 #endif
3327
3328 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3329 #define SELECTED_ONE_OPTION
3330          child_id = _beginthread(
3331             (void(* _Optlink)(void*))serve,
3332             NULL,
3333             64 * 1024,
3334             csp);
3335 #endif
3336
3337 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3338 #define SELECTED_ONE_OPTION
3339          {
3340             thread_id tid = spawn_thread
3341                (server_thread, "server", B_NORMAL_PRIORITY, csp);
3342
3343             if ((tid >= 0) && (resume_thread(tid) == B_OK))
3344             {
3345                child_id = (int) tid;
3346             }
3347             else
3348             {
3349                child_id = -1;
3350             }
3351          }
3352 #endif
3353
3354 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3355 #define SELECTED_ONE_OPTION
3356          csp->cfd = ReleaseSocket(csp->cfd, -1);
3357          
3358 #ifdef __amigaos4__
3359          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3360                                            NP_Output, Output(),
3361                                            NP_CloseOutput, FALSE,
3362                                            NP_Name, (ULONG)"privoxy child",
3363                                            NP_Child, TRUE,
3364                                            TAG_DONE);
3365 #else
3366          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3367                                            NP_Output, Output(),
3368                                            NP_CloseOutput, FALSE,
3369                                            NP_Name, (ULONG)"privoxy child",
3370                                            NP_StackSize, 200*1024,
3371                                            TAG_DONE);
3372 #endif
3373          if(0 != child_id)
3374          {
3375             childs++;
3376             ((struct Task *)child_id)->tc_UserData = csp;
3377             Signal((struct Task *)child_id, SIGF_SINGLE);
3378             Wait(SIGF_SINGLE);
3379          }
3380 #endif
3381
3382 #if !defined(SELECTED_ONE_OPTION)
3383          child_id = fork();
3384
3385          /* This block is only needed when using fork().
3386           * When using threads, the server thread was
3387           * created and run by the call to _beginthread().
3388           */
3389          if (child_id == 0)   /* child */
3390          {
3391             int rc = 0;
3392 #ifdef FEATURE_TOGGLE
3393             int inherited_toggle_state = global_toggle_state;
3394 #endif /* def FEATURE_TOGGLE */
3395
3396             serve(csp);
3397
3398             /* 
3399              * If we've been toggled or we've blocked the request, tell Mom
3400              */
3401
3402 #ifdef FEATURE_TOGGLE
3403             if (inherited_toggle_state != global_toggle_state)
3404             {
3405                rc |= RC_FLAG_TOGGLED;
3406             }
3407 #endif /* def FEATURE_TOGGLE */
3408
3409 #ifdef FEATURE_STATISTICS  
3410             if (csp->flags & CSP_FLAG_REJECTED)
3411             {
3412                rc |= RC_FLAG_BLOCKED;
3413             }
3414 #endif /* ndef FEATURE_STATISTICS */
3415
3416             _exit(rc);
3417          }
3418          else if (child_id > 0) /* parent */
3419          {
3420             /* in a fork()'d environment, the parent's
3421              * copy of the client socket and the CSP
3422              * are not used.
3423              */
3424             int child_status;
3425 #if !defined(_WIN32) && !defined(__CYGWIN__)
3426
3427             wait( &child_status );
3428
3429             /* 
3430              * Evaluate child's return code: If the child has
3431              *  - been toggled, toggle ourselves
3432              *  - blocked its request, bump up the stats counter
3433              */
3434
3435 #ifdef FEATURE_TOGGLE
3436             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3437             {
3438                global_toggle_state = !global_toggle_state;
3439             }
3440 #endif /* def FEATURE_TOGGLE */
3441
3442 #ifdef FEATURE_STATISTICS
3443             urls_read++;
3444             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3445             {
3446                urls_rejected++;
3447             }
3448 #endif /* def FEATURE_STATISTICS */ 
3449
3450 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3451             close_socket(csp->cfd);
3452             csp->flags &= ~CSP_FLAG_ACTIVE;
3453          }
3454 #endif
3455
3456 #undef SELECTED_ONE_OPTION
3457 /* end of cpp switch () */
3458
3459          if (child_id < 0)
3460          {
3461             /*
3462              * Spawning the child failed, assume it's because
3463              * there are too many children running already.
3464              * XXX: If you assume ...
3465              */
3466             log_error(LOG_LEVEL_ERROR,
3467                "Unable to take any additional connections: %E");
3468             write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3469                strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3470             close_socket(csp->cfd);
3471             csp->flags &= ~CSP_FLAG_ACTIVE;
3472          }
3473       }
3474       else
3475       {
3476          serve(csp);
3477       }
3478    }
3479
3480    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3481
3482    /* Clean up.  Aim: free all memory (no leaks) */
3483 #ifdef FEATURE_GRACEFUL_TERMINATION
3484
3485    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3486
3487    unload_current_config_file();
3488    unload_current_actions_file();
3489    unload_current_re_filterfile();
3490 #ifdef FEATURE_TRUST
3491    unload_current_trust_file();
3492 #endif
3493
3494    if (config->multi_threaded)
3495    {
3496       int i = 60;
3497       do
3498       {
3499          sleep(1);
3500          sweep();
3501       } while ((clients->next != NULL) && (--i > 0));
3502
3503       if (i <= 0)
3504       {
3505          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3506       }
3507    }
3508    sweep();
3509    sweep();
3510
3511 #if defined(unix)
3512    freez(basedir);
3513 #endif
3514    freez(configfile);
3515
3516 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3517    /* Cleanup - remove taskbar icon etc. */
3518    TermLogWindow();
3519 #endif
3520
3521    exit(0);
3522 #endif /* FEATURE_GRACEFUL_TERMINATION */
3523
3524 }
3525
3526
3527 /*
3528   Local Variables:
3529   tab-width: 3
3530   end:
3531 */