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