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