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