nit: put all the '--enable-xxx' options together
[privoxy.git] / jcc.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
4  *
5  * Purpose     :  Main file.  Contains main() method, main loop, and
6  *                the main connection-handling function.
7  *
8  * Copyright   :  Written by and Copyright (C) 2001-2021 the
9  *                Privoxy team. https://www.privoxy.org/
10  *
11  *                Based on the Internet Junkbuster originally written
12  *                by and Copyright (C) 1997 Anonymous Coders and
13  *                Junkbusters Corporation.  http://www.junkbusters.com
14  *
15  *                This program is free software; you can redistribute it
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <stdio.h>
39 #include <sys/types.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <assert.h>
46
47 #ifdef _WIN32
48 # ifndef FEATURE_PTHREAD
49 #  ifndef STRICT
50 #   define STRICT
51 #  endif
52 #  include <winsock2.h>
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 # include <unistd.h>
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
70
71 #ifdef sun
72 #include <sys/termios.h>
73 #endif /* sun */
74
75 #ifdef unix
76 #include <pwd.h>
77 #include <grp.h>
78 #endif
79
80 # include <signal.h>
81
82 # ifdef __BEOS__
83 #  include <socket.h>  /* BeOS has select() for sockets only. */
84 #  include <OS.h>      /* declarations for threads and stuff. */
85 # endif
86
87 #ifdef HAVE_POLL
88 #ifdef __GLIBC__
89 #include <sys/poll.h>
90 #else
91 #include <poll.h>
92 #endif /* def __GLIBC__ */
93 #else
94 # ifndef FD_ZERO
95 #  include <select.h>
96 # endif
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
99
100 #endif
101
102 #include "project.h"
103 #include "list.h"
104 #include "jcc.h"
105 #ifdef FEATURE_HTTPS_INSPECTION
106 #include "ssl.h"
107 #endif
108 #include "filters.h"
109 #include "loaders.h"
110 #include "parsers.h"
111 #include "miscutil.h"
112 #include "errlog.h"
113 #include "jbsockets.h"
114 #include "gateway.h"
115 #include "actions.h"
116 #include "cgi.h"
117 #include "loadcfg.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
121 #endif
122
123 int daemon_mode = 1;
124 struct client_states clients[1];
125 struct file_list     files[1];
126
127 #ifdef FEATURE_STATISTICS
128 int urls_read     = 0;     /* total nr of urls read inc rejected */
129 int urls_rejected = 0;     /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
131
132 #ifdef FEATURE_GRACEFUL_TERMINATION
133 int g_terminate = 0;
134 #endif
135
136 #if !defined(_WIN32)
137 static void sig_handler(int the_signal);
138 #endif
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
154 #endif
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
161
162 #ifdef __BEOS__
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
165
166 #ifdef _WIN32
167 #define sleep(N)  Sleep(((N) * 1000))
168 #endif
169
170 #ifdef FUZZ
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
173 #endif
174
175 #ifdef MUTEX_LOCKS_AVAILABLE
176 /*
177  * XXX: Does the locking stuff really belong in this file?
178  */
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
182
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
186 #endif
187
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
190 #endif
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
193 #endif
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
197 #endif
198
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
202
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
206
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
210
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
214
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
216
217 #if defined(unix)
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
222
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225    "HTTP/1.1 200 Connection established\r\n\r\n";
226
227 static const char CHEADER[] =
228    "HTTP/1.1 400 Invalid header received from client\r\n"
229    "Content-Type: text/plain\r\n"
230    "Connection: close\r\n\r\n"
231    "Invalid header received from client.\n";
232
233 static const char FTP_RESPONSE[] =
234    "HTTP/1.1 400 Invalid request received from client\r\n"
235    "Content-Type: text/plain\r\n"
236    "Connection: close\r\n\r\n"
237    "Invalid request. Privoxy doesn't support FTP.\n";
238
239 static const char GOPHER_RESPONSE[] =
240    "HTTP/1.1 400 Invalid request received from client\r\n"
241    "Content-Type: text/plain\r\n"
242    "Connection: close\r\n\r\n"
243    "Invalid request. Privoxy doesn't support gopher.\n";
244
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247    "HTTP/1.1 400 Bad request received from client\r\n"
248    "Content-Type: text/plain\r\n"
249    "Connection: close\r\n\r\n"
250    "Bad request. Privoxy was unable to extract the destination.\n";
251
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254    "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255    "Content-Type: text/plain\r\n"
256    "Connection: close\r\n\r\n"
257    "Bad response. The server or forwarder response doesn't look like HTTP.\n";
258
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261    "HTTP/1.1 400 Malformed request after rewriting\r\n"
262    "Content-Type: text/plain\r\n"
263    "Connection: close\r\n\r\n"
264    "Bad request. Messed up with header filters.\n";
265
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267    "HTTP/1.1 503 Too many open connections\r\n"
268    "Content-Type: text/plain\r\n"
269    "Connection: close\r\n\r\n"
270    "Maximum number of open connections reached.\n";
271
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273    "HTTP/1.1 504 Connection timeout\r\n"
274    "Content-Type: text/plain\r\n"
275    "Connection: close\r\n\r\n"
276    "The connection timed out because the client request didn't arrive in time.\n";
277
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279    "HTTP/1.1 400 Failed reading client body\r\n"
280    "Content-Type: text/plain\r\n"
281    "Connection: close\r\n\r\n"
282    "Failed parsing or buffering the chunk-encoded client body.\n";
283
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285    "HTTP/1.1 417 Expecting too much\r\n"
286    "Content-Type: text/plain\r\n"
287    "Connection: close\r\n\r\n"
288    "Privoxy detected an unsupported Expect header value.\n";
289
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
292
293 /* Crunch function flags */
294 #define CF_NO_FLAGS        0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE    1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
299
300 /* A crunch function and its flags */
301 struct cruncher
302 {
303    const crunch_func_ptr cruncher;
304    const int flags;
305 };
306
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
308
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312    { block_url,       CF_COUNT_AS_REJECT },
313 #ifdef FEATURE_TRUST
314    { trust_url,       CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316    { redirect_url,    CF_NO_FLAGS  },
317    { dispatch_cgi,    CF_IGNORE_FORCE},
318    { NULL,            0 }
319 };
320
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323    { block_url,       CF_COUNT_AS_REJECT },
324    { redirect_url,    CF_NO_FLAGS },
325    { NULL,            0 }
326 };
327
328
329 /*
330  * XXX: Don't we really mean
331  *
332  * #if defined(unix)
333  *
334  * here?
335  */
336 #if !defined(_WIN32)
337 /*********************************************************************
338  *
339  * Function    :  sig_handler
340  *
341  * Description :  Signal handler for different signals.
342  *                Exit gracefully on TERM and INT
343  *                or set a flag that will cause the errlog
344  *                to be reopened by the main thread on HUP.
345  *
346  * Parameters  :
347  *          1  :  the_signal = the signal cause this function to call
348  *
349  * Returns     :  -
350  *
351  *********************************************************************/
352 static void sig_handler(int the_signal)
353 {
354    switch(the_signal)
355    {
356       case SIGTERM:
357       case SIGINT:
358          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
359 #if defined(unix)
360          if (pidfile)
361          {
362             unlink(pidfile);
363          }
364 #endif /* unix */
365          exit(the_signal);
366          break;
367
368       case SIGHUP:
369 #if defined(unix)
370          received_hup_signal = 1;
371 #endif
372          break;
373
374       default:
375          /*
376           * We shouldn't be here, unless we catch signals
377           * in main() that we can't handle here!
378           */
379          log_error(LOG_LEVEL_FATAL,
380             "sig_handler: exiting on unexpected signal %d", the_signal);
381    }
382    return;
383
384 }
385 #endif
386
387
388 /*********************************************************************
389  *
390  * Function    :  get_write_delay
391  *
392  * Description :  Parse the delay-response parameter.
393  *
394  * Parameters  :
395  *          1  :  csp = Current client state (buffers, headers, etc...)
396  *
397  * Returns     :  Number of milliseconds to delay writes.
398  *
399  *********************************************************************/
400 static unsigned int get_write_delay(const struct client_state *csp)
401 {
402    unsigned int delay;
403    char *endptr;
404    char *newval;
405
406    if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
407    {
408       return 0;
409    }
410    newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
411
412    delay = (unsigned)strtol(newval, &endptr, 0);
413    if (*endptr != '\0')
414    {
415       log_error(LOG_LEVEL_FATAL,
416          "Invalid delay-response{} parameter: '%s'", newval);
417    }
418
419    return delay;
420
421 }
422
423
424 /*********************************************************************
425  *
426  * Function    :  client_protocol_is_unsupported
427  *
428  * Description :  Checks if the client used a known unsupported
429  *                protocol and deals with it by sending an error
430  *                response.
431  *
432  * Parameters  :
433  *          1  :  csp = Current client state (buffers, headers, etc...)
434  *          2  :  req = the first request line send by the client
435  *
436  * Returns     :  TRUE if an error response has been generated, or
437  *                FALSE if the request doesn't look invalid.
438  *
439  *********************************************************************/
440 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
441 {
442    /*
443     * If it's a FTP or gopher request, we don't support it.
444     *
445     * These checks are better than nothing, but they might
446     * not work in all configurations and some clients might
447     * have problems digesting the answer.
448     *
449     * They should, however, never cause more problems than
450     * Privoxy's old behaviour (returning the misleading HTML
451     * error message:
452     *
453     * "Could not resolve http://(ftp|gopher)://example.org").
454     */
455    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
456    {
457       const char *response = NULL;
458       const char *protocol = NULL;
459
460       if (!strncmpic(req, "GET ftp://", 10))
461       {
462          response = FTP_RESPONSE;
463          protocol = "FTP";
464       }
465       else
466       {
467          response = GOPHER_RESPONSE;
468          protocol = "GOPHER";
469       }
470       log_error(LOG_LEVEL_ERROR,
471          "%s tried to use Privoxy as %s proxy: %s",
472          csp->ip_addr_str, protocol, req);
473       log_error(LOG_LEVEL_CLF,
474          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
475       freez(req);
476
477 #ifdef FEATURE_HTTPS_INSPECTION
478       if (client_use_ssl(csp))
479       {
480          ssl_send_data_delayed(&(csp->ssl_client_attr),
481             (const unsigned char *)response, strlen(response),
482             get_write_delay(csp));
483       }
484       else
485 #endif
486       {
487          write_socket_delayed(csp->cfd, response, strlen(response),
488             get_write_delay(csp));
489       }
490
491       return TRUE;
492    }
493
494    return FALSE;
495 }
496
497
498 /*********************************************************************
499  *
500  * Function    :  client_has_unsupported_expectations
501  *
502  * Description :  Checks if the client used an unsupported expectation
503  *                in which case an error message is delivered.
504  *
505  * Parameters  :
506  *          1  :  csp = Current client state (buffers, headers, etc...)
507  *
508  * Returns     :  TRUE if an error response has been generated, or
509  *                FALSE if the request doesn't look invalid.
510  *
511  *********************************************************************/
512 static int client_has_unsupported_expectations(const struct client_state *csp)
513 {
514    if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
515    {
516       log_error(LOG_LEVEL_ERROR,
517          "Rejecting request from client %s with unsupported Expect header value",
518          csp->ip_addr_str);
519       log_error(LOG_LEVEL_CLF,
520          "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
521       write_socket_delayed(csp->cfd,
522          UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
523          strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
524          get_write_delay(csp));
525
526       return TRUE;
527    }
528
529    return FALSE;
530
531 }
532
533
534 /*********************************************************************
535  *
536  * Function    :  get_request_destination_elsewhere
537  *
538  * Description :  If the client's request was redirected into
539  *                Privoxy without the client's knowledge,
540  *                the request line lacks the destination host.
541  *
542  *                This function tries to get it elsewhere,
543  *                provided accept-intercepted-requests is enabled.
544  *
545  *                "Elsewhere" currently only means "Host: header",
546  *                but in the future we may ask the redirecting
547  *                packet filter to look the destination up.
548  *
549  *                If the destination stays unknown, an error
550  *                response is send to the client and headers
551  *                are freed so that chat() can return directly.
552  *
553  * Parameters  :
554  *          1  :  csp = Current client state (buffers, headers, etc...)
555  *          2  :  headers = a header list
556  *
557  * Returns     :  JB_ERR_OK if the destination is now known, or
558  *                JB_ERR_PARSE if it isn't.
559  *
560  *********************************************************************/
561 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
562 {
563    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
564    {
565       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
566          " Privoxy isn't configured to accept intercepted requests.",
567          csp->ip_addr_str, csp->http->cmd);
568       /* XXX: Use correct size */
569       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
570          csp->ip_addr_str, csp->http->cmd);
571
572       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
573          get_write_delay(csp));
574       destroy_list(headers);
575
576       return JB_ERR_PARSE;
577    }
578    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
579    {
580       /* Split the domain we just got for pattern matching */
581       init_domain_components(csp->http);
582
583       return JB_ERR_OK;
584    }
585    else
586    {
587       /* We can't work without destination. Go spread the news.*/
588
589       /* XXX: Use correct size */
590       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
591          csp->ip_addr_str, csp->http->cmd);
592       log_error(LOG_LEVEL_ERROR,
593          "Privoxy was unable to get the destination for %s's request: %s",
594          csp->ip_addr_str, csp->http->cmd);
595
596       write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
597          strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
598       destroy_list(headers);
599
600       return JB_ERR_PARSE;
601    }
602    /*
603     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
604     * to get the destination IP address, use it as host directly
605     * or do a reverse DNS lookup first.
606     */
607 }
608
609
610 /*********************************************************************
611  *
612  * Function    :  get_server_headers
613  *
614  * Description :  Parses server headers in iob and fills them
615  *                into csp->headers so that they can later be
616  *                handled by sed().
617  *
618  * Parameters  :
619  *          1  :  csp = Current client state (buffers, headers, etc...)
620  *
621  * Returns     :  JB_ERR_OK if everything went fine, or
622  *                JB_ERR_PARSE if the headers were incomplete.
623  *
624  *********************************************************************/
625 static jb_err get_server_headers(struct client_state *csp)
626 {
627    int continue_hack_in_da_house = 0;
628    char * header;
629
630    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
631    {
632       if (header == NULL)
633       {
634          /*
635           * continue hack in da house. Ignore the ending of
636           * this head and continue enlisting header lines.
637           * The reason is described below.
638           */
639          enlist(csp->headers, "");
640          continue_hack_in_da_house = 0;
641          continue;
642       }
643       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
644       {
645          /*
646           * It's a bodyless continue response, don't
647           * stop header parsing after reaching its end.
648           *
649           * As a result Privoxy will concatenate the
650           * next response's head and parse and deliver
651           * the headers as if they belonged to one request.
652           *
653           * The client will separate them because of the
654           * empty line between them.
655           *
656           * XXX: What we're doing here is clearly against
657           * the intended purpose of the continue header,
658           * and under some conditions (HTTP/1.0 client request)
659           * it's a standard violation.
660           *
661           * Anyway, "sort of against the spec" is preferable
662           * to "always getting confused by Continue responses"
663           * (Privoxy's behaviour before this hack was added)
664           */
665          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
666          continue_hack_in_da_house = 1;
667       }
668       else if (*header == '\0')
669       {
670          /*
671           * If the header is empty, but the Continue hack
672           * isn't active, we can assume that we reached the
673           * end of the buffer before we hit the end of the
674           * head.
675           *
676           * Inform the caller an let it decide how to handle it.
677           */
678          return JB_ERR_PARSE;
679       }
680
681       if (JB_ERR_MEMORY == enlist(csp->headers, header))
682       {
683          /*
684           * XXX: Should we quit the request and return a
685           * out of memory error page instead?
686           */
687          log_error(LOG_LEVEL_ERROR,
688             "Out of memory while enlisting server headers. %s lost.",
689             header);
690       }
691       freez(header);
692    }
693
694    return JB_ERR_OK;
695 }
696
697
698 /*********************************************************************
699  *
700  * Function    :  crunch_reason
701  *
702  * Description :  Translates the crunch reason code into a string.
703  *
704  * Parameters  :
705  *          1  :  rsp = a http_response
706  *
707  * Returns     :  A string with the crunch reason or an error description.
708  *
709  *********************************************************************/
710 static const char *crunch_reason(const struct http_response *rsp)
711 {
712    char * reason = NULL;
713
714    assert(rsp != NULL);
715    if (rsp == NULL)
716    {
717       return "Internal error while searching for crunch reason";
718    }
719
720    switch (rsp->crunch_reason)
721    {
722       case UNSUPPORTED:
723          reason = "Unsupported HTTP feature";
724          break;
725       case BLOCKED:
726          reason = "Blocked";
727          break;
728       case UNTRUSTED:
729          reason = "Untrusted";
730          break;
731       case REDIRECTED:
732          reason = "Redirected";
733          break;
734       case CGI_CALL:
735          reason = "CGI Call";
736          break;
737       case NO_SUCH_DOMAIN:
738          reason = "DNS failure";
739          break;
740       case FORWARDING_FAILED:
741          reason = "Forwarding failed";
742          break;
743       case CONNECT_FAILED:
744          reason = "Connection failure";
745          break;
746       case OUT_OF_MEMORY:
747          reason = "Out of memory (may mask other reasons)";
748          break;
749       case CONNECTION_TIMEOUT:
750          reason = "Connection timeout";
751          break;
752       case NO_SERVER_DATA:
753          reason = "No server data received";
754          break;
755       default:
756          reason = "No reason recorded";
757          break;
758    }
759
760    return reason;
761 }
762
763
764 /*********************************************************************
765  *
766  * Function    :  log_applied_actions
767  *
768  * Description :  Logs the applied actions if LOG_LEVEL_ACTIONS is
769  *                enabled.
770  *
771  * Parameters  :
772  *          1  :  actions = Current action spec to log
773  *
774  * Returns     :  Nothing.
775  *
776  *********************************************************************/
777 static void log_applied_actions(const struct current_action_spec *actions)
778 {
779    /*
780     * The conversion to text requires lots of memory allocations so
781     * we only do the conversion if the user is actually interested.
782     */
783    if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
784    {
785       char *actions_as_text = actions_to_line_of_text(actions);
786       log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
787       freez(actions_as_text);
788    }
789 }
790
791
792 /*********************************************************************
793  *
794  * Function    :  send_crunch_response
795  *
796  * Description :  Delivers already prepared response for
797  *                intercepted requests, logs the interception
798  *                and frees the response.
799  *
800  * Parameters  :
801  *          1  :  csp = Current client state (buffers, headers, etc...)
802  *          2  :  rsp = Fully prepared response. Will be freed on exit.
803  *
804  * Returns     :  Nothing.
805  *
806  *********************************************************************/
807 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
808 {
809       const struct http_request *http = csp->http;
810       char status_code[4];
811
812       assert(rsp != NULL);
813       assert(rsp->head != NULL);
814
815       if (rsp == NULL)
816       {
817          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
818       }
819
820       /*
821        * Extract the status code from the actual head
822        * that will be send to the client. It is the only
823        * way to get it right for all requests, including
824        * the fixed ones for out-of-memory problems.
825        *
826        * A head starts like this: 'HTTP/1.1 200...'
827        *                           0123456789|11
828        *                                     10
829        */
830       status_code[0] = rsp->head[9];
831       status_code[1] = rsp->head[10];
832       status_code[2] = rsp->head[11];
833       status_code[3] = '\0';
834
835       /* Log that the request was crunched and why. */
836       log_applied_actions(csp->action);
837 #ifdef FEATURE_HTTPS_INSPECTION
838       if (client_use_ssl(csp))
839       {
840          log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
841             http->hostport, http->path);
842          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
843             csp->ip_addr_str, http->gpc, http->hostport, http->path,
844             http->version, status_code, rsp->content_length);
845       }
846       else
847 #endif
848       {
849          log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
850          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
851             csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
852       }
853       /* Write the answer to the client */
854 #ifdef FEATURE_HTTPS_INSPECTION
855       if (client_use_ssl(csp))
856       {
857          if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
858                 (const unsigned char *)rsp->head, rsp->head_length,
859                 get_write_delay(csp)) < 0)
860           || (ssl_send_data_delayed(&(csp->ssl_client_attr),
861                 (const unsigned char *)rsp->body, rsp->content_length,
862                 get_write_delay(csp)) < 0))
863          {
864             /* There is nothing we can do about it. */
865             log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
866                "for https://%s%s through client socket %d using TLS/SSL",
867                http->hostport, http->url, csp->cfd);
868          }
869       }
870       else
871 #endif
872       {
873          if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
874                 get_write_delay(csp))
875           || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
876                 get_write_delay(csp)))
877          {
878             /* There is nothing we can do about it. */
879             log_error(LOG_LEVEL_CONNECT,
880                "Couldn't deliver the error message for %s through client socket %d: %E",
881                http->url, csp->cfd);
882          }
883       }
884
885       /* Clean up and return */
886       if (cgi_error_memory() != rsp)
887       {
888          free_http_response(rsp);
889       }
890       return;
891 }
892
893
894 /*********************************************************************
895  *
896  * Function    :  crunch_response_triggered
897  *
898  * Description :  Checks if the request has to be crunched,
899  *                and delivers the crunch response if necessary.
900  *
901  * Parameters  :
902  *          1  :  csp = Current client state (buffers, headers, etc...)
903  *          2  :  crunchers = list of cruncher functions to run
904  *
905  * Returns     :  TRUE if the request was answered with a crunch response
906  *                FALSE otherwise.
907  *
908  *********************************************************************/
909 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
910 {
911    struct http_response *rsp = NULL;
912    const struct cruncher *c;
913
914    /*
915     * If CGI request crunching is disabled,
916     * check the CGI dispatcher out of order to
917     * prevent unintentional blocks or redirects.
918     */
919    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
920        && (NULL != (rsp = dispatch_cgi(csp))))
921    {
922       /* Deliver, log and free the interception response. */
923       send_crunch_response(csp, rsp);
924       csp->flags |= CSP_FLAG_CRUNCHED;
925       return TRUE;
926    }
927
928    for (c = crunchers; c->cruncher != NULL; c++)
929    {
930       /*
931        * Check the cruncher if either Privoxy is toggled
932        * on and the request isn't forced, or if the cruncher
933        * applies to forced requests as well.
934        */
935       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
936           !(csp->flags & CSP_FLAG_FORCED)) ||
937           (c->flags & CF_IGNORE_FORCE))
938       {
939          rsp = c->cruncher(csp);
940          if (NULL != rsp)
941          {
942             /* Deliver, log and free the interception response. */
943             send_crunch_response(csp, rsp);
944             csp->flags |= CSP_FLAG_CRUNCHED;
945 #ifdef FEATURE_STATISTICS
946             if (c->flags & CF_COUNT_AS_REJECT)
947             {
948                csp->flags |= CSP_FLAG_REJECTED;
949             }
950 #endif /* def FEATURE_STATISTICS */
951
952             return TRUE;
953          }
954       }
955    }
956
957    return FALSE;
958 }
959
960
961 /*********************************************************************
962  *
963  * Function    :  build_request_line
964  *
965  * Description :  Builds the HTTP request line.
966  *
967  *                If a HTTP forwarder is used it expects the whole URL,
968  *                web servers only get the path.
969  *
970  * Parameters  :
971  *          1  :  csp = Current client state (buffers, headers, etc...)
972  *          2  :  fwd = The forwarding spec used for the request.
973  *                      Can be NULL.
974  *          3  :  request_line = The old request line which will be replaced.
975  *
976  * Returns     :  Nothing. Terminates in case of memory problems.
977  *
978  *********************************************************************/
979 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
980 {
981    struct http_request *http = csp->http;
982
983    /*
984     * Downgrade http version from 1.1 to 1.0
985     * if +downgrade action applies.
986     */
987    if ((csp->action->flags & ACTION_DOWNGRADE)
988      && (!strcmpic(http->version, "HTTP/1.1")))
989    {
990       freez(http->version);
991       http->version = strdup_or_die("HTTP/1.0");
992    }
993
994    /*
995     * Rebuild the request line.
996     */
997    freez(*request_line);
998 #ifdef FEATURE_HTTPS_INSPECTION
999    if (fwd != NULL && fwd->forward_host &&
1000        fwd->type != FORWARD_WEBSERVER && client_use_ssl(csp))
1001    {
1002       *request_line = strdup("CONNECT ");
1003    }
1004    else
1005 #endif
1006    {
1007       *request_line = strdup(http->gpc);
1008       string_append(request_line, " ");
1009    }
1010
1011    if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1012    {
1013 #ifdef FEATURE_HTTPS_INSPECTION
1014       if (client_use_ssl(csp))
1015       {
1016          char port_string[10];
1017
1018          string_append(request_line, http->host);
1019          snprintf(port_string, sizeof(port_string), ":%d", http->port);
1020          string_append(request_line, port_string);
1021       }
1022       else
1023 #endif
1024       {
1025          string_append(request_line, http->url);
1026       }
1027    }
1028    else
1029    {
1030       string_append(request_line, http->path);
1031    }
1032    string_append(request_line, " ");
1033    string_append(request_line, http->version);
1034
1035    if (*request_line == NULL)
1036    {
1037       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1038    }
1039    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1040 }
1041
1042
1043 /*********************************************************************
1044  *
1045  * Function    :  change_request_destination
1046  *
1047  * Description :  Parse a (rewritten) request line and regenerate
1048  *                the http request data.
1049  *
1050  * Parameters  :
1051  *          1  :  csp = Current client state (buffers, headers, etc...)
1052  *
1053  * Returns     :  Forwards the parse_http_request() return code.
1054  *                Terminates in case of memory problems.
1055  *
1056  *********************************************************************/
1057 static jb_err change_request_destination(struct client_state *csp)
1058 {
1059    struct http_request *http = csp->http;
1060    jb_err err;
1061
1062    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1063       csp->headers->first->str);
1064    free_http_request(http);
1065    err = parse_http_request(csp->headers->first->str, http);
1066    if (JB_ERR_OK != err)
1067    {
1068       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1069          jb_err_to_string(err));
1070    }
1071    if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1072    {
1073       /*
1074        * A client header filter changed the request URL from
1075        * http:// to https:// which we currently don't support.
1076        */
1077       log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1078          "to https behind the client's back currently isn't supported.");
1079       return JB_ERR_PARSE;
1080    }
1081
1082    return err;
1083 }
1084
1085
1086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1087 /*********************************************************************
1088  *
1089  * Function    :  server_response_is_complete
1090  *
1091  * Description :  Determines whether we should stop reading
1092  *                from the server socket.
1093  *
1094  * Parameters  :
1095  *          1  :  csp = Current client state (buffers, headers, etc...)
1096  *          2  :  content_length = Length of content received so far.
1097  *
1098  * Returns     :  TRUE if the response is complete,
1099  *                FALSE otherwise.
1100  *
1101  *********************************************************************/
1102 static int server_response_is_complete(struct client_state *csp,
1103    unsigned long long content_length)
1104 {
1105    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1106
1107    if (!strcmpic(csp->http->gpc, "HEAD"))
1108    {
1109       /*
1110        * "HEAD" implies no body, we are thus expecting
1111        * no content. XXX: incomplete "list" of methods?
1112        */
1113       csp->expected_content_length = 0;
1114       content_length_known = TRUE;
1115       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1116    }
1117
1118    if (csp->http->status == 204 || csp->http->status == 304)
1119    {
1120       /*
1121        * Expect no body. XXX: incomplete "list" of status codes?
1122        */
1123       csp->expected_content_length = 0;
1124       content_length_known = TRUE;
1125       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1126    }
1127
1128    return (content_length_known && ((0 == csp->expected_content_length)
1129             || (csp->expected_content_length <= content_length)));
1130 }
1131
1132
1133 #ifdef FEATURE_CONNECTION_SHARING
1134 /*********************************************************************
1135  *
1136  * Function    :  wait_for_alive_connections
1137  *
1138  * Description :  Waits for alive connections to timeout.
1139  *
1140  * Parameters  :  N/A
1141  *
1142  * Returns     :  N/A
1143  *
1144  *********************************************************************/
1145 static void wait_for_alive_connections(void)
1146 {
1147    int connections_alive = close_unusable_connections();
1148
1149    while (0 < connections_alive)
1150    {
1151       log_error(LOG_LEVEL_CONNECT,
1152          "Waiting for %d connections to timeout.",
1153          connections_alive);
1154       sleep(60);
1155       connections_alive = close_unusable_connections();
1156    }
1157
1158    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1159
1160 }
1161 #endif /* def FEATURE_CONNECTION_SHARING */
1162
1163
1164 /*********************************************************************
1165  *
1166  * Function    :  save_connection_destination
1167  *
1168  * Description :  Remembers a connection for reuse later on.
1169  *
1170  * Parameters  :
1171  *          1  :  sfd  = Open socket to remember.
1172  *          2  :  http = The destination for the connection.
1173  *          3  :  fwd  = The forwarder settings used.
1174  *          4  :  server_connection  = storage.
1175  *
1176  * Returns     : void
1177  *
1178  *********************************************************************/
1179 static void save_connection_destination(jb_socket sfd,
1180                                         const struct http_request *http,
1181                                         const struct forward_spec *fwd,
1182                                         struct reusable_connection *server_connection)
1183 {
1184    assert(sfd != JB_INVALID_SOCKET);
1185    assert(NULL != http->host);
1186
1187    server_connection->sfd = sfd;
1188    server_connection->host = strdup_or_die(http->host);
1189    server_connection->port = http->port;
1190
1191    assert(NULL != fwd);
1192    assert(server_connection->gateway_host == NULL);
1193    assert(server_connection->gateway_port == 0);
1194    assert(server_connection->forwarder_type == 0);
1195    assert(server_connection->forward_host == NULL);
1196    assert(server_connection->forward_port == 0);
1197
1198    server_connection->forwarder_type = fwd->type;
1199    if (NULL != fwd->gateway_host)
1200    {
1201       server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1202    }
1203    else
1204    {
1205       server_connection->gateway_host = NULL;
1206    }
1207    server_connection->gateway_port = fwd->gateway_port;
1208    if (NULL != fwd->auth_username)
1209    {
1210       server_connection->auth_username = strdup_or_die(fwd->auth_username);
1211    }
1212    else
1213    {
1214       server_connection->auth_username = NULL;
1215    }
1216    if (NULL != fwd->auth_password)
1217    {
1218       server_connection->auth_password = strdup_or_die(fwd->auth_password);
1219    }
1220    else
1221    {
1222       server_connection->auth_password = NULL;
1223    }
1224
1225    if (NULL != fwd->forward_host)
1226    {
1227       server_connection->forward_host = strdup_or_die(fwd->forward_host);
1228    }
1229    else
1230    {
1231       server_connection->forward_host = NULL;
1232    }
1233    server_connection->forward_port = fwd->forward_port;
1234 }
1235 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1236
1237
1238 /*********************************************************************
1239  *
1240  * Function    : verify_request_length
1241  *
1242  * Description : Checks if we already got the whole client requests
1243  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1244  *               we do.
1245  *
1246  *               Data that doesn't belong to the current request is
1247  *               either thrown away to let the client retry on a clean
1248  *               socket, or stashed to be dealt with after the current
1249  *               request is served.
1250  *
1251  * Parameters  :
1252  *          1  :  csp = Current client state (buffers, headers, etc...)
1253  *
1254  * Returns     :  void
1255  *
1256  *********************************************************************/
1257 static void verify_request_length(struct client_state *csp)
1258 {
1259    unsigned long long buffered_request_bytes =
1260       (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1261
1262    if ((csp->expected_client_content_length != 0)
1263       && (buffered_request_bytes != 0))
1264    {
1265       if (csp->expected_client_content_length >= buffered_request_bytes)
1266       {
1267          csp->expected_client_content_length -= buffered_request_bytes;
1268          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1269             "to account for the %llu ones we already got.",
1270             csp->expected_client_content_length, buffered_request_bytes);
1271       }
1272       else
1273       {
1274          assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1275          csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1276          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1277             "Marking the server socket tainted after throwing %llu bytes away.",
1278             buffered_request_bytes - csp->expected_client_content_length);
1279          csp->expected_client_content_length = 0;
1280          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1281       }
1282
1283       if (csp->expected_client_content_length == 0)
1284       {
1285          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1286       }
1287    }
1288
1289    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1290       && ((csp->client_iob->cur < csp->client_iob->eod)
1291          || (csp->expected_client_content_length != 0)))
1292    {
1293       if (strcmpic(csp->http->gpc, "GET")
1294          && strcmpic(csp->http->gpc, "HEAD")
1295          && strcmpic(csp->http->gpc, "TRACE")
1296          && strcmpic(csp->http->gpc, "OPTIONS")
1297          && strcmpic(csp->http->gpc, "DELETE"))
1298       {
1299          /* XXX: this is an incomplete hack */
1300          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1301          log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1302       }
1303       else
1304       {
1305          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1306
1307          if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1308          {
1309             csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1310             log_error(LOG_LEVEL_CONNECT,
1311                "Possible pipeline attempt detected. The connection will not "
1312                "be kept alive and we will only serve the first request.");
1313             /* Nuke the pipelined requests from orbit, just to be sure. */
1314             clear_iob(csp->client_iob);
1315          }
1316          else
1317          {
1318             /*
1319              * Keep the pipelined data around for now, we'll deal with
1320              * it once we're done serving the current request.
1321              */
1322             csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1323             assert(csp->client_iob->eod >= csp->client_iob->cur);
1324             log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1325                "%d bytes of pipelined data received.",
1326                (int)(csp->client_iob->eod - csp->client_iob->cur));
1327          }
1328       }
1329    }
1330    else
1331    {
1332       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1333       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1334    }
1335 }
1336
1337
1338 /*********************************************************************
1339  *
1340  * Function    :  mark_server_socket_tainted
1341  *
1342  * Description :  Makes sure we don't reuse a server socket
1343  *                (if we didn't read everything the server sent
1344  *                us reusing the socket would lead to garbage).
1345  *
1346  * Parameters  :
1347  *          1  :  csp = Current client state (buffers, headers, etc...)
1348  *
1349  * Returns     :  void.
1350  *
1351  *********************************************************************/
1352 static void mark_server_socket_tainted(struct client_state *csp)
1353 {
1354    /*
1355     * For consistency we always mark the server socket
1356     * tainted, however, to reduce the log noise we only
1357     * emit a log message if the server socket could have
1358     * actually been reused.
1359     */
1360    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1361       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1362    {
1363       log_error(LOG_LEVEL_CONNECT,
1364          "Marking the server socket %d tainted.",
1365          csp->server_connection.sfd);
1366    }
1367    csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1368 }
1369
1370 /*********************************************************************
1371  *
1372  * Function    :  get_request_line
1373  *
1374  * Description : Read the client request line.
1375  *
1376  * Parameters  :
1377  *          1  :  csp = Current client state (buffers, headers, etc...)
1378  *
1379  * Returns     :  Pointer to request line or NULL in case of errors.
1380  *
1381  *********************************************************************/
1382 static char *get_request_line(struct client_state *csp)
1383 {
1384    char buf[BUFFER_SIZE];
1385    char *request_line = NULL;
1386    int len;
1387
1388    memset(buf, 0, sizeof(buf));
1389
1390    if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1391    {
1392       /*
1393        * If there are multiple pipelined requests waiting,
1394        * the flag will be set again once the next request
1395        * has been parsed.
1396        */
1397       csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1398
1399       request_line = get_header(csp->client_iob);
1400       if ((NULL != request_line) && ('\0' != *request_line))
1401       {
1402          return request_line;
1403       }
1404       else
1405       {
1406          log_error(LOG_LEVEL_CONNECT, "No complete request line "
1407             "received yet. Continuing reading from %d.", csp->cfd);
1408       }
1409    }
1410
1411    do
1412    {
1413       if (
1414 #ifdef FUZZ
1415           0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1416 #endif
1417           !data_is_available(csp->cfd, csp->config->socket_timeout)
1418           )
1419       {
1420          if (socket_is_still_alive(csp->cfd))
1421          {
1422             log_error(LOG_LEVEL_CONNECT,
1423                "No request line on socket %d received in time. Timeout: %d.",
1424                csp->cfd, csp->config->socket_timeout);
1425             write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1426                strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1427                get_write_delay(csp));
1428          }
1429          else
1430          {
1431             log_error(LOG_LEVEL_CONNECT,
1432                "The client side of the connection on socket %d got "
1433                "closed without sending a complete request line.", csp->cfd);
1434          }
1435          return NULL;
1436       }
1437
1438       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1439
1440       if (len <= 0) return NULL;
1441
1442       /*
1443        * If there is no memory left for buffering the
1444        * request, there is nothing we can do but hang up
1445        */
1446       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1447       {
1448          return NULL;
1449       }
1450
1451       request_line = get_header(csp->client_iob);
1452
1453    } while ((NULL != request_line) && ('\0' == *request_line));
1454
1455    return request_line;
1456
1457 }
1458
1459 enum chunk_status
1460 {
1461    CHUNK_STATUS_MISSING_DATA,
1462    CHUNK_STATUS_BODY_COMPLETE,
1463    CHUNK_STATUS_PARSE_ERROR
1464 };
1465
1466
1467 /*********************************************************************
1468  *
1469  * Function    :  chunked_body_is_complete
1470  *
1471  * Description :  Figures out whether or not a chunked body is complete.
1472  *
1473  *                Currently it always starts at the beginning of the
1474  *                buffer which is somewhat wasteful and prevents Privoxy
1475  *                from starting to forward the correctly parsed chunks
1476  *                as soon as theoretically possible.
1477  *
1478  *                Should be modified to work with a common buffer,
1479  *                and allow the caller to skip already parsed chunks.
1480  *
1481  *                This would allow the function to be used for unbuffered
1482  *                response bodies as well.
1483  *
1484  * Parameters  :
1485  *          1  :  iob = Buffer with the body to check.
1486  *          2  :  length = Length of complete body
1487  *
1488  * Returns     :  Enum with the result of the check.
1489  *
1490  *********************************************************************/
1491 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1492 {
1493    unsigned int chunksize;
1494    char *p = iob->cur;
1495
1496    do
1497    {
1498       /*
1499        * We need at least a single digit, followed by "\r\n",
1500        * followed by an unknown amount of data, followed by "\r\n".
1501        */
1502       if (p + 5 > iob->eod)
1503       {
1504          return CHUNK_STATUS_MISSING_DATA;
1505       }
1506       if (sscanf(p, "%x", &chunksize) != 1)
1507       {
1508          return CHUNK_STATUS_PARSE_ERROR;
1509       }
1510
1511       /*
1512        * We want at least a single digit, followed by "\r\n",
1513        * followed by the specified amount of data, followed by "\r\n".
1514        */
1515       if (p + chunksize + 5 > iob->eod)
1516       {
1517          return CHUNK_STATUS_MISSING_DATA;
1518       }
1519
1520       /* Skip chunk-size. */
1521       p = strstr(p, "\r\n");
1522       if (NULL == p)
1523       {
1524          return CHUNK_STATUS_PARSE_ERROR;
1525       }
1526       /* Move beyond the chunkdata. */
1527       p += 2 + chunksize;
1528
1529       /* Make sure we're still within the buffer and have two bytes left */
1530       if (p + 2 > iob->eod)
1531       {
1532          return CHUNK_STATUS_MISSING_DATA;
1533       }
1534
1535       /* There should be another "\r\n" to skip */
1536       if (memcmp(p, "\r\n", 2))
1537       {
1538          return CHUNK_STATUS_PARSE_ERROR;
1539       }
1540       p += 2;
1541    } while (chunksize > 0U);
1542
1543    *length = (size_t)(p - iob->cur);
1544    assert(*length <= (size_t)(iob->eod - iob->cur));
1545    assert(p <= iob->eod);
1546
1547    return CHUNK_STATUS_BODY_COMPLETE;
1548
1549 }
1550
1551
1552 /*********************************************************************
1553  *
1554  * Function    : receive_chunked_client_request_body
1555  *
1556  * Description : Read the chunk-encoded client request body.
1557  *               Failures are dealt with.
1558  *
1559  * Parameters  :
1560  *          1  :  csp = Current client state (buffers, headers, etc...)
1561  *
1562  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1563  *
1564  *********************************************************************/
1565 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1566 {
1567    size_t body_length;
1568    enum chunk_status status;
1569
1570    while (CHUNK_STATUS_MISSING_DATA ==
1571       (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1572    {
1573       char buf[BUFFER_SIZE];
1574       int len;
1575
1576       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1577       {
1578          log_error(LOG_LEVEL_ERROR,
1579             "Timeout while waiting for the client body.");
1580          break;
1581       }
1582       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1583       if (len <= 0)
1584       {
1585          log_error(LOG_LEVEL_ERROR,
1586             "Reading the client body failed: %E");
1587          break;
1588       }
1589       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1590       {
1591          break;
1592       }
1593    }
1594    if (status != CHUNK_STATUS_BODY_COMPLETE)
1595    {
1596       write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1597          strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1598       log_error(LOG_LEVEL_CLF,
1599          "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1600       return JB_ERR_PARSE;
1601    }
1602    log_error(LOG_LEVEL_CONNECT,
1603       "Chunked client body completely read. Length: %lu", body_length);
1604    csp->expected_client_content_length = body_length;
1605
1606    return JB_ERR_OK;
1607
1608 }
1609
1610
1611 #ifdef FUZZ
1612 /*********************************************************************
1613  *
1614  * Function    :  fuzz_chunked_transfer_encoding
1615  *
1616  * Description :  Treat the fuzzed input as chunked transfer encoding
1617  *                to check and dechunk.
1618  *
1619  * Parameters  :
1620  *          1  :  csp      = Used to store the data.
1621  *          2  :  fuzz_input_file = File to read the input from.
1622  *
1623  * Returns     : Result of dechunking
1624  *
1625  *********************************************************************/
1626 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1627 {
1628    size_t length;
1629    size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1630    enum chunk_status status;
1631
1632    status = chunked_body_is_complete(csp->iob, &length);
1633    if (CHUNK_STATUS_BODY_COMPLETE != status)
1634    {
1635       log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1636    }
1637
1638    return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1639
1640 }
1641
1642
1643 /*********************************************************************
1644  *
1645  * Function    : fuzz_client_request
1646  *
1647  * Description : Try to get a client request from the fuzzed input.
1648  *
1649  * Parameters  :
1650  *          1  :  csp = Current client state (buffers, headers, etc...)
1651  *          2  :  fuzz_input_file = File to read the input from.
1652  *
1653  * Returns     :  Result of fuzzing.
1654  *
1655  *********************************************************************/
1656 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1657 {
1658    jb_err err;
1659
1660    csp->cfd = 0;
1661    csp->ip_addr_str = "fuzzer";
1662
1663    if (strcmp(fuzz_input_file, "-") != 0)
1664    {
1665       log_error(LOG_LEVEL_FATAL,
1666          "Fuzzed client requests can currently only be read from stdin (-).");
1667    }
1668    err = receive_client_request(csp);
1669    if (err != JB_ERR_OK)
1670    {
1671       return 1;
1672    }
1673    err = parse_client_request(csp);
1674    if (err != JB_ERR_OK)
1675    {
1676       return 1;
1677    }
1678
1679    return 0;
1680
1681 }
1682 #endif  /* def FUZZ */
1683
1684
1685 #ifdef FEATURE_FORCE_LOAD
1686 /*********************************************************************
1687  *
1688  * Function    :  force_required
1689  *
1690  * Description : Checks a request line to see if it contains
1691  *               the FORCE_PREFIX. If it does, it is removed
1692  *               unless enforcing requests has beend disabled.
1693  *
1694  * Parameters  :
1695  *          1  :  request_line = HTTP request line
1696  *
1697  * Returns     :  TRUE if force is required, FALSE otherwise.
1698  *
1699  *********************************************************************/
1700 static int force_required(const struct client_state *csp, char *request_line)
1701 {
1702    char *p;
1703
1704    p = strstr(request_line, "http://");
1705    if (p != NULL)
1706    {
1707       /* Skip protocol */
1708       p += strlen("http://");
1709    }
1710    else
1711    {
1712       /* Intercepted request usually don't specify the protocol. */
1713       p = request_line;
1714    }
1715
1716    /* Go to the beginning of the path */
1717    p = strstr(p, "/");
1718    if (p == NULL)
1719    {
1720       /*
1721        * If the path is missing the request line is invalid and we
1722        * are done here. The client-visible rejection happens later on.
1723        */
1724       return 0;
1725    }
1726
1727    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1728    {
1729       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1730       {
1731          /* XXX: Should clean more carefully */
1732          strclean(request_line, FORCE_PREFIX);
1733          log_error(LOG_LEVEL_FORCE,
1734             "Enforcing request: \"%s\".", request_line);
1735
1736          return 1;
1737       }
1738       log_error(LOG_LEVEL_FORCE,
1739          "Ignored force prefix in request: \"%s\".", request_line);
1740    }
1741
1742    return 0;
1743
1744 }
1745 #endif /* def FEATURE_FORCE_LOAD */
1746
1747
1748 /*********************************************************************
1749  *
1750  * Function    :  receive_client_request
1751  *
1752  * Description : Read the client's request (more precisely the
1753  *               client headers) and answer it if necessary.
1754  *
1755  * Parameters  :
1756  *          1  :  csp = Current client state (buffers, headers, etc...)
1757  *
1758  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1759  *
1760  *********************************************************************/
1761 static jb_err receive_client_request(struct client_state *csp)
1762 {
1763    char buf[BUFFER_SIZE];
1764    char *p;
1765    char *req = NULL;
1766    struct http_request *http;
1767    int len;
1768    jb_err err;
1769
1770    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1771    struct list header_list;
1772    struct list *headers = &header_list;
1773
1774    /* We don't care if the arriving data is a valid HTTP request or not. */
1775    csp->requests_received_total++;
1776
1777    http = csp->http;
1778
1779    memset(buf, 0, sizeof(buf));
1780
1781    req = get_request_line(csp);
1782    if (req == NULL)
1783    {
1784       mark_server_socket_tainted(csp);
1785       return JB_ERR_PARSE;
1786    }
1787    assert(*req != '\0');
1788
1789    if (client_protocol_is_unsupported(csp, req))
1790    {
1791       return JB_ERR_PARSE;
1792    }
1793
1794 #ifdef FEATURE_FORCE_LOAD
1795    if (force_required(csp, req))
1796    {
1797       csp->flags |= CSP_FLAG_FORCED;
1798    }
1799 #endif /* def FEATURE_FORCE_LOAD */
1800
1801    err = parse_http_request(req, http);
1802    freez(req);
1803    if (JB_ERR_OK != err)
1804    {
1805       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1806          get_write_delay(csp));
1807       /* XXX: Use correct size */
1808       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1809       log_error(LOG_LEVEL_ERROR,
1810          "Couldn't parse request line received from %s: %s",
1811          csp->ip_addr_str, jb_err_to_string(err));
1812
1813       free_http_request(http);
1814       return JB_ERR_PARSE;
1815    }
1816
1817    /* grab the rest of the client's headers */
1818    init_list(headers);
1819    for (;;)
1820    {
1821       p = get_header(csp->client_iob);
1822
1823       if (p == NULL)
1824       {
1825          /* There are no additional headers to read. */
1826          break;
1827       }
1828
1829       if (*p == '\0')
1830       {
1831          /*
1832           * We didn't receive a complete header
1833           * line yet, get the rest of it.
1834           */
1835          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1836          {
1837             log_error(LOG_LEVEL_ERROR,
1838                "Stopped grabbing the client headers.");
1839             destroy_list(headers);
1840             return JB_ERR_PARSE;
1841          }
1842
1843          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1844          if (len <= 0)
1845          {
1846             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1847             destroy_list(headers);
1848             return JB_ERR_PARSE;
1849          }
1850
1851          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1852          {
1853             /*
1854              * If there is no memory left for buffering the
1855              * request, there is nothing we can do but hang up
1856              */
1857             destroy_list(headers);
1858             return JB_ERR_MEMORY;
1859          }
1860       }
1861       else
1862       {
1863          if (!strncmpic(p, "Transfer-Encoding:", 18))
1864          {
1865             /*
1866              * XXX: should be called through sed()
1867              *      but currently can't.
1868              */
1869             client_transfer_encoding(csp, &p);
1870          }
1871          /*
1872           * We were able to read a complete
1873           * header and can finally enlist it.
1874           */
1875          enlist(headers, p);
1876          freez(p);
1877       }
1878    }
1879
1880    if (http->host == NULL)
1881    {
1882       /*
1883        * If we still don't know the request destination,
1884        * the request is invalid or the client uses
1885        * Privoxy without its knowledge.
1886        */
1887       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1888       {
1889          /*
1890           * Our attempts to get the request destination
1891           * elsewhere failed or Privoxy is configured
1892           * to only accept proxy requests.
1893           *
1894           * An error response has already been sent
1895           * and we're done here.
1896           */
1897          return JB_ERR_PARSE;
1898       }
1899    }
1900
1901 #ifdef FEATURE_CLIENT_TAGS
1902    /* XXX: If the headers were enlisted sooner, passing csp would do. */
1903    set_client_address(csp, headers);
1904    get_tag_list_for_client(csp->client_tags, csp->client_address);
1905 #endif
1906
1907    /*
1908     * Determine the actions for this URL
1909     */
1910 #ifdef FEATURE_TOGGLE
1911    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1912    {
1913       /* Most compatible set of actions (i.e. none) */
1914       init_current_action(csp->action);
1915    }
1916    else
1917 #endif /* ndef FEATURE_TOGGLE */
1918    {
1919       get_url_actions(csp, http);
1920    }
1921
1922    enlist(csp->headers, http->cmd);
1923
1924    /* Append the previously read headers */
1925    err = list_append_list_unique(csp->headers, headers);
1926    destroy_list(headers);
1927
1928    return err;
1929
1930 }
1931
1932
1933 /*********************************************************************
1934  *
1935  * Function    : parse_client_request
1936  *
1937  * Description : Parses the client's request and decides what to do
1938  *               with it.
1939  *
1940  *               Note that since we're not using select() we could get
1941  *               blocked here if a client connected, then didn't say
1942  *               anything!
1943  *
1944  * Parameters  :
1945  *          1  :  csp = Current client state (buffers, headers, etc...)
1946  *
1947  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1948  *
1949  *********************************************************************/
1950 static jb_err parse_client_request(struct client_state *csp)
1951 {
1952    struct http_request *http = csp->http;
1953    jb_err err;
1954
1955 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1956    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1957     && (!strcmpic(csp->http->version, "HTTP/1.1"))
1958     && (csp->http->ssl == 0))
1959    {
1960       /* Assume persistence until further notice */
1961       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1962    }
1963 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1964
1965    if (csp->http->ssl == 0)
1966    {
1967       /*
1968        * This whole block belongs to chat() but currently
1969        * has to be executed before sed().
1970        */
1971       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1972       {
1973          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1974          {
1975             return JB_ERR_PARSE;
1976          }
1977       }
1978       else
1979       {
1980          csp->expected_client_content_length = get_expected_content_length(csp->headers);
1981       }
1982       verify_request_length(csp);
1983    }
1984 #ifndef FEATURE_HTTPS_INSPECTION
1985    else
1986    {
1987       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1988    }
1989 #endif
1990
1991    err = sed(csp, FILTER_CLIENT_HEADERS);
1992    if (JB_ERR_OK != err)
1993    {
1994       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1995          csp->ip_addr_str);
1996       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1997          csp->ip_addr_str, csp->http->cmd);
1998       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1999       return JB_ERR_PARSE;
2000    }
2001    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2002
2003    /* Check request line for rewrites. */
2004    if ((NULL == csp->headers->first->str)
2005       || (strcmp(http->cmd, csp->headers->first->str) &&
2006          (JB_ERR_OK != change_request_destination(csp))))
2007    {
2008       /*
2009        * A header filter broke the request line - bail out.
2010        */
2011       write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2012          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2013       /* XXX: Use correct size */
2014       log_error(LOG_LEVEL_CLF,
2015          "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2016       log_error(LOG_LEVEL_ERROR,
2017          "Invalid request line after applying header filters.");
2018       free_http_request(http);
2019
2020       return JB_ERR_PARSE;
2021    }
2022
2023    if (client_has_unsupported_expectations(csp))
2024    {
2025       return JB_ERR_PARSE;
2026    }
2027
2028    return JB_ERR_OK;
2029
2030 }
2031
2032
2033 /*********************************************************************
2034  *
2035  * Function    : read_http_request_body
2036  *
2037  * Description : Reads remaining request body from the client.
2038  *
2039  * Parameters  :
2040  *          1  :  csp = Current client state (buffers, headers, etc...)
2041  *
2042  * Returns     :  0 on success, anything else is an error.
2043  *
2044  *********************************************************************/
2045 static int read_http_request_body(struct client_state *csp)
2046 {
2047    size_t to_read = csp->expected_client_content_length;
2048    int len;
2049
2050    assert(to_read != 0);
2051
2052    /* check if all data has been already read */
2053    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2054    {
2055       return 0;
2056    }
2057
2058    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2059         to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2060         to_read -= (unsigned)len)
2061    {
2062       char buf[BUFFER_SIZE];
2063       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2064
2065       log_error(LOG_LEVEL_CONNECT,
2066          "Waiting for up to %lu bytes of request body from the client.",
2067          max_bytes_to_read);
2068       len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2069       if (len <= -1)
2070       {
2071          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2072          return 1;
2073       }
2074       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2075       {
2076          return 1;
2077       }
2078       assert(to_read >= len);
2079    }
2080
2081    if (to_read != 0)
2082    {
2083       log_error(LOG_LEVEL_CONNECT,
2084          "Not enough request body has been read: expected %lu more bytes",
2085          to_read);
2086       return 1;
2087    }
2088    log_error(LOG_LEVEL_CONNECT,
2089       "The last %d bytes of the request body have been read", len);
2090    return 0;
2091 }
2092
2093
2094 /*********************************************************************
2095  *
2096  * Function    : update_client_headers
2097  *
2098  * Description : Updates the HTTP headers from the client request.
2099  *
2100  * Parameters  :
2101  *          1  :  csp = Current client state (buffers, headers, etc...)
2102  *          2  :  new_content_length = new content length value to set
2103  *
2104  * Returns     :  0 on success, anything else is an error.
2105  *
2106  *********************************************************************/
2107 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2108 {
2109    static const char content_length[] = "Content-Length:";
2110    int updated = 0;
2111    struct list_entry *p;
2112
2113 #ifndef FEATURE_HTTPS_INSPECTION
2114    for (p = csp->headers->first;
2115 #else
2116    for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2117 #endif
2118         !updated  && (p != NULL); p = p->next)
2119    {
2120       /* Header crunch()ed in previous run? -> ignore */
2121       if (p->str == NULL)
2122       {
2123          continue;
2124       }
2125
2126       /* Does the current parser handle this header? */
2127       if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2128       {
2129          updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2130          if (!updated)
2131          {
2132             return 1;
2133          }
2134       }
2135    }
2136
2137    return !updated;
2138 }
2139
2140
2141 /*********************************************************************
2142  *
2143  * Function    : can_filter_request_body
2144  *
2145  * Description : Checks if the current request body can be stored in
2146  *               the client_iob without hitting buffer limit.
2147  *
2148  * Parameters  :
2149  *          1  : csp = Current client state (buffers, headers, etc...)
2150  *
2151  * Returns     : TRUE if the current request size do not exceed buffer limit
2152  *               FALSE otherwise.
2153  *
2154  *********************************************************************/
2155 static int can_filter_request_body(const struct client_state *csp)
2156 {
2157    if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2158                        csp->expected_client_content_length))
2159    {
2160       log_error(LOG_LEVEL_INFO,
2161          "Not filtering request body from %s: buffer limit %lu will be exceeded "
2162          "(content length %lluu)", csp->ip_addr_str, csp->config->buffer_limit,
2163          csp->expected_client_content_length);
2164       return FALSE;
2165    }
2166    return TRUE;
2167 }
2168
2169
2170 /*********************************************************************
2171  *
2172  * Function    : send_http_request
2173  *
2174  * Description : Sends the HTTP headers from the client request
2175  *               and all the body data that has already been received.
2176  *
2177  * Parameters  :
2178  *          1  :  csp = Current client state (buffers, headers, etc...)
2179  *
2180  * Returns     :  0 on success, anything else is an error.
2181  *
2182  *********************************************************************/
2183 static int send_http_request(struct client_state *csp)
2184 {
2185    char *hdr;
2186    int write_failure;
2187    const char *to_send;
2188    size_t to_send_len;
2189    int filter_client_body = csp->expected_client_content_length != 0 &&
2190       client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2191
2192    if (filter_client_body)
2193    {
2194       if (read_http_request_body(csp))
2195       {
2196          return 1;
2197       }
2198       to_send_len = csp->expected_client_content_length;
2199       to_send = execute_client_body_filters(csp, &to_send_len);
2200       if (to_send == NULL)
2201       {
2202          /* just flush client_iob */
2203          filter_client_body = FALSE;
2204       }
2205       else if (to_send_len != csp->expected_client_content_length &&
2206          update_client_headers(csp, to_send_len))
2207       {
2208          log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2209          return 1;
2210       }
2211       csp->expected_client_content_length = 0;
2212    }
2213
2214    hdr = list_to_text(csp->headers);
2215    if (hdr == NULL)
2216    {
2217       /* FIXME Should handle error properly */
2218       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2219    }
2220    list_remove_all(csp->headers);
2221
2222    /*
2223     * Write the client's (modified) header to the server
2224     * (along with anything else that may be in the buffer)
2225     */
2226    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2227    freez(hdr);
2228
2229    if (write_failure)
2230    {
2231       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2232          csp->http->hostport);
2233       return 1;
2234    }
2235
2236    if (filter_client_body)
2237    {
2238       write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2239       freez(to_send);
2240       if (write_failure)
2241       {
2242          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2243             csp->http->hostport);
2244          return 1;
2245       }
2246    }
2247
2248    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2249       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2250    {
2251       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2252          csp->http->hostport);
2253       return 1;
2254    }
2255    return 0;
2256 }
2257
2258
2259 #ifdef FEATURE_HTTPS_INSPECTION
2260 /*********************************************************************
2261  *
2262  * Function    : read_https_request_body
2263  *
2264  * Description : Reads remaining request body from the client.
2265  *
2266  * Parameters  :
2267  *          1  :  csp = Current client state (buffers, headers, etc...)
2268  *
2269  * Returns     :  0 on success, anything else is an error.
2270  *
2271  *********************************************************************/
2272 static int read_https_request_body(struct client_state *csp)
2273 {
2274    size_t to_read = csp->expected_client_content_length;
2275    int len;
2276
2277    assert(to_read != 0);
2278
2279    /* check if all data has been already read */
2280    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2281    {
2282       return 0;
2283    }
2284
2285    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2286         to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2287           data_is_available(csp->cfd, csp->config->socket_timeout));
2288         to_read -= (unsigned)len)
2289    {
2290       unsigned char buf[BUFFER_SIZE];
2291       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2292
2293       log_error(LOG_LEVEL_CONNECT,
2294          "Waiting for up to %lu bytes of request body from the client.",
2295          max_bytes_to_read);
2296       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2297          (unsigned)max_bytes_to_read);
2298       if (len <= 0)
2299       {
2300          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2301          return 1;
2302       }
2303       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2304       {
2305          return 1;
2306       }
2307       assert(to_read >= len);
2308    }
2309
2310    if (to_read != 0)
2311    {
2312       log_error(LOG_LEVEL_CONNECT,
2313          "Not enough request body has been read: expected %lu more bytes",
2314          to_read);
2315       return 1;
2316    }
2317
2318    log_error(LOG_LEVEL_CONNECT,
2319       "The last %llu bytes of the request body have been read",
2320       csp->expected_client_content_length);
2321    return 0;
2322 }
2323
2324
2325 /*********************************************************************
2326  *
2327  * Function    : receive_and_send_encrypted_post_data
2328  *
2329  * Description : Reads remaining request body from the client and sends
2330  *               it to the server.
2331  *
2332  * Parameters  :
2333  *          1  :  csp = Current client state (buffers, headers, etc...)
2334  *
2335  * Returns     :  0 on success, anything else is an error.
2336  *
2337  *********************************************************************/
2338 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2339 {
2340    int content_length_known = csp->expected_client_content_length != 0;
2341
2342    while (is_ssl_pending(&(csp->ssl_client_attr))
2343       || (content_length_known && csp->expected_client_content_length != 0))
2344    {
2345       unsigned char buf[BUFFER_SIZE];
2346       int len;
2347       int max_bytes_to_read = sizeof(buf);
2348
2349       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2350       {
2351          max_bytes_to_read = (int)csp->expected_client_content_length;
2352       }
2353       log_error(LOG_LEVEL_CONNECT,
2354          "Waiting for up to %d bytes of request body from the client.",
2355          max_bytes_to_read);
2356       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2357          (unsigned)max_bytes_to_read);
2358       if (len == -1)
2359       {
2360          return 1;
2361       }
2362       if (len == 0)
2363       {
2364          /* XXX: Does this actually happen? */
2365          break;
2366       }
2367       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2368          len);
2369       len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2370       if (len == -1)
2371       {
2372          return 1;
2373       }
2374       if (csp->expected_client_content_length != 0)
2375       {
2376          if (csp->expected_client_content_length >= len)
2377          {
2378             csp->expected_client_content_length -= (unsigned)len;
2379          }
2380          if (csp->expected_client_content_length == 0)
2381          {
2382             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2383             break;
2384          }
2385       }
2386    }
2387
2388    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2389
2390    return 0;
2391
2392 }
2393
2394
2395 /*********************************************************************
2396  *
2397  * Function    : send_https_request
2398  *
2399  * Description : Sends the HTTP headers from the client request
2400  *               and all the body data that has already been received.
2401  *
2402  * Parameters  :
2403  *          1  :  csp = Current client state (buffers, headers, etc...)
2404  *
2405  * Returns     :  0 on success, anything else is an error.
2406  *
2407  *********************************************************************/
2408 static int send_https_request(struct client_state *csp)
2409 {
2410    char *hdr;
2411    int ret;
2412    long flushed = 0;
2413    const char *to_send;
2414    size_t to_send_len;
2415    int filter_client_body = csp->expected_client_content_length != 0 &&
2416       client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2417
2418    if (filter_client_body)
2419    {
2420       if (read_https_request_body(csp))
2421       {
2422          return 1;
2423       }
2424       to_send_len = csp->expected_client_content_length;
2425       to_send = execute_client_body_filters(csp, &to_send_len);
2426       if (to_send == NULL)
2427       {
2428          /* just flush client_iob */
2429          filter_client_body = FALSE;
2430       }
2431       else if (to_send_len != csp->expected_client_content_length &&
2432          update_client_headers(csp, to_send_len))
2433       {
2434          log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2435          return 1;
2436       }
2437       csp->expected_client_content_length = 0;
2438    }
2439
2440    hdr = list_to_text(csp->https_headers);
2441    if (hdr == NULL)
2442    {
2443       /* FIXME Should handle error properly */
2444       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2445    }
2446    list_remove_all(csp->https_headers);
2447
2448    /*
2449     * Write the client's (modified) header to the server
2450     * (along with anything else that may be in the buffer)
2451     */
2452    ret = ssl_send_data(&(csp->ssl_server_attr),
2453       (const unsigned char *)hdr, strlen(hdr));
2454    freez(hdr);
2455
2456    if (ret < 0)
2457    {
2458       log_error(LOG_LEVEL_CONNECT,
2459          "Failed sending encrypted request headers to: %s: %E",
2460          csp->http->hostport);
2461       mark_server_socket_tainted(csp);
2462       return 1;
2463    }
2464
2465    if (filter_client_body)
2466    {
2467       ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2468       freez(to_send);
2469       if (ret < 0)
2470       {
2471          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2472             csp->http->hostport);
2473          return 1;
2474       }
2475    }
2476
2477    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2478       && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2479             csp->client_iob)) < 0))
2480    {
2481       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2482          csp->http->hostport);
2483       return 1;
2484    }
2485    if (flushed != 0 || csp->expected_client_content_length != 0)
2486    {
2487       if (csp->expected_client_content_length != 0)
2488       {
2489          if (csp->expected_client_content_length < flushed)
2490          {
2491             log_error(LOG_LEVEL_ERROR,
2492                "Flushed %ld bytes of request body while only expecting %llu",
2493                flushed, csp->expected_client_content_length);
2494             csp->expected_client_content_length = 0;
2495          }
2496          else
2497          {
2498             log_error(LOG_LEVEL_CONNECT,
2499                "Flushed %ld bytes of request body while expecting %llu",
2500                flushed, csp->expected_client_content_length);
2501             csp->expected_client_content_length -= (unsigned)flushed;
2502             if (receive_and_send_encrypted_post_data(csp))
2503             {
2504                return 1;
2505             }
2506          }
2507       }
2508       else
2509       {
2510          log_error(LOG_LEVEL_CONNECT,
2511             "Flushed %ld bytes of request body", flushed);
2512       }
2513    }
2514
2515    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2516
2517    return 0;
2518
2519 }
2520
2521
2522 /*********************************************************************
2523  *
2524  * Function    :  receive_encrypted_request_headers
2525  *
2526  * Description :  Receives the encrypted request headers when
2527  *                https-inspecting.
2528  *
2529  * Parameters  :
2530  *          1  :  csp = Current client state (buffers, headers, etc...)
2531  *
2532  * Returns     :  JB_ERR_OK on success,
2533  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2534  *
2535  *********************************************************************/
2536 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2537 {
2538    char buf[BUFFER_SIZE];
2539    int len;
2540    char *p;
2541
2542    do
2543    {
2544       log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2545       if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2546           !data_is_available(csp->cfd, csp->config->socket_timeout))
2547       {
2548          log_error(LOG_LEVEL_CONNECT,
2549             "Socket %d timed out while waiting for client headers", csp->cfd);
2550          return JB_ERR_PARSE;
2551       }
2552       len = ssl_recv_data(&(csp->ssl_client_attr),
2553          (unsigned char *)buf, sizeof(buf));
2554       if (len == 0)
2555       {
2556          log_error(LOG_LEVEL_CONNECT,
2557             "Socket %d closed while waiting for client headers", csp->cfd);
2558          return JB_ERR_PARSE;
2559       }
2560       if (len == -1)
2561       {
2562          return JB_ERR_PARSE;
2563       }
2564       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2565       {
2566          return JB_ERR_MEMORY;
2567       }
2568       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2569    } while (p == NULL);
2570
2571    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2572
2573    return JB_ERR_OK;
2574 }
2575
2576
2577 /*********************************************************************
2578  *
2579  * Function    :  change_encrypted_request_destination
2580  *
2581  * Description :  Parse a (rewritten) request line from an encrypted
2582  *                request and regenerate the http request data.
2583  *
2584  * Parameters  :
2585  *          1  :  csp = Current client state (buffers, headers, etc...)
2586  *
2587  * Returns     :  Forwards the parse_http_request() return code.
2588  *                Terminates in case of memory problems.
2589  *
2590  *********************************************************************/
2591 static jb_err change_encrypted_request_destination(struct client_state *csp)
2592 {
2593    jb_err err;
2594    char *original_host = csp->http->host;
2595    int original_port = csp->http->port;
2596
2597    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2598       csp->https_headers->first->str);
2599    csp->http->host = NULL;
2600    free_http_request(csp->http);
2601    err = parse_http_request(csp->https_headers->first->str, csp->http);
2602    if (JB_ERR_OK != err)
2603    {
2604       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2605          jb_err_to_string(err));
2606       freez(original_host);
2607       return err;
2608    }
2609
2610    if (csp->http->host == NULL)
2611    {
2612       char port_string[10];
2613       /*
2614        * The rewritten request line did not specify a host
2615        * which means we can use the original host specified
2616        * by the client.
2617        */
2618       csp->http->host = original_host;
2619       csp->http->port = original_port;
2620       log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2621          csp->http->host);
2622       /*
2623        * If the rewritten request line didn't contain a host
2624        * it also didn't contain a port so we can reuse the host
2625        * port.
2626        */
2627       freez(csp->http->hostport);
2628       csp->http->hostport = strdup_or_die(csp->http->host);
2629       snprintf(port_string, sizeof(port_string), ":%d", original_port);
2630       err = string_append(&csp->http->hostport, port_string);
2631       if (err != JB_ERR_OK)
2632       {
2633          log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2634             jb_err_to_string(err));
2635          return err;
2636       }
2637
2638       /*
2639        * While the request line didn't mention it,
2640        * we're https-inspecting and want to speak TLS
2641        * with the server.
2642        */
2643       csp->http->server_ssl = 1;
2644       csp->http->ssl = 1;
2645    }
2646    else
2647    {
2648       /* The rewrite filter added a host so we can ditch the original */
2649       freez(original_host);
2650       csp->http->server_ssl = csp->http->ssl;
2651    }
2652
2653    csp->http->client_ssl = 1;
2654
2655    freez(csp->https_headers->first->str);
2656    build_request_line(csp, NULL, &csp->https_headers->first->str);
2657
2658    if (!server_use_ssl(csp))
2659    {
2660       log_error(LOG_LEVEL_REDIRECTS,
2661          "Rewritten request line results in downgrade to http");
2662       /*
2663        * Replace the unencryptd headers received with the
2664        * CONNECT request with the ones we received securely.
2665        */
2666       destroy_list(csp->headers);
2667       csp->headers->first = csp->https_headers->first;
2668       csp->headers->last  = csp->https_headers->last;
2669       csp->https_headers->first = NULL;
2670       csp->https_headers->last = NULL;
2671    }
2672
2673    return JB_ERR_OK;
2674
2675 }
2676
2677
2678 /*********************************************************************
2679  *
2680  * Function    :  process_encrypted_request_headers
2681  *
2682  * Description :  Receives and parses the encrypted headers send
2683  *                by the client when https-inspecting.
2684  *
2685  * Parameters  :
2686  *          1  :  csp = Current client state (buffers, headers, etc...)
2687  *
2688  * Returns     :  JB_ERR_OK on success,
2689  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2690  *
2691  *********************************************************************/
2692 static jb_err process_encrypted_request_headers(struct client_state *csp)
2693 {
2694    char *p;
2695    char *request_line;
2696    jb_err err;
2697    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2698    struct list header_list;
2699    struct list *headers = &header_list;
2700
2701    assert(csp->ssl_with_client_is_opened);
2702
2703 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2704    if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2705    {
2706       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2707    }
2708 #endif
2709    err = receive_encrypted_request_headers(csp);
2710    if (err != JB_ERR_OK)
2711    {
2712       if (csp->client_iob->cur == NULL ||
2713           csp->client_iob->cur == csp->client_iob->eod)
2714       {
2715          /*
2716           * We did not receive any data, most likely because the
2717           * client is done. Don't log this as a parse failure.
2718           */
2719          return JB_ERR_PARSE;
2720       }
2721       /* XXX: Also used for JB_ERR_MEMORY */
2722       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2723          jb_err_to_string(err));
2724       ssl_send_data_delayed(&(csp->ssl_client_attr),
2725          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2726       return err;
2727    }
2728
2729    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2730    request_line = get_header(csp->client_iob);
2731    if (request_line == NULL)
2732    {
2733       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2734       ssl_send_data_delayed(&(csp->ssl_client_attr),
2735          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2736       return JB_ERR_PARSE;
2737    }
2738    assert(*request_line != '\0');
2739
2740    if (client_protocol_is_unsupported(csp, request_line))
2741    {
2742       /*
2743        * If the protocol is unsupported we're done here.
2744        * client_protocol_is_unsupported() took care of sending
2745        * the error response and logging the error message.
2746        */
2747       return JB_ERR_PARSE;
2748    }
2749
2750 #ifdef FEATURE_FORCE_LOAD
2751    if (force_required(csp, request_line))
2752    {
2753       csp->flags |= CSP_FLAG_FORCED;
2754    }
2755 #endif /* def FEATURE_FORCE_LOAD */
2756
2757    free_http_request(csp->http);
2758
2759    err = parse_http_request(request_line, csp->http);
2760    /* XXX: Restore ssl setting. This is ugly */
2761    csp->http->client_ssl = 1;
2762    csp->http->server_ssl = 1;
2763
2764    freez(request_line);
2765    if (JB_ERR_OK != err)
2766    {
2767       ssl_send_data_delayed(&(csp->ssl_client_attr),
2768          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2769       /* XXX: Use correct size */
2770       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2771       log_error(LOG_LEVEL_ERROR,
2772          "Couldn't parse request line received from %s: %s",
2773          csp->ip_addr_str, jb_err_to_string(err));
2774
2775       free_http_request(csp->http);
2776       return JB_ERR_PARSE;
2777    }
2778
2779    /* Parse the rest of the client's headers. */
2780    init_list(headers);
2781    for (;;)
2782    {
2783       p = get_header(csp->client_iob);
2784
2785       if (p == NULL)
2786       {
2787          /* There are no additional headers to read. */
2788          break;
2789       }
2790       enlist(headers, p);
2791       freez(p);
2792    }
2793
2794    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2795    {
2796       /*
2797        * Our attempts to get the request destination
2798        * elsewhere failed.
2799        */
2800       log_error(LOG_LEVEL_ERROR,
2801          "Failed to get the encrypted request destination");
2802       ssl_send_data_delayed(&(csp->ssl_client_attr),
2803          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2804       return JB_ERR_PARSE;
2805    }
2806
2807    /* Split the domain we just got for pattern matching */
2808    init_domain_components(csp->http);
2809
2810 #ifdef FEATURE_CLIENT_TAGS
2811    /* XXX: If the headers were enlisted sooner, passing csp would do. */
2812    if (csp->client_address == NULL)
2813    {
2814       set_client_address(csp, headers);
2815       get_tag_list_for_client(csp->client_tags, csp->client_address);
2816    }
2817 #endif
2818
2819 #ifdef FEATURE_TOGGLE
2820    if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2821 #endif
2822    {
2823       /*
2824        * Determine the actions for this request after
2825        * clearing the ones from the previous one.
2826        */
2827       free_current_action(csp->action);
2828       get_url_actions(csp, csp->http);
2829    }
2830
2831    enlist(csp->https_headers, csp->http->cmd);
2832
2833    /* Append the previously read headers */
2834    err = list_append_list_unique(csp->https_headers, headers);
2835    destroy_list(headers);
2836    if (JB_ERR_OK != err)
2837    {
2838       /* XXX: Send error message */
2839       return err;
2840    }
2841
2842    /* XXX: Work around crash */
2843    csp->error_message = NULL;
2844
2845    /* XXX: Why do this here? */
2846    csp->http->ssl = 1;
2847
2848    err = sed_https(csp);
2849    if (JB_ERR_OK != err)
2850    {
2851       ssl_send_data_delayed(&(csp->ssl_client_attr),
2852          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2853       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2854          csp->ip_addr_str);
2855       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2856          csp->ip_addr_str, csp->http->cmd);
2857       return JB_ERR_PARSE;
2858    }
2859
2860    if ((NULL == csp->https_headers->first->str)
2861       || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2862          (JB_ERR_OK != change_encrypted_request_destination(csp))))
2863    {
2864       ssl_send_data_delayed(&(csp->ssl_client_attr),
2865          (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2866          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2867       log_error(LOG_LEVEL_ERROR,
2868          "Invalid request line after applying header filters.");
2869       /* XXX: Use correct size */
2870       log_error(LOG_LEVEL_CLF,
2871          "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2872
2873       return JB_ERR_PARSE;
2874    }
2875
2876    log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2877    log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2878       csp->http->path);
2879
2880    return err;
2881
2882 }
2883
2884 /*********************************************************************
2885  *
2886  * Function    :  cgi_page_requested
2887  *
2888  * Description :  Checks if a request is for an internal CGI page.
2889  *
2890  * Parameters  :
2891  *          1  :  host = The host requested by the client.
2892  *
2893  * Returns     :  1 if a CGI page has been requested, 0 otherwise
2894  *
2895  *********************************************************************/
2896 static int cgi_page_requested(const char *host)
2897 {
2898    if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2899     || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2900     || (0 == strcmpic(host, CGI_SITE_2_HOST))
2901     || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2902    {
2903       return 1;
2904    }
2905
2906    return 0;
2907
2908 }
2909
2910
2911 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2912 /*********************************************************************
2913  *
2914  * Function    :  continue_https_chat
2915  *
2916  * Description :  Behaves similar to chat() but only deals with
2917  *                https-inspected requests that arrive on an already
2918  *                established connection. The first request is always
2919  *                served by chat() which is a lot more complex as it
2920  *                has to deal with forwarding settings and connection
2921  *                failures etc.
2922  *
2923  *                If a connection to the server has already been
2924  *                opened it is reused unless the request is blocked
2925  *                or the forwarder changed.
2926  *
2927  *                If a connection to the server has not yet been
2928  *                opened (because the previous request was crunched),
2929  *                or the forwarder changed, the connection is dropped
2930  *                so that the client retries on a fresh one.
2931  *
2932  * Parameters  :
2933  *          1  :  csp = Current client state (buffers, headers, etc...)
2934  *
2935  * Returns     :  Nothing.
2936  *
2937  *********************************************************************/
2938 static void continue_https_chat(struct client_state *csp)
2939 {
2940    const struct forward_spec *fwd;
2941
2942    if (JB_ERR_OK != process_encrypted_request_headers(csp))
2943    {
2944       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2945       return;
2946    }
2947
2948    csp->requests_received_total++;
2949
2950    /*
2951     * We have an encrypted request. Check if one of the crunchers wants it.
2952     */
2953    if (crunch_response_triggered(csp, crunchers_all))
2954    {
2955       /*
2956        * Yes. The client got the crunch response and we're done here.
2957        */
2958       return;
2959    }
2960    if (csp->ssl_with_server_is_opened == 0)
2961    {
2962       log_error(LOG_LEVEL_CONNECT,
2963          "Dropping the client connection on socket %d. "
2964          "The server connection has not been established yet.",
2965          csp->cfd);
2966       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2967       return;
2968    }
2969    assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2970
2971    fwd = forward_url(csp, csp->http);
2972    if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2973    {
2974       log_error(LOG_LEVEL_CONNECT,
2975          "Dropping the client connection on socket %d with "
2976          "server socket %d connected to %s. The forwarder has changed.",
2977          csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2978       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2979       return;
2980    }
2981
2982    log_applied_actions(csp->action);
2983
2984    log_error(LOG_LEVEL_CONNECT,
2985       "Reusing server socket %d connected to %s. Requests already sent: %u.",
2986       csp->server_connection.sfd, csp->server_connection.host,
2987       csp->server_connection.requests_sent_total);
2988
2989    if (send_https_request(csp))
2990    {
2991       /*
2992        * Most likely the server connection timed out. We can't easily
2993        * create a new one so simply drop the client connection without a
2994        * error response to let the client retry.
2995        */
2996       log_error(LOG_LEVEL_CONNECT,
2997          "Dropping client connection on socket %d. "
2998          "Forwarding the encrypted client request failed.",
2999          csp->cfd);
3000       return;
3001    }
3002    csp->server_connection.request_sent = time(NULL);
3003    csp->server_connection.requests_sent_total++;
3004    handle_established_connection(csp);
3005    freez(csp->receive_buffer);
3006 }
3007 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3008 #endif
3009
3010
3011 /*********************************************************************
3012  *
3013  * Function    :  handle_established_connection
3014  *
3015  * Description :  Shuffle data between client and server once the
3016  *                connection has been established and the request
3017  *                has been sent.
3018  *
3019  * Parameters  :
3020  *          1  :  csp = Current client state (buffers, headers, etc...)
3021  *
3022  * Returns     :  Nothing.
3023  *
3024  *********************************************************************/
3025 static void handle_established_connection(struct client_state *csp)
3026 {
3027    char *hdr;
3028    char *p;
3029    int n;
3030 #ifdef HAVE_POLL
3031    struct pollfd poll_fds[2];
3032 #else
3033    fd_set rfds;
3034    jb_socket maxfd;
3035    struct timeval timeout;
3036 #endif
3037    int server_body;
3038    int ms_iis5_hack = 0;
3039    unsigned long long byte_count = 0;
3040    struct http_request *http;
3041    long len = 0; /* for buffer sizes (and negative error codes) */
3042    int buffer_and_filter_content = 0;
3043    unsigned int write_delay;
3044 #ifdef FEATURE_HTTPS_INSPECTION
3045    int ret = 0;
3046    int use_ssl_tunnel = 0;
3047    csp->dont_verify_certificate = 0;
3048
3049    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3050    {
3051       /* Pass encrypted content without filtering. */
3052       use_ssl_tunnel = 1;
3053    }
3054 #endif
3055
3056    /* Skeleton for HTTP response, if we should intercept the request */
3057    struct http_response *rsp;
3058 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3059    int watch_client_socket;
3060 #endif
3061
3062    csp->receive_buffer_size = csp->config->receive_buffer_size;
3063    csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3064    if (csp->receive_buffer == NULL)
3065    {
3066       log_error(LOG_LEVEL_ERROR,
3067          "Out of memory. Failed to allocate the receive buffer.");
3068       rsp = cgi_error_memory();
3069       send_crunch_response(csp, rsp);
3070       return;
3071    }
3072
3073    http = csp->http;
3074
3075 #ifndef HAVE_POLL
3076    maxfd = (csp->cfd > csp->server_connection.sfd) ?
3077       csp->cfd : csp->server_connection.sfd;
3078 #endif
3079
3080    /* pass data between the client and server
3081     * until one or the other shuts down the connection.
3082     */
3083
3084    server_body = 0;
3085
3086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3087    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3088 #endif
3089    write_delay = get_write_delay(csp);
3090
3091    for (;;)
3092    {
3093 #ifdef FEATURE_HTTPS_INSPECTION
3094       if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3095       {
3096          /*
3097           * It's possible that the TLS library already consumed all the
3098           * data the server intends to send. If that happens poll() and
3099           * select() will no longer see the data as available so we have
3100           * to skip the calls.
3101           */
3102          goto server_wants_to_talk;
3103       }
3104 #endif
3105 #ifndef HAVE_POLL
3106       FD_ZERO(&rfds);
3107 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3108       if (!watch_client_socket)
3109       {
3110          maxfd = csp->server_connection.sfd;
3111       }
3112       else
3113 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3114       {
3115          FD_SET(csp->cfd, &rfds);
3116       }
3117
3118       FD_SET(csp->server_connection.sfd, &rfds);
3119 #endif /* ndef HAVE_POLL */
3120
3121 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3122       if ((csp->flags & CSP_FLAG_CHUNKED)
3123          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3124          && ((csp->iob->eod - csp->iob->cur) >= 5)
3125          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3126       {
3127          /*
3128           * XXX: This check should be obsolete now,
3129           *      but let's wait a while to be sure.
3130           */
3131          log_error(LOG_LEVEL_CONNECT,
3132             "Looks like we got the last chunk together with "
3133             "the server headers but didn't detect it earlier. "
3134             "We better stop reading.");
3135          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3136          csp->expected_content_length = byte_count;
3137          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3138       }
3139       if (server_body && server_response_is_complete(csp, byte_count))
3140       {
3141          if (csp->expected_content_length == byte_count)
3142          {
3143             log_error(LOG_LEVEL_CONNECT,
3144                "Done reading from server. Content length: %llu as expected. "
3145                "Bytes most recently read: %ld.",
3146                byte_count, len);
3147          }
3148          else
3149          {
3150             log_error(LOG_LEVEL_CONNECT,
3151                "Done reading from server. Expected content length: %llu. "
3152                "Actual content length: %llu. Bytes most recently read: %ld.",
3153                csp->expected_content_length, byte_count, len);
3154          }
3155          len = 0;
3156          /*
3157           * XXX: Should not jump around, handle_established_connection()
3158           * is complicated enough already.
3159           */
3160          goto reading_done;
3161       }
3162 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3163
3164 #ifdef HAVE_POLL
3165       poll_fds[0].fd = csp->cfd;
3166 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3167       if (!watch_client_socket)
3168       {
3169          /*
3170           * Ignore incoming data, but still watch out
3171           * for disconnects etc. These flags are always
3172           * implied anyway but explicitly setting them
3173           * doesn't hurt.
3174           */
3175          poll_fds[0].events = POLLERR|POLLHUP;
3176       }
3177       else
3178 #endif
3179       {
3180          poll_fds[0].events = POLLIN;
3181       }
3182       poll_fds[1].fd = csp->server_connection.sfd;
3183       poll_fds[1].events = POLLIN;
3184       n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3185 #else
3186       timeout.tv_sec = csp->config->socket_timeout;
3187       timeout.tv_usec = 0;
3188       n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3189 #endif /* def HAVE_POLL */
3190
3191       /* Server or client not responding in timeout */
3192       if (n == 0)
3193       {
3194          log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3195             csp->config->socket_timeout, http->url);
3196          if ((byte_count == 0) && (http->ssl == 0))
3197          {
3198             send_crunch_response(csp, error_response(csp, "connection-timeout"));
3199          }
3200          mark_server_socket_tainted(csp);
3201 #ifdef FEATURE_HTTPS_INSPECTION
3202          close_client_and_server_ssl_connections(csp);
3203 #endif
3204          return;
3205       }
3206       else if (n < 0)
3207       {
3208 #ifdef HAVE_POLL
3209          log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3210 #else
3211          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3212 #endif
3213          mark_server_socket_tainted(csp);
3214 #ifdef FEATURE_HTTPS_INSPECTION
3215          close_client_and_server_ssl_connections(csp);
3216 #endif
3217          return;
3218       }
3219
3220       /*
3221        * This is the body of the browser's request,
3222        * just read and write it.
3223        *
3224        * Receives data from browser and sends it to server
3225        *
3226        * XXX: Make sure the client doesn't use pipelining
3227        * behind Privoxy's back.
3228        */
3229 #ifdef HAVE_POLL
3230       if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3231       {
3232          log_error(LOG_LEVEL_CONNECT,
3233             "The client socket %d has become unusable while "
3234             "the server socket %d is still open.",
3235             csp->cfd, csp->server_connection.sfd);
3236          mark_server_socket_tainted(csp);
3237          break;
3238       }
3239
3240       if (poll_fds[0].revents != 0)
3241 #else
3242       if (FD_ISSET(csp->cfd, &rfds))
3243 #endif /* def HAVE_POLL*/
3244       {
3245          int max_bytes_to_read = (int)csp->receive_buffer_size;
3246
3247 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3248          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3249          {
3250             if (data_is_available(csp->cfd, 0))
3251             {
3252                /*
3253                 * If the next request is already waiting, we have
3254                 * to stop select()ing the client socket. Otherwise
3255                 * we would always return right away and get nothing
3256                 * else done.
3257                 */
3258                watch_client_socket = 0;
3259                log_error(LOG_LEVEL_CONNECT,
3260                   "Stop watching client socket %d. "
3261                   "There's already another request waiting.",
3262                   csp->cfd);
3263                continue;
3264             }
3265             /*
3266              * If the client socket is set, but there's no data
3267              * available on the socket, the client went fishing
3268              * and continuing talking to the server makes no sense.
3269              */
3270             log_error(LOG_LEVEL_CONNECT,
3271                "The client closed socket %d while "
3272                "the server socket %d is still open.",
3273                csp->cfd, csp->server_connection.sfd);
3274             mark_server_socket_tainted(csp);
3275             break;
3276          }
3277          if (csp->expected_client_content_length != 0)
3278          {
3279             if (csp->expected_client_content_length < csp->receive_buffer_size)
3280             {
3281                max_bytes_to_read = (int)csp->expected_client_content_length;
3282             }
3283             log_error(LOG_LEVEL_CONNECT,
3284                "Waiting for up to %d bytes from the client.",
3285                max_bytes_to_read);
3286          }
3287          assert(max_bytes_to_read <= csp->receive_buffer_size);
3288 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3289
3290 #ifdef FEATURE_HTTPS_INSPECTION
3291          if (client_use_ssl(csp))
3292          {
3293             if (csp->http->status == 101)
3294             {
3295                len = ssl_recv_data(&(csp->ssl_client_attr),
3296                   (unsigned char *)csp->receive_buffer,
3297                   (size_t)max_bytes_to_read);
3298                if (len == -1)
3299                {
3300                   log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3301                      "on client socket %d for an upgraded connection",
3302                      csp->cfd);
3303                   break;
3304                }
3305                if (len == 0)
3306                {
3307                   log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3308                      "on client socket %d for an upgraded connection",
3309                      csp->cfd);
3310                   break;
3311                }
3312                byte_count += (unsigned long long)len;
3313                len = ssl_send_data(&(csp->ssl_server_attr),
3314                   (unsigned char *)csp->receive_buffer, (size_t)len);
3315                if (len == -1)
3316                {
3317                   log_error(LOG_LEVEL_ERROR, "Failed to send data "
3318                      "on server socket %d for an upgraded connection",
3319                      csp->server_connection.sfd);
3320                   break;
3321                }
3322                continue;
3323             }
3324             log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3325             break;
3326          }
3327          else
3328 #endif /* def FEATURE_HTTPS_INSPECTION */
3329          {
3330             len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3331
3332             if (len <= 0)
3333             {
3334                /* XXX: not sure if this is necessary. */
3335                mark_server_socket_tainted(csp);
3336                break; /* "game over, man" */
3337             }
3338
3339 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3340             if (csp->expected_client_content_length != 0)
3341             {
3342                assert(len <= max_bytes_to_read);
3343                csp->expected_client_content_length -= (unsigned)len;
3344                log_error(LOG_LEVEL_CONNECT,
3345                   "Expected client content length set to %llu "
3346                   "after reading %ld bytes.",
3347                   csp->expected_client_content_length, len);
3348                if (csp->expected_client_content_length == 0)
3349                {
3350                   log_error(LOG_LEVEL_CONNECT,
3351                      "Done reading from the client.");
3352                   csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3353                }
3354             }
3355 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3356
3357             if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3358             {
3359                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3360                mark_server_socket_tainted(csp);
3361                return;
3362             }
3363          }
3364          continue;
3365       }
3366
3367       /*
3368        * The server wants to talk. It could be the header or the body.
3369        * If `hdr' is null, then it's the header otherwise it's the body.
3370        * FIXME: Does `hdr' really mean `host'? No.
3371        */
3372 #ifdef HAVE_POLL
3373       if (poll_fds[1].revents != 0)
3374 #else
3375       if (FD_ISSET(csp->server_connection.sfd, &rfds))
3376 #endif /* HAVE_POLL */
3377       {
3378 #ifdef FEATURE_HTTPS_INSPECTION
3379          server_wants_to_talk:
3380 #endif
3381 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3382          /*
3383           * If we are buffering content, we don't want to eat up to
3384           * buffer-limit bytes if the client no longer cares about them.
3385           * If we aren't buffering, however, a dead client socket will be
3386           * noticed pretty much right away anyway, so we can reduce the
3387           * overhead by skipping the check.
3388           */
3389          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3390          {
3391 #ifdef _WIN32
3392             log_error(LOG_LEVEL_CONNECT,
3393                "The server still wants to talk, but the client may already have hung up on us.");
3394 #else
3395             log_error(LOG_LEVEL_CONNECT,
3396                "The server still wants to talk, but the client hung up on us.");
3397             mark_server_socket_tainted(csp);
3398 #ifdef FEATURE_HTTPS_INSPECTION
3399             close_client_and_server_ssl_connections(csp);
3400 #endif
3401             return;
3402 #endif /* def _WIN32 */
3403          }
3404 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3405
3406 #ifdef FEATURE_HTTPS_INSPECTION
3407          /*
3408           * Reading data from standard or secured connection (HTTP/HTTPS)
3409           */
3410          if (server_use_ssl(csp))
3411          {
3412             len = ssl_recv_data(&(csp->ssl_server_attr),
3413                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3414          }
3415          else
3416 #endif
3417          {
3418             len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3419                (int)csp->receive_buffer_size);
3420          }
3421
3422          if (len < 0)
3423          {
3424             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3425
3426             if ((http->ssl && (csp->fwd == NULL))
3427 #ifdef FEATURE_HTTPS_INSPECTION
3428                && use_ssl_tunnel
3429 #endif
3430                 )
3431             {
3432                /*
3433                 * Just hang up. We already confirmed the client's CONNECT
3434                 * request with status code 200 and unencrypted content is
3435                 * no longer welcome.
3436                 */
3437                log_error(LOG_LEVEL_ERROR,
3438                   "CONNECT already confirmed. Unable to tell the client about the problem.");
3439                return;
3440             }
3441             else if (byte_count)
3442             {
3443                /*
3444                 * Just hang up. We already transmitted the original headers
3445                 * and parts of the original content and therefore missed the
3446                 * chance to send an error message (without risking data corruption).
3447                 *
3448                 * XXX: we could retry with a fancy range request here.
3449                 */
3450                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3451                   "Unable to tell the client about the problem.");
3452                mark_server_socket_tainted(csp);
3453 #ifdef FEATURE_HTTPS_INSPECTION
3454                close_client_and_server_ssl_connections(csp);
3455 #endif
3456                return;
3457             }
3458             /*
3459              * XXX: Consider handling the cases above the same.
3460              */
3461             mark_server_socket_tainted(csp);
3462             len = 0;
3463          }
3464
3465 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3466          if (csp->flags & CSP_FLAG_CHUNKED)
3467          {
3468             if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3469             {
3470                /* XXX: this is a temporary hack */
3471                log_error(LOG_LEVEL_CONNECT,
3472                   "Looks like we reached the end of the last chunk. "
3473                   "We better stop reading.");
3474                csp->expected_content_length = byte_count + (unsigned long long)len;
3475                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3476             }
3477          }
3478          reading_done:
3479 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3480
3481          /*
3482           * This is guaranteed by allocating with zalloc_or_die()
3483           * and never (intentionally) writing to the last byte.
3484           *
3485           * csp->receive_buffer_size is the size of the part of the
3486           * buffer we intentionally write to, but we actually
3487           * allocated csp->receive_buffer_size+1 bytes so the assertion
3488           * stays within the allocated range.
3489           */
3490          assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3491
3492          /*
3493           * Add a trailing zero to let be able to use string operations.
3494           * XXX: do we still need this with filter_popups gone?
3495           */
3496          assert(len <= csp->receive_buffer_size);
3497          csp->receive_buffer[len] = '\0';
3498
3499          /*
3500           * Normally, this would indicate that we've read
3501           * as much as the server has sent us and we can
3502           * close the client connection.  However, Microsoft
3503           * in its wisdom has released IIS/5 with a bug that
3504           * prevents it from sending the trailing \r\n in
3505           * a 302 redirect header (and possibly other headers).
3506           * To work around this if we've haven't parsed
3507           * a full header we'll append a trailing \r\n
3508           * and see if this now generates a valid one.
3509           *
3510           * This hack shouldn't have any impacts.  If we've
3511           * already transmitted the header or if this is a
3512           * SSL connection, then we won't bother with this
3513           * hack.  So we only work on partially received
3514           * headers.  If we append a \r\n and this still
3515           * doesn't generate a valid header, then we won't
3516           * transmit anything to the client.
3517           */
3518          if (len == 0)
3519          {
3520
3521             if (server_body || (http->ssl
3522 #ifdef FEATURE_HTTPS_INSPECTION
3523                   && use_ssl_tunnel
3524 #endif
3525                ))
3526             {
3527                /*
3528                 * If we have been buffering up the document,
3529                 * now is the time to apply content modification
3530                 * and send the result to the client.
3531                 */
3532                if (buffer_and_filter_content)
3533                {
3534                   p = execute_content_filters(csp);
3535                   /*
3536                    * If content filtering fails, use the original
3537                    * buffer and length.
3538                    * (see p != NULL ? p : csp->iob->cur below)
3539                    */
3540                   if (NULL == p)
3541                   {
3542                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3543                   }
3544 #ifdef FEATURE_COMPRESSION
3545                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3546                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3547                   {
3548                      char *compressed_content = compress_buffer(p,
3549                         (size_t *)&csp->content_length, csp->config->compression_level);
3550                      if (compressed_content != NULL)
3551                      {
3552                         freez(p);
3553                         p = compressed_content;
3554                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3555                      }
3556                   }
3557 #endif
3558
3559                   if (JB_ERR_OK != update_server_headers(csp))
3560                   {
3561                      log_error(LOG_LEVEL_FATAL,
3562                         "Failed to update server headers. after filtering.");
3563                   }
3564
3565                   hdr = list_to_text(csp->headers);
3566                   if (hdr == NULL)
3567                   {
3568                      /* FIXME Should handle error properly */
3569                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3570                   }
3571
3572 #ifdef FEATURE_HTTPS_INSPECTION
3573                   /*
3574                    * Sending data with standard or secured connection (HTTP/HTTPS)
3575                    */
3576                   if (client_use_ssl(csp))
3577                   {
3578                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3579                               (const unsigned char *)hdr, strlen(hdr),
3580                               get_write_delay(csp)) < 0)
3581                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3582                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3583                               csp->content_length, get_write_delay(csp)) < 0))
3584                      {
3585                         log_error(LOG_LEVEL_ERROR,
3586                            "Failed to send the modified content to the client over TLS");
3587                         freez(hdr);
3588                         freez(p);
3589                         mark_server_socket_tainted(csp);
3590                         close_client_and_server_ssl_connections(csp);
3591                         return;
3592                      }
3593                   }
3594                   else
3595 #endif /* def FEATURE_HTTPS_INSPECTION */
3596                   {
3597                      if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3598                       || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3599                          (size_t)csp->content_length, write_delay))
3600                      {
3601                         log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3602                         freez(hdr);
3603                         freez(p);
3604                         mark_server_socket_tainted(csp);
3605                         return;
3606                      }
3607                   }
3608
3609                   freez(hdr);
3610                   freez(p);
3611                }
3612
3613                break; /* "game over, man" */
3614             }
3615
3616             /*
3617              * This is not the body, so let's pretend the server just sent
3618              * us a blank line.
3619              */
3620             snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3621             len = (int)strlen(csp->receive_buffer);
3622
3623             /*
3624              * Now, let the normal header parsing algorithm below do its
3625              * job.  If it fails, we'll exit instead of continuing.
3626              */
3627
3628             ms_iis5_hack = 1;
3629          }
3630
3631          /*
3632           * If we're in the body of the server document, just write it to
3633           * the client, unless we need to buffer the body for later
3634           * content-filtering.
3635           */
3636          if (server_body || (http->ssl
3637 #ifdef FEATURE_HTTPS_INSPECTION
3638                && use_ssl_tunnel
3639 #endif
3640             ))
3641          {
3642             if (buffer_and_filter_content)
3643             {
3644                /*
3645                 * If there is no memory left for buffering the content, or the buffer limit
3646                 * has been reached, switch to non-filtering mode, i.e. make & write the
3647                 * header, flush the iob and buf, and get out of the way.
3648                 */
3649                if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3650                {
3651                   size_t hdrlen;
3652                   long flushed;
3653
3654                   log_error(LOG_LEVEL_INFO,
3655                      "Flushing header and buffers. Stepping back from filtering.");
3656
3657                   hdr = list_to_text(csp->headers);
3658                   if (hdr == NULL)
3659                   {
3660                      /*
3661                       * Memory is too tight to even generate the header.
3662                       * Send our static "Out-of-memory" page.
3663                       */
3664                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3665                      rsp = cgi_error_memory();
3666                      send_crunch_response(csp, rsp);
3667                      mark_server_socket_tainted(csp);
3668 #ifdef FEATURE_HTTPS_INSPECTION
3669                      close_client_and_server_ssl_connections(csp);
3670 #endif
3671                      return;
3672                   }
3673                   hdrlen = strlen(hdr);
3674
3675 #ifdef FEATURE_HTTPS_INSPECTION
3676                   /*
3677                    * Sending data with standard or secured connection (HTTP/HTTPS)
3678                    */
3679                   if (client_use_ssl(csp))
3680                   {
3681                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3682                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3683                         || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3684                                 csp->iob)) < 0)
3685                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3686                               (const unsigned char *)csp->receive_buffer, (size_t)len,
3687                               get_write_delay(csp)) < 0))
3688                      {
3689                         log_error(LOG_LEVEL_CONNECT,
3690                            "Flush header and buffers to client failed");
3691                         freez(hdr);
3692                         mark_server_socket_tainted(csp);
3693                         close_client_and_server_ssl_connections(csp);
3694                         return;
3695                      }
3696                   }
3697                   else
3698 #endif /* def FEATURE_HTTPS_INSPECTION */
3699                   {
3700                      if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3701                       || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3702                       || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3703                             write_delay))
3704                      {
3705                         log_error(LOG_LEVEL_CONNECT,
3706                            "Flush header and buffers to client failed: %E");
3707                         freez(hdr);
3708                         mark_server_socket_tainted(csp);
3709                         return;
3710                      }
3711                   }
3712
3713                   /*
3714                    * Reset the byte_count to the amount of bytes
3715                    * we just flushed. len will be added a few lines below,
3716                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
3717                    */
3718                   byte_count = (unsigned long long)flushed;
3719                   freez(hdr);
3720                   buffer_and_filter_content = 0;
3721                   server_body = 1;
3722                }
3723             }
3724             else
3725             {
3726 #ifdef FEATURE_HTTPS_INSPECTION
3727                /*
3728                 * Sending data with standard or secured connection (HTTP/HTTPS)
3729                 */
3730                if (client_use_ssl(csp))
3731                {
3732                   ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3733                      (const unsigned char *)csp->receive_buffer, (size_t)len,
3734                      get_write_delay(csp));
3735                   if (ret < 0)
3736                   {
3737                      log_error(LOG_LEVEL_ERROR,
3738                         "Sending data to client failed");
3739                      mark_server_socket_tainted(csp);
3740                      close_client_and_server_ssl_connections(csp);
3741                      return;
3742                   }
3743                }
3744                else
3745 #endif /* def FEATURE_HTTPS_INSPECTION */
3746                {
3747                   if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3748                         (size_t)len, write_delay))
3749                   {
3750                      log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3751                      mark_server_socket_tainted(csp);
3752                      return;
3753                   }
3754                }
3755             }
3756             byte_count += (unsigned long long)len;
3757             continue;
3758          }
3759          else
3760          {
3761             /*
3762              * We're still looking for the end of the server's header.
3763              * Buffer up the data we just read.  If that fails, there's
3764              * little we can do but send our static out-of-memory page.
3765              */
3766             if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3767             {
3768                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3769                rsp = cgi_error_memory();
3770                send_crunch_response(csp, rsp);
3771                mark_server_socket_tainted(csp);
3772 #ifdef FEATURE_HTTPS_INSPECTION
3773                close_client_and_server_ssl_connections(csp);
3774 #endif
3775                return;
3776             }
3777
3778             /* Convert iob into something sed() can digest */
3779             if (JB_ERR_PARSE == get_server_headers(csp))
3780             {
3781                if (ms_iis5_hack)
3782                {
3783                   /*
3784                    * Well, we tried our MS IIS/5 hack and it didn't work.
3785                    * The header is incomplete and there isn't anything
3786                    * we can do about it.
3787                    */
3788                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3789                      "Applying the MS IIS5 hack didn't help.");
3790                   log_error(LOG_LEVEL_CLF,
3791                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3792 #ifdef FEATURE_HTTPS_INSPECTION
3793                   /*
3794                    * Sending data with standard or secured connection (HTTP/HTTPS)
3795                    */
3796                   if (client_use_ssl(csp))
3797                   {
3798                      ssl_send_data_delayed(&(csp->ssl_client_attr),
3799                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3800                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3801                   }
3802                   else
3803 #endif /* def FEATURE_HTTPS_INSPECTION */
3804                   {
3805                      write_socket_delayed(csp->cfd,
3806                         INVALID_SERVER_HEADERS_RESPONSE,
3807                         strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3808                   }
3809                   mark_server_socket_tainted(csp);
3810 #ifdef FEATURE_HTTPS_INSPECTION
3811                   close_client_and_server_ssl_connections(csp);
3812 #endif
3813                   return;
3814                }
3815                else
3816                {
3817                   /*
3818                    * Since we have to wait for more from the server before
3819                    * we can parse the headers we just continue here.
3820                    */
3821                   log_error(LOG_LEVEL_CONNECT,
3822                      "Continuing buffering server headers from socket %d. "
3823                      "Bytes most recently read: %ld.", csp->cfd, len);
3824                   continue;
3825                }
3826             }
3827             else
3828             {
3829                /*
3830                 * Account for the content bytes we
3831                 * might have gotten with the headers.
3832                 */
3833                assert(csp->iob->eod >= csp->iob->cur);
3834                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3835             }
3836
3837             /* Did we actually get anything? */
3838             if (NULL == csp->headers->first)
3839             {
3840                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3841                {
3842                   log_error(LOG_LEVEL_ERROR,
3843                      "No server or forwarder response received on socket %d. "
3844                      "Closing client socket %d without sending data.",
3845                      csp->server_connection.sfd, csp->cfd);
3846                   log_error(LOG_LEVEL_CLF,
3847                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3848                }
3849                else
3850                {
3851                   log_error(LOG_LEVEL_ERROR,
3852                      "No server or forwarder response received on socket %d.",
3853                      csp->server_connection.sfd);
3854                   send_crunch_response(csp, error_response(csp, "no-server-data"));
3855                }
3856                free_http_request(http);
3857                mark_server_socket_tainted(csp);
3858 #ifdef FEATURE_HTTPS_INSPECTION
3859                close_client_and_server_ssl_connections(csp);
3860 #endif
3861                return;
3862             }
3863
3864             if (!csp->headers->first->str)
3865             {
3866                log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3867             }
3868             assert(csp->headers->first->str);
3869
3870             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3871                 strncmpic(csp->headers->first->str, "ICY", 3))
3872             {
3873                /*
3874                 * It doesn't look like a HTTP (or Shoutcast) response:
3875                 * tell the client and log the problem.
3876                 */
3877                if (strlen(csp->headers->first->str) > 30)
3878                {
3879                   csp->headers->first->str[30] = '\0';
3880                }
3881                log_error(LOG_LEVEL_ERROR,
3882                   "Invalid server or forwarder response. Starts with: %s",
3883                   csp->headers->first->str);
3884                log_error(LOG_LEVEL_CLF,
3885                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3886 #ifdef FEATURE_HTTPS_INSPECTION
3887                /*
3888                 * Sending data with standard or secured connection (HTTP/HTTPS)
3889                 */
3890                if (client_use_ssl(csp))
3891                {
3892                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3893                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3894                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3895                      get_write_delay(csp));
3896                }
3897                else
3898 #endif /* def FEATURE_HTTPS_INSPECTION */
3899                {
3900                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3901                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3902                }
3903                free_http_request(http);
3904                mark_server_socket_tainted(csp);
3905 #ifdef FEATURE_HTTPS_INSPECTION
3906                close_client_and_server_ssl_connections(csp);
3907 #endif
3908                return;
3909             }
3910
3911             /*
3912              * Disable redirect checkers, so that they will be only run
3913              * again if the user also enables them through tags.
3914              *
3915              * From a performance point of view it doesn't matter,
3916              * but it prevents duplicated log messages.
3917              */
3918 #ifdef FEATURE_FAST_REDIRECTS
3919             csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3920 #endif
3921             csp->action->flags &= ~ACTION_REDIRECT;
3922
3923             /*
3924              * We have now received the entire server header,
3925              * filter it and send the result to the client
3926              */
3927             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3928             {
3929                log_error(LOG_LEVEL_CLF,
3930                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3931 #ifdef FEATURE_HTTPS_INSPECTION
3932                /*
3933                 * Sending data with standard or secured connection (HTTP/HTTPS)
3934                 */
3935                if (client_use_ssl(csp))
3936                {
3937                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3938                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3939                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3940                      get_write_delay(csp));
3941                }
3942                else
3943 #endif
3944                {
3945                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3946                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3947                }
3948                free_http_request(http);
3949                mark_server_socket_tainted(csp);
3950 #ifdef FEATURE_HTTPS_INSPECTION
3951                close_client_and_server_ssl_connections(csp);
3952 #endif
3953                return;
3954             }
3955             hdr = list_to_text(csp->headers);
3956             if (hdr == NULL)
3957             {
3958                /* FIXME Should handle error properly */
3959                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3960             }
3961
3962             if ((csp->flags & CSP_FLAG_CHUNKED)
3963                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3964                && ((csp->iob->eod - csp->iob->cur) >= 5)
3965                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3966             {
3967                log_error(LOG_LEVEL_CONNECT,
3968                   "Looks like we got the last chunk together with "
3969                   "the server headers. We better stop reading.");
3970                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3971                csp->expected_content_length = byte_count;
3972                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3973             }
3974
3975             csp->server_connection.response_received = time(NULL);
3976
3977             if (crunch_response_triggered(csp, crunchers_light))
3978             {
3979                /*
3980                 * One of the tags created by a server-header
3981                 * tagger triggered a crunch. We already
3982                 * delivered the crunch response to the client
3983                 * and are done here after cleaning up.
3984                 */
3985                freez(hdr);
3986                mark_server_socket_tainted(csp);
3987 #ifdef FEATURE_HTTPS_INSPECTION
3988                close_client_and_server_ssl_connections(csp);
3989 #endif
3990                return;
3991             }
3992
3993             /* Buffer and pcrs filter this if appropriate. */
3994             buffer_and_filter_content = content_requires_filtering(csp);
3995
3996             if (!buffer_and_filter_content)
3997             {
3998                /*
3999                 * Write the server's (modified) header to
4000                 * the client (along with anything else that
4001                 * may be in the buffer). Use standard or secured
4002                 * connection.
4003                 */
4004 #ifdef FEATURE_HTTPS_INSPECTION
4005                if (client_use_ssl(csp))
4006                {
4007                   if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
4008                           (const unsigned char *)hdr, strlen(hdr),
4009                           get_write_delay(csp)) < 0)
4010                      || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4011                             csp->iob)) < 0))
4012                   {
4013                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
4014
4015                      /*
4016                       * The write failed, so don't bother mentioning it
4017                       * to the client... it probably can't hear us anyway.
4018                       */
4019                      freez(hdr);
4020                      mark_server_socket_tainted(csp);
4021 #ifdef FEATURE_HTTPS_INSPECTION
4022                      close_client_and_server_ssl_connections(csp);
4023 #endif
4024                      return;
4025                   }
4026                }
4027                else
4028 #endif /* def FEATURE_HTTPS_INSPECTION */
4029                {
4030                   if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4031                      || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4032                   {
4033                      log_error(LOG_LEVEL_ERROR,
4034                         "write header to client failed");
4035                      /*
4036                       * The write failed, so don't bother mentioning it
4037                       * to the client... it probably can't hear us anyway.
4038                       */
4039                      freez(hdr);
4040                      mark_server_socket_tainted(csp);
4041                      return;
4042                   }
4043                }
4044                                 }
4045
4046             /* we're finished with the server's header */
4047
4048             freez(hdr);
4049             server_body = 1;
4050
4051             /*
4052              * If this was a MS IIS/5 hack then it means the server
4053              * has already closed the connection. Nothing more to read.
4054              * Time to bail.
4055              */
4056             if (ms_iis5_hack)
4057             {
4058                log_error(LOG_LEVEL_ERROR,
4059                   "Closed server connection detected. "
4060                   "Applying the MS IIS5 hack didn't help.");
4061                log_error(LOG_LEVEL_CLF,
4062                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4063 #ifdef FEATURE_HTTPS_INSPECTION
4064                /*
4065                 * Sending data with standard or secured connection (HTTP/HTTPS)
4066                 */
4067                if (client_use_ssl(csp))
4068                {
4069                   ssl_send_data_delayed(&(csp->ssl_client_attr),
4070                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4071                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
4072                      get_write_delay(csp));
4073                }
4074                else
4075 #endif /* def FEATURE_HTTPS_INSPECTION */
4076                {
4077                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4078                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4079                }
4080                mark_server_socket_tainted(csp);
4081 #ifdef FEATURE_HTTPS_INSPECTION
4082                close_client_and_server_ssl_connections(csp);
4083 #endif
4084                return;
4085             }
4086          }
4087          continue;
4088       }
4089       mark_server_socket_tainted(csp);
4090 #ifdef FEATURE_HTTPS_INSPECTION
4091       close_client_and_server_ssl_connections(csp);
4092 #endif
4093       return; /* huh? we should never get here */
4094    }
4095
4096    if (csp->content_length == 0)
4097    {
4098       /*
4099        * If Privoxy didn't recalculate the Content-Length,
4100        * byte_count is still correct.
4101        */
4102       csp->content_length = byte_count;
4103    }
4104
4105 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4106    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4107       && (csp->expected_content_length != byte_count))
4108    {
4109       log_error(LOG_LEVEL_CONNECT,
4110          "Received %llu bytes while expecting %llu.",
4111          byte_count, csp->expected_content_length);
4112       mark_server_socket_tainted(csp);
4113    }
4114 #endif
4115
4116 #ifdef FEATURE_HTTPS_INSPECTION
4117    if (client_use_ssl(csp))
4118    {
4119       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4120          csp->ip_addr_str, http->gpc, http->hostport, http->path,
4121          http->version, csp->content_length);
4122    }
4123    else
4124 #endif
4125    {
4126       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4127          csp->ip_addr_str, http->ocmd, csp->content_length);
4128    }
4129    csp->server_connection.timestamp = time(NULL);
4130 }
4131
4132
4133 /*********************************************************************
4134  *
4135  * Function    :  chat
4136  *
4137  * Description :  Once a connection from the client has been accepted,
4138  *                this function is called (via serve()) to handle the
4139  *                main business of the communication.  This function
4140  *                returns after dealing with a single request. It can
4141  *                be called multiple times with the same client socket
4142  *                if the client is keeping the connection alive.
4143  *
4144  *                The decision whether or not a client connection will
4145  *                be kept alive is up to the caller which also must
4146  *                close the client socket when done.
4147  *
4148  *                FIXME: chat is nearly thousand lines long.
4149  *                Ridiculous.
4150  *
4151  * Parameters  :
4152  *          1  :  csp = Current client state (buffers, headers, etc...)
4153  *
4154  * Returns     :  Nothing.
4155  *
4156  *********************************************************************/
4157 static void chat(struct client_state *csp)
4158 {
4159    const struct forward_spec *fwd;
4160    struct http_request *http;
4161    /* Skeleton for HTTP response, if we should intercept the request */
4162    struct http_response *rsp;
4163 #ifdef FEATURE_HTTPS_INSPECTION
4164    int use_ssl_tunnel = 0;
4165 #endif
4166
4167    http = csp->http;
4168
4169    if (receive_client_request(csp) != JB_ERR_OK)
4170    {
4171       return;
4172    }
4173    if (parse_client_request(csp) != JB_ERR_OK)
4174    {
4175       return;
4176    }
4177
4178 #ifdef FEATURE_HTTPS_INSPECTION
4179    /*
4180     * Setting flags to use old solution with SSL tunnel and to disable
4181     * certificate verification.
4182     */
4183    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4184       && !cgi_page_requested(csp->http->host))
4185    {
4186       use_ssl_tunnel = 1;
4187    }
4188
4189    if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4190    {
4191       csp->dont_verify_certificate = 1;
4192    }
4193 #endif
4194
4195    /*
4196     * build the http request to send to the server
4197     * we have to do one of the following:
4198     *
4199     * create =    use the original HTTP request to create a new
4200     *             HTTP request that has either the path component
4201     *             without the http://domainspec (w/path) or the
4202     *             full orininal URL (w/url)
4203     *             Note that the path and/or the HTTP version may
4204     *             have been altered by now.
4205     *
4206     * SSL proxy = Open a socket to the host:port of the server
4207     *             and create TLS/SSL connection with server and
4208     *             with client. Then behave like mediator between
4209     *             client and server over TLS/SSL.
4210     *
4211     * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4212     *    with     request to a parent proxy. Note that we'll be sending
4213     * forwarding  the CFAIL message ourselves if connecting to the parent
4214     *             fails, but we won't send a CSUCCEED message if it works,
4215     *             since that would result in a double message (ours and the
4216     *             parent's). After sending the request to the parent, we
4217     *             must parse answer and send it to client. If connection
4218     *             with server is established, we do TLS/SSL proxy. Otherwise
4219     *             we send parent response to client and close connections.
4220     *
4221     * here's the matrix:
4222     *                        SSL
4223     *                    0        1
4224     *                +--------+--------+
4225     *                |        |        |
4226     *             0  | create |   SSL  |
4227     *                | w/path |  proxy |
4228     *  Forwarding    +--------+--------+
4229     *                |        |   SSL  |
4230     *             1  | create |  proxy |
4231     *                | w/url  |+forward|
4232     *                +--------+--------+
4233     *
4234     */
4235
4236 #ifdef FEATURE_HTTPS_INSPECTION
4237    /*
4238     * Presetting SSL client and server flags
4239     */
4240    if (http->ssl && !use_ssl_tunnel)
4241    {
4242       http->client_ssl = 1;
4243       http->server_ssl = 1;
4244    }
4245    else
4246    {
4247       http->client_ssl = 0;
4248       http->server_ssl = 0;
4249    }
4250 #endif
4251
4252 #ifdef FEATURE_HTTPS_INSPECTION
4253    /*
4254     * Log the request unless we're https inspecting
4255     * in which case we don't have the path yet and
4256     * will log the request later.
4257     */
4258    if (!client_use_ssl(csp))
4259 #endif
4260    {
4261       log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4262    }
4263
4264    if (http->ssl && connect_port_is_forbidden(csp))
4265    {
4266       const char *acceptable_connect_ports =
4267          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4268       assert(NULL != acceptable_connect_ports);
4269       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4270          "limit-connect{%s} doesn't allow CONNECT requests to %s",
4271          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4272       csp->action->flags |= ACTION_BLOCK;
4273       http->ssl = 0;
4274 #ifdef FEATURE_HTTPS_INSPECTION
4275       http->client_ssl = 0;
4276       http->server_ssl = 0;
4277 #endif
4278    }
4279
4280    /*
4281     * We have a request. Check if one of the crunchers wants it
4282     * unless the client wants to use TLS/SSL in which case we
4283     * haven't setup the TLS context yet and will send the crunch
4284     * response later.
4285     */
4286    if (
4287 #ifdef FEATURE_HTTPS_INSPECTION
4288        !client_use_ssl(csp) &&
4289 #endif
4290        crunch_response_triggered(csp, crunchers_all))
4291    {
4292       /*
4293        * Yes. The client got the crunch response and we're done here.
4294        */
4295       return;
4296    }
4297
4298 #ifdef FEATURE_HTTPS_INSPECTION
4299    if (client_use_ssl(csp) && !use_ssl_tunnel)
4300    {
4301       int ret;
4302       /*
4303        * Creating a SSL proxy.
4304        *
4305        * By sending the CSUCCEED message we're lying to the client as
4306        * the connection hasn't actually been established yet. We don't
4307        * establish the connection until we have seen and parsed the
4308        * encrypted client headers.
4309        */
4310       if (write_socket_delayed(csp->cfd, CSUCCEED,
4311             strlen(CSUCCEED), get_write_delay(csp)) != 0)
4312       {
4313          log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4314          return;
4315       }
4316
4317       ret = create_client_ssl_connection(csp);
4318       if (ret != 0)
4319       {
4320          log_error(LOG_LEVEL_ERROR,
4321             "Failed to open a secure connection with the client");
4322          return;
4323       }
4324       if (JB_ERR_OK != process_encrypted_request_headers(csp))
4325       {
4326          close_client_ssl_connection(csp);
4327          return;
4328       }
4329       /*
4330        * We have an encrypted request. Check if one of the crunchers now
4331        * wants it (for example because the previously invisible path was
4332        * required to match).
4333        */
4334       if (crunch_response_triggered(csp, crunchers_all))
4335       {
4336          /*
4337           * Yes. The client got the crunch response and we're done here.
4338           */
4339          return;
4340       }
4341    }
4342 #endif
4343
4344    log_applied_actions(csp->action);
4345
4346    /* decide how to route the HTTP request */
4347    fwd = forward_url(csp, http);
4348
4349    freez(csp->headers->first->str);
4350    build_request_line(csp, fwd, &csp->headers->first->str);
4351
4352    if (fwd->forward_host)
4353    {
4354       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4355          fwd->forward_host, fwd->forward_port, http->hostport);
4356    }
4357    else
4358    {
4359       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4360    }
4361
4362    /* here we connect to the server, gateway, or the forwarder */
4363
4364 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4365    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4366       && socket_is_still_alive(csp->server_connection.sfd)
4367       && connection_destination_matches(&csp->server_connection, http, fwd))
4368    {
4369       log_error(LOG_LEVEL_CONNECT,
4370          "Reusing server socket %d connected to %s. Total requests: %u.",
4371          csp->server_connection.sfd, csp->server_connection.host,
4372          csp->server_connection.requests_sent_total);
4373    }
4374    else
4375    {
4376       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4377       {
4378 #ifdef FEATURE_CONNECTION_SHARING
4379          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4380 #ifdef FEATURE_HTTPS_INSPECTION
4381             && !server_use_ssl(csp)
4382 #endif
4383             )
4384          {
4385             remember_connection(&csp->server_connection);
4386          }
4387          else
4388 #endif /* def FEATURE_CONNECTION_SHARING */
4389          {
4390             log_error(LOG_LEVEL_CONNECT,
4391                "Closing server socket %d connected to %s. Total requests: %u.",
4392                csp->server_connection.sfd, csp->server_connection.host,
4393                csp->server_connection.requests_sent_total);
4394             close_socket(csp->server_connection.sfd);
4395          }
4396          mark_connection_closed(&csp->server_connection);
4397       }
4398 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4399
4400       /*
4401        * Connecting to destination server
4402        */
4403       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4404
4405       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4406       {
4407          if (fwd->type != SOCKS_NONE)
4408          {
4409             /* Socks error. */
4410             rsp = error_response(csp, "forwarding-failed");
4411          }
4412          else if (errno == EINVAL)
4413          {
4414             rsp = error_response(csp, "no-such-domain");
4415          }
4416          else
4417          {
4418             rsp = error_response(csp, "connect-failed");
4419          }
4420
4421          /* Write the answer to the client */
4422          if (rsp != NULL)
4423          {
4424             send_crunch_response(csp, rsp);
4425          }
4426
4427          /*
4428           * Temporary workaround to prevent already-read client
4429           * bodies from being parsed as new requests. For now we
4430           * err on the safe side and throw all the following
4431           * requests under the bus, even if no client body has been
4432           * buffered. A compliant client will repeat the dropped
4433           * requests on an untainted connection.
4434           *
4435           * The proper fix is to discard the no longer needed
4436           * client body in the buffer (if there is one) and to
4437           * continue parsing the bytes that follow.
4438           */
4439 #ifdef FEATURE_HTTPS_INSPECTION
4440          close_client_ssl_connection(csp);
4441 #endif
4442          drain_and_close_socket(csp->cfd);
4443          csp->cfd = JB_INVALID_SOCKET;
4444
4445          return;
4446       }
4447
4448 #ifdef FEATURE_HTTPS_INSPECTION
4449       /*
4450        * Creating TLS/SSL connections with destination server or parent
4451        * proxy. If forwarding is enabled, we must send client request to
4452        * parent proxy and receive, parse and resend parent proxy answer.
4453        */
4454       if (http->ssl && !use_ssl_tunnel)
4455       {
4456          if (fwd->forward_host != NULL)
4457          {
4458             char server_response[BUFFER_SIZE];
4459             int ret = 0;
4460             int len = 0;
4461             char *hdr = list_to_text(csp->headers);
4462             memset(server_response, 0, sizeof(server_response));
4463
4464             if (hdr == NULL)
4465             {
4466                log_error(LOG_LEVEL_FATAL,
4467                   "Out of memory parsing client header");
4468             }
4469             list_remove_all(csp->headers);
4470
4471             /*
4472              * Sending client's CONNECT request to the parent proxy
4473              */
4474             ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4475
4476             freez(hdr);
4477
4478             if (ret != 0)
4479             {
4480                log_error(LOG_LEVEL_CONNECT,
4481                   "Sending request headers to: %s failed", http->hostport);
4482                mark_server_socket_tainted(csp);
4483                close_client_ssl_connection(csp);
4484                return;
4485             }
4486
4487             /* Waiting for parent proxy server response */
4488             len = read_socket(csp->server_connection.sfd, server_response,
4489                sizeof(server_response)-1);
4490
4491             if (len <= 0)
4492             {
4493                log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4494                   "server on socket %d.", csp->server_connection.sfd);
4495
4496                rsp = error_response(csp, "no-server-data");
4497                if (rsp)
4498                {
4499                   send_crunch_response(csp, rsp);
4500                }
4501                mark_server_socket_tainted(csp);
4502                close_client_ssl_connection(csp);
4503                return;
4504             }
4505
4506             /*
4507              * Test if the connection to the destination server was
4508              * established successfully by the parent proxy.
4509              */
4510             if (!tunnel_established_successfully(server_response, (unsigned int)len))
4511             {
4512                log_error(LOG_LEVEL_ERROR,
4513                   "The forwarder %s failed to establish a connection with %s",
4514                   fwd->forward_host, http->host);
4515                rsp = error_response(csp, "connect-failed");
4516                if (rsp)
4517                {
4518                   send_crunch_response(csp, rsp);
4519                }
4520                mark_server_socket_tainted(csp);
4521                close_client_ssl_connection(csp);
4522                return;
4523             }
4524          } /* -END- if (fwd->forward_host != NULL) */
4525
4526          /*
4527           * We can now create the TLS/SSL connection with the destination server.
4528           */
4529          int ret = create_server_ssl_connection(csp);
4530          if (ret != 0)
4531          {
4532             if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4533                 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4534             {
4535                /*
4536                 * If the server certificate is invalid, we must inform
4537                 * the client and then close connection to the client.
4538                 */
4539                ssl_send_certificate_error(csp);
4540                close_client_and_server_ssl_connections(csp);
4541                return;
4542             }
4543             if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4544              || csp->server_cert_verification_result == SSL_CERT_VALID)
4545             {
4546                /*
4547                 * The TLS/SSL connection wasn't created but an invalid
4548                 * certificate wasn't detected. Report it as connection
4549                 * failure.
4550                 */
4551                rsp = error_response(csp, "connect-failed");
4552                if (rsp)
4553                {
4554                   send_crunch_response(csp, rsp);
4555                }
4556                close_client_and_server_ssl_connections(csp);
4557                return;
4558             }
4559          }
4560       }/* -END- if (http->ssl) */
4561 #endif /* def FEATURE_HTTPS_INSPECTION */
4562
4563 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4564       save_connection_destination(csp->server_connection.sfd,
4565          http, fwd, &csp->server_connection);
4566       csp->server_connection.keep_alive_timeout =
4567          (unsigned)csp->config->keep_alive_timeout;
4568    }
4569 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4570
4571    csp->server_connection.requests_sent_total++;
4572
4573    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4574    {
4575       /* Client headers have been sent optimistically */
4576       assert(csp->headers->last == NULL);
4577    }
4578    else if (http->ssl == 0 || (fwd->forward_host
4579 #ifdef FEATURE_HTTPS_INSPECTION
4580          && use_ssl_tunnel
4581 #endif
4582            ))
4583    {
4584       if (send_http_request(csp))
4585       {
4586          rsp = error_response(csp, "connect-failed");
4587          if (rsp)
4588          {
4589             send_crunch_response(csp, rsp);
4590          }
4591          return;
4592       }
4593    }
4594    else
4595    {
4596       /*
4597        * Using old solution with SSL tunnel or new solution with SSL proxy
4598        */
4599       list_remove_all(csp->headers);
4600 #ifdef FEATURE_HTTPS_INSPECTION
4601       if (use_ssl_tunnel)
4602 #endif
4603       {
4604          /*
4605          * We're running an SSL tunnel and we're not forwarding,
4606          * so just ditch the client headers, send the "connect succeeded"
4607          * message to the client, flush the rest, and get out of the way.
4608          */
4609          if (write_socket_delayed(csp->cfd, CSUCCEED,
4610                strlen(CSUCCEED), get_write_delay(csp)))
4611          {
4612             return;
4613          }
4614       }
4615 #ifdef FEATURE_HTTPS_INSPECTION
4616       else
4617       {
4618          /*
4619           * If server certificate has been verified and is invalid,
4620           * we must inform the client and then close the connection
4621           * with client and server.
4622           */
4623          if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4624              csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4625          {
4626             ssl_send_certificate_error(csp);
4627             close_client_and_server_ssl_connections(csp);
4628             return;
4629          }
4630          if (send_https_request(csp))
4631          {
4632             rsp = error_response(csp, "connect-failed");
4633             if (rsp)
4634             {
4635                send_crunch_response(csp, rsp);
4636             }
4637             close_client_and_server_ssl_connections(csp);
4638             return;
4639          }
4640       }
4641 #endif /* def FEATURE_HTTPS_INSPECTION */
4642       clear_iob(csp->client_iob);
4643    }/* -END- else ... if (http->ssl == 1) */
4644
4645    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4646
4647    /* XXX: should the time start earlier for optimistically sent data? */
4648    csp->server_connection.request_sent = time(NULL);
4649
4650    handle_established_connection(csp);
4651    freez(csp->receive_buffer);
4652 }
4653
4654
4655 #ifdef FUZZ
4656 /*********************************************************************
4657  *
4658  * Function    :  fuzz_server_response
4659  *
4660  * Description :  Treat the input as a whole server response.
4661  *
4662  * Parameters  :
4663  *          1  :  csp = Current client state (buffers, headers, etc...)
4664  *          2  :  fuzz_input_file = File to read the input from.
4665  *
4666  * Returns     :  0
4667  *
4668  *********************************************************************/
4669 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4670 {
4671    static struct forward_spec fwd; /* Zero'd due to being static */
4672    csp->cfd = 0;
4673
4674    if (strcmp(fuzz_input_file, "-") == 0)
4675    {
4676       /* XXX: Doesn't work yet. */
4677       csp->server_connection.sfd = 0;
4678    }
4679    else
4680    {
4681       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4682       if (csp->server_connection.sfd == -1)
4683       {
4684          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4685             fuzz_input_file);
4686       }
4687    }
4688    csp->fwd = &fwd;
4689    csp->content_type |= CT_GIF;
4690    csp->action->flags |= ACTION_DEANIMATE;
4691    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4692
4693    csp->http->path = strdup_or_die("/");
4694    csp->http->host = strdup_or_die("fuzz.example.org");
4695    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4696    /* Prevent client socket monitoring */
4697    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4698    csp->flags |= CSP_FLAG_CHUNKED;
4699
4700    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4701    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4702
4703    csp->content_type |= CT_DECLARED|CT_GIF;
4704
4705    csp->config->socket_timeout = 0;
4706
4707    cgi_init_error_messages();
4708
4709    handle_established_connection(csp);
4710    freez(csp->receive_buffer);
4711
4712    return 0;
4713 }
4714 #endif
4715
4716
4717 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4718 /*********************************************************************
4719  *
4720  * Function    :  prepare_csp_for_next_request
4721  *
4722  * Description :  Put the csp in a mostly vergin state.
4723  *
4724  * Parameters  :
4725  *          1  :  csp = Current client state (buffers, headers, etc...)
4726  *
4727  * Returns     :  N/A
4728  *
4729  *********************************************************************/
4730 static void prepare_csp_for_next_request(struct client_state *csp)
4731 {
4732    csp->content_type = 0;
4733    csp->content_length = 0;
4734    csp->expected_content_length = 0;
4735    csp->expected_client_content_length = 0;
4736    list_remove_all(csp->headers);
4737    clear_iob(csp->iob);
4738    freez(csp->error_message);
4739    free_http_request(csp->http);
4740    destroy_list(csp->headers);
4741 #ifdef FEATURE_HTTPS_INSPECTION
4742    destroy_list(csp->https_headers);
4743 #endif
4744    destroy_list(csp->tags);
4745 #ifdef FEATURE_CLIENT_TAGS
4746    destroy_list(csp->client_tags);
4747    freez(csp->client_address);
4748 #endif
4749    free_current_action(csp->action);
4750    if (NULL != csp->fwd)
4751    {
4752       unload_forward_spec(csp->fwd);
4753       csp->fwd = NULL;
4754    }
4755    /* XXX: Store per-connection flags someplace else. */
4756    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4757 #ifdef FEATURE_TOGGLE
4758    if (global_toggle_state)
4759 #endif /* def FEATURE_TOGGLE */
4760    {
4761       csp->flags |= CSP_FLAG_TOGGLED_ON;
4762    }
4763
4764    if (csp->client_iob->eod > csp->client_iob->cur)
4765    {
4766       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4767       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4768
4769       assert(bytes_to_shift > 0);
4770       assert(data_length > 0);
4771
4772       log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4773          data_length, bytes_to_shift);
4774       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4775       csp->client_iob->cur = csp->client_iob->buf;
4776       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4777       csp->client_iob->eod = csp->client_iob->buf + data_length;
4778       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4779
4780       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4781    }
4782    else
4783    {
4784       /*
4785        * We mainly care about resetting client_iob->cur so we don't
4786        * waste buffer space at the beginning and don't mess up the
4787        * request restoration done by cgi_show_request().
4788        *
4789        * Freeing the buffer itself isn't technically necessary,
4790        * but makes debugging more convenient.
4791        */
4792       clear_iob(csp->client_iob);
4793    }
4794 }
4795 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4796
4797
4798 /*********************************************************************
4799  *
4800  * Function    :  serve
4801  *
4802  * Description :  This is little more than chat.  We only "serve" to
4803  *                to close (or remember) any socket that chat may have
4804  *                opened.
4805  *
4806  * Parameters  :
4807  *          1  :  csp = Current client state (buffers, headers, etc...)
4808  *
4809  * Returns     :  N/A
4810  *
4811  *********************************************************************/
4812 static void serve(struct client_state *csp)
4813 {
4814    int config_file_change_detected = 0; /* Only used for debugging */
4815 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4816 #ifdef FEATURE_CONNECTION_SHARING
4817    static int monitor_thread_running = 0;
4818 #endif /* def FEATURE_CONNECTION_SHARING */
4819    int continue_chatting = 0;
4820
4821    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4822       csp->ip_addr_str, csp->cfd);
4823
4824    do
4825    {
4826       unsigned int latency;
4827
4828 #ifdef FEATURE_HTTPS_INSPECTION
4829       if (continue_chatting && client_use_ssl(csp))
4830       {
4831          continue_https_chat(csp);
4832       }
4833       else
4834 #endif
4835       {
4836          chat(csp);
4837       }
4838
4839       /*
4840        * If the request has been crunched,
4841        * the calculated latency is zero.
4842        */
4843       latency = (unsigned)(csp->server_connection.response_received -
4844          csp->server_connection.request_sent) / 2;
4845
4846       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4847          && (csp->flags & CSP_FLAG_CRUNCHED)
4848          && (csp->expected_client_content_length != 0))
4849       {
4850          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4851          log_error(LOG_LEVEL_CONNECT,
4852             "Tainting client socket %d due to unread data.", csp->cfd);
4853       }
4854
4855       continue_chatting = (csp->config->feature_flags
4856          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4857          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4858          && (csp->cfd != JB_INVALID_SOCKET)
4859          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4860          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4861             || (csp->flags & CSP_FLAG_CHUNKED));
4862
4863       if (!(csp->flags & CSP_FLAG_CRUNCHED)
4864          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4865       {
4866          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4867          {
4868             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4869          }
4870          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4871             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4872             || !socket_is_still_alive(csp->server_connection.sfd)
4873             || !(latency < csp->server_connection.keep_alive_timeout))
4874          {
4875             log_error(LOG_LEVEL_CONNECT,
4876                "Closing server socket %d connected to %s. "
4877                "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4878                csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4879                csp->server_connection.host : csp->http->host,
4880                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4881                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4882                socket_is_still_alive(csp->server_connection.sfd),
4883                csp->server_connection.keep_alive_timeout);
4884 #ifdef FEATURE_CONNECTION_SHARING
4885             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4886             {
4887                forget_connection(csp->server_connection.sfd);
4888             }
4889 #endif /* def FEATURE_CONNECTION_SHARING */
4890 #ifdef FEATURE_HTTPS_INSPECTION
4891             close_server_ssl_connection(csp);
4892 #endif
4893             close_socket(csp->server_connection.sfd);
4894             mark_connection_closed(&csp->server_connection);
4895 #ifdef FEATURE_HTTPS_INSPECTION
4896             if (continue_chatting && client_use_ssl(csp))
4897             {
4898                /*
4899                 * Close the client socket as well as Privoxy currently
4900                 * can't establish a new server connection when the client
4901                 * socket is reused and would drop the connection in
4902                 * continue_https_chat() anyway.
4903                 */
4904                continue_chatting = 0;
4905                csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4906                log_error(LOG_LEVEL_CONNECT,
4907                   "Client socket %d is no longer usable. "
4908                   "The server socket has been closed.", csp->cfd);
4909             }
4910 #endif
4911          }
4912       }
4913
4914       if (continue_chatting && any_loaded_file_changed(csp))
4915       {
4916          continue_chatting = 0;
4917          config_file_change_detected = 1;
4918       }
4919 #ifdef FEATURE_HTTPS_INSPECTION
4920       if (continue_chatting && client_use_ssl(csp) &&
4921          csp->ssl_with_client_is_opened == 0)
4922       {
4923          continue_chatting = 0;
4924          log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4925             "The TLS session has been terminated.", csp->cfd);
4926       }
4927 #endif
4928
4929       if (continue_chatting)
4930       {
4931          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4932             && socket_is_still_alive(csp->cfd))
4933          {
4934             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4935                "pipelined on socket %d and the socket is still alive.",
4936                csp->requests_received_total+1, csp->cfd);
4937             prepare_csp_for_next_request(csp);
4938             continue;
4939          }
4940
4941          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4942          {
4943             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4944             {
4945                log_error(LOG_LEVEL_CONNECT,
4946                   "Waiting for the next client request on socket %d. "
4947                   "Keeping the server socket %d to %s open.",
4948                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4949             }
4950             else
4951             {
4952                log_error(LOG_LEVEL_CONNECT,
4953                   "Waiting for the next client request on socket %d. "
4954                   "No server socket to keep open.", csp->cfd);
4955             }
4956          }
4957
4958          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4959             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4960             && socket_is_still_alive(csp->cfd))
4961          {
4962             log_error(LOG_LEVEL_CONNECT,
4963                "Data arrived in time on client socket %d. Requests so far: %u",
4964                csp->cfd, csp->requests_received_total);
4965             prepare_csp_for_next_request(csp);
4966          }
4967          else
4968          {
4969 #ifdef FEATURE_CONNECTION_SHARING
4970             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4971                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4972                && (socket_is_still_alive(csp->server_connection.sfd))
4973 #ifdef FEATURE_HTTPS_INSPECTION
4974                && !server_use_ssl(csp)
4975 #endif
4976                 )
4977             {
4978                time_t time_open = time(NULL) - csp->server_connection.timestamp;
4979
4980                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4981                {
4982                   break;
4983                }
4984
4985                remember_connection(&csp->server_connection);
4986                csp->server_connection.sfd = JB_INVALID_SOCKET;
4987                drain_and_close_socket(csp->cfd);
4988                csp->cfd = JB_INVALID_SOCKET;
4989                privoxy_mutex_lock(&connection_reuse_mutex);
4990                if (!monitor_thread_running)
4991                {
4992                   monitor_thread_running = 1;
4993                   privoxy_mutex_unlock(&connection_reuse_mutex);
4994                   wait_for_alive_connections();
4995                   privoxy_mutex_lock(&connection_reuse_mutex);
4996                   monitor_thread_running = 0;
4997                }
4998                privoxy_mutex_unlock(&connection_reuse_mutex);
4999             }
5000 #endif /* def FEATURE_CONNECTION_SHARING */
5001             break;
5002          }
5003       }
5004       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5005       {
5006          log_error(LOG_LEVEL_CONNECT,
5007             "Closing server socket %d connected to %s. Keep-alive: %u. "
5008             "Tainted: %u. Socket alive: %u. Timeout: %u. "
5009             "Configuration file change detected: %u",
5010             csp->server_connection.sfd, csp->server_connection.host,
5011             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5012             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5013             socket_is_still_alive(csp->server_connection.sfd),
5014             csp->server_connection.keep_alive_timeout,
5015             config_file_change_detected);
5016       }
5017    } while (continue_chatting);
5018
5019 #else
5020    chat(csp);
5021 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5022
5023    if (csp->cfd != JB_INVALID_SOCKET)
5024    {
5025       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5026          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5027          "Configuration file change detected: %u. Requests received: %u.",
5028          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5029          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5030          config_file_change_detected, csp->requests_received_total);
5031 #ifdef FEATURE_HTTPS_INSPECTION
5032       close_client_ssl_connection(csp);
5033 #endif
5034       drain_and_close_socket(csp->cfd);
5035    }
5036
5037    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5038    {
5039 #ifdef FEATURE_CONNECTION_SHARING
5040       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5041       {
5042          forget_connection(csp->server_connection.sfd);
5043       }
5044 #endif /* def FEATURE_CONNECTION_SHARING */
5045
5046 #ifdef FEATURE_HTTPS_INSPECTION
5047       close_server_ssl_connection(csp);
5048 #endif /* def FEATURE_HTTPS_INSPECTION */
5049
5050       close_socket(csp->server_connection.sfd);
5051    }
5052
5053 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5054    mark_connection_closed(&csp->server_connection);
5055 #endif
5056
5057    free_csp_resources(csp);
5058
5059    csp->flags &= ~CSP_FLAG_ACTIVE;
5060
5061 }
5062
5063
5064 #ifdef __BEOS__
5065 /*********************************************************************
5066  *
5067  * Function    :  server_thread
5068  *
5069  * Description :  We only exist to call `serve' in a threaded environment.
5070  *
5071  * Parameters  :
5072  *          1  :  data = Current client state (buffers, headers, etc...)
5073  *
5074  * Returns     :  Always 0.
5075  *
5076  *********************************************************************/
5077 static int32 server_thread(void *data)
5078 {
5079    serve((struct client_state *) data);
5080    return 0;
5081
5082 }
5083 #endif
5084
5085
5086 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5087 /*********************************************************************
5088  *
5089  * Function    :  usage
5090  *
5091  * Description :  Print usage info & exit.
5092  *
5093  * Parameters  :  Pointer to argv[0] for identifying ourselves
5094  *
5095  * Returns     :  No. ,-)
5096  *
5097  *********************************************************************/
5098 static void usage(const char *name)
5099 {
5100    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5101           "Usage: %s [--config-test] "
5102 #if defined(unix)
5103           "[--chroot] "
5104 #endif /* defined(unix) */
5105           "[--help] "
5106 #if defined(unix)
5107           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5108 #endif /* defined(unix) */
5109          "[--version] [configfile]\n",
5110           name);
5111
5112 #ifdef FUZZ
5113    show_fuzz_usage(name);
5114 #endif
5115
5116    printf("Aborting\n");
5117
5118    exit(2);
5119
5120 }
5121 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5122
5123
5124 #ifdef MUTEX_LOCKS_AVAILABLE
5125 /*********************************************************************
5126  *
5127  * Function    :  privoxy_mutex_lock
5128  *
5129  * Description :  Locks a mutex.
5130  *
5131  * Parameters  :
5132  *          1  :  mutex = The mutex to lock.
5133  *
5134  * Returns     :  Void. May exit in case of errors.
5135  *
5136  *********************************************************************/
5137 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5138 {
5139 #ifdef FEATURE_PTHREAD
5140    int err = pthread_mutex_lock(mutex);
5141    if (err)
5142    {
5143       if (mutex != &log_mutex)
5144       {
5145          log_error(LOG_LEVEL_FATAL,
5146             "Mutex locking failed: %s.\n", strerror(err));
5147       }
5148       exit(1);
5149    }
5150 #else
5151    EnterCriticalSection(mutex);
5152 #endif /* def FEATURE_PTHREAD */
5153 }
5154
5155
5156 /*********************************************************************
5157  *
5158  * Function    :  privoxy_mutex_unlock
5159  *
5160  * Description :  Unlocks a mutex.
5161  *
5162  * Parameters  :
5163  *          1  :  mutex = The mutex to unlock.
5164  *
5165  * Returns     :  Void. May exit in case of errors.
5166  *
5167  *********************************************************************/
5168 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5169 {
5170 #ifdef FEATURE_PTHREAD
5171    int err = pthread_mutex_unlock(mutex);
5172    if (err)
5173    {
5174       if (mutex != &log_mutex)
5175       {
5176          log_error(LOG_LEVEL_FATAL,
5177             "Mutex unlocking failed: %s.\n", strerror(err));
5178       }
5179       exit(1);
5180    }
5181 #else
5182    LeaveCriticalSection(mutex);
5183 #endif /* def FEATURE_PTHREAD */
5184 }
5185
5186
5187 /*********************************************************************
5188  *
5189  * Function    :  privoxy_mutex_init
5190  *
5191  * Description :  Prepares a mutex.
5192  *
5193  * Parameters  :
5194  *          1  :  mutex = The mutex to initialize.
5195  *
5196  * Returns     :  Void. May exit in case of errors.
5197  *
5198  *********************************************************************/
5199 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5200 {
5201 #ifdef FEATURE_PTHREAD
5202    int err = pthread_mutex_init(mutex, 0);
5203    if (err)
5204    {
5205       printf("Fatal error. Mutex initialization failed: %s.\n",
5206          strerror(err));
5207       exit(1);
5208    }
5209 #else
5210    InitializeCriticalSection(mutex);
5211 #endif /* def FEATURE_PTHREAD */
5212 }
5213 #endif /* def MUTEX_LOCKS_AVAILABLE */
5214
5215 /*********************************************************************
5216  *
5217  * Function    :  initialize_mutexes
5218  *
5219  * Description :  Prepares mutexes if mutex support is available.
5220  *
5221  * Parameters  :  None
5222  *
5223  * Returns     :  Void, exits in case of errors.
5224  *
5225  *********************************************************************/
5226 static void initialize_mutexes(void)
5227 {
5228 #ifdef MUTEX_LOCKS_AVAILABLE
5229    /*
5230     * Prepare global mutex semaphores
5231     */
5232
5233 #ifdef FEATURE_HTTPS_INSPECTION
5234    privoxy_mutex_init(&certificate_mutex);
5235    privoxy_mutex_init(&ssl_init_mutex);
5236 #endif
5237
5238    privoxy_mutex_init(&log_mutex);
5239    privoxy_mutex_init(&log_init_mutex);
5240    privoxy_mutex_init(&connection_reuse_mutex);
5241 #ifdef FEATURE_EXTERNAL_FILTERS
5242    privoxy_mutex_init(&external_filter_mutex);
5243 #endif
5244 #ifdef FEATURE_CLIENT_TAGS
5245    privoxy_mutex_init(&client_tags_mutex);
5246 #endif
5247 #ifdef FEATURE_EXTENDED_STATISTICS
5248    privoxy_mutex_init(&filter_statistics_mutex);
5249    privoxy_mutex_init(&block_statistics_mutex);
5250 #endif
5251
5252    /*
5253     * XXX: The assumptions below are a bit naive
5254     * and can cause locks that aren't necessary.
5255     *
5256     * For example older FreeBSD versions (< 6.x?)
5257     * have no gethostbyname_r, but gethostbyname is
5258     * thread safe.
5259     */
5260 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5261    privoxy_mutex_init(&resolver_mutex);
5262 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5263    /*
5264     * XXX: should we use a single mutex for
5265     * localtime() and gmtime() as well?
5266     */
5267 #ifndef HAVE_GMTIME_R
5268    privoxy_mutex_init(&gmtime_mutex);
5269 #endif /* ndef HAVE_GMTIME_R */
5270
5271 #ifndef HAVE_LOCALTIME_R
5272    privoxy_mutex_init(&localtime_mutex);
5273 #endif /* ndef HAVE_GMTIME_R */
5274
5275 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5276    privoxy_mutex_init(&rand_mutex);
5277 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5278
5279 #endif /* def MUTEX_LOCKS_AVAILABLE */
5280 }
5281
5282 /*********************************************************************
5283  *
5284  * Function    :  main
5285  *
5286  * Description :  Load the config file and start the listen loop.
5287  *                This function is a lot more *sane* with the `load_config'
5288  *                and `listen_loop' functions; although it stills does
5289  *                a *little* too much for my taste.
5290  *
5291  * Parameters  :
5292  *          1  :  argc = Number of parameters (including $0).
5293  *          2  :  argv = Array of (char *)'s to the parameters.
5294  *
5295  * Returns     :  1 if : can't open config file, unrecognized directive,
5296  *                stats requested in multi-thread mode, can't open the
5297  *                log file, can't open the jar file, listen port is invalid,
5298  *                any load fails, and can't bind port.
5299  *
5300  *                Else main never returns, the process must be signaled
5301  *                to terminate execution.  Or, on Windows, use the
5302  *                "File", "Exit" menu option.
5303  *
5304  *********************************************************************/
5305 #ifdef __MINGW32__
5306 int real_main(int argc, char **argv)
5307 #else
5308 int main(int argc, char **argv)
5309 #endif
5310 {
5311    int argc_pos = 0;
5312    int do_config_test = 0;
5313 #ifndef HAVE_ARC4RANDOM
5314    unsigned int random_seed;
5315 #endif
5316 #ifdef unix
5317    struct passwd *pw = NULL;
5318    struct group *grp = NULL;
5319    int do_chroot = 0;
5320    char *pre_chroot_nslookup_to_load_resolver = NULL;
5321 #endif
5322 #ifdef FUZZ
5323    char *fuzz_input_type = NULL;
5324    char *fuzz_input_file = NULL;
5325 #endif
5326
5327    Argc = argc;
5328    Argv = argv;
5329
5330    configfile =
5331 #if !defined(_WIN32)
5332    "config"
5333 #else
5334    "config.txt"
5335 #endif
5336       ;
5337
5338    /* Prepare mutexes if supported and necessary. */
5339    initialize_mutexes();
5340
5341    /* Enable logging until further notice. */
5342    init_log_module();
5343
5344    /*
5345     * Parse the command line arguments
5346     *
5347     * XXX: simply printing usage information in case of
5348     * invalid arguments isn't particularly user friendly.
5349     */
5350    while (++argc_pos < argc)
5351    {
5352 #ifdef _WIN32
5353       /* Check to see if the service must be installed or uninstalled */
5354       if (strncmp(argv[argc_pos], "--install", 9) == 0)
5355       {
5356          const char *pName = argv[argc_pos] + 9;
5357          if (*pName == ':')
5358             pName++;
5359          exit((install_service(pName)) ? 0 : 1);
5360       }
5361       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5362       {
5363          const char *pName = argv[argc_pos] + 11;
5364          if (*pName == ':')
5365             pName++;
5366          exit((uninstall_service(pName)) ? 0 : 1);
5367       }
5368       else if (strcmp(argv[argc_pos], "--service") == 0)
5369       {
5370          bRunAsService = TRUE;
5371          w32_set_service_cwd();
5372          atexit(w32_service_exit_notify);
5373       }
5374       else
5375 #endif /* defined(_WIN32) */
5376
5377
5378 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5379
5380       if (strcmp(argv[argc_pos], "--help") == 0)
5381       {
5382          usage(argv[0]);
5383       }
5384
5385       else if (strcmp(argv[argc_pos], "--version") == 0)
5386       {
5387          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5388          exit(0);
5389       }
5390
5391 #if defined(unix)
5392
5393       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5394       {
5395          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5396          daemon_mode = 0;
5397       }
5398
5399       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5400       {
5401          if (++argc_pos == argc) usage(argv[0]);
5402          pidfile = strdup_or_die(argv[argc_pos]);
5403       }
5404
5405       else if (strcmp(argv[argc_pos], "--user") == 0)
5406       {
5407          char *user_arg;
5408          char *group_name;
5409
5410          if (++argc_pos == argc) usage(argv[argc_pos]);
5411
5412          user_arg = strdup_or_die(argv[argc_pos]);
5413          group_name = strchr(user_arg, '.');
5414          if (NULL != group_name)
5415          {
5416             /* Nul-terminate the user name */
5417             *group_name = '\0';
5418
5419             /* Skip the former delimiter to actually reach the group name */
5420             group_name++;
5421
5422             grp = getgrnam(group_name);
5423             if (NULL == grp)
5424             {
5425                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5426             }
5427          }
5428          pw = getpwnam(user_arg);
5429          if (NULL == pw)
5430          {
5431             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5432          }
5433
5434          freez(user_arg);
5435       }
5436
5437       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5438       {
5439          if (++argc_pos == argc) usage(argv[0]);
5440          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5441       }
5442
5443       else if (strcmp(argv[argc_pos], "--chroot") == 0)
5444       {
5445          do_chroot = 1;
5446       }
5447 #endif /* defined(unix) */
5448
5449       else if (strcmp(argv[argc_pos], "--config-test") == 0)
5450       {
5451          do_config_test = 1;
5452       }
5453 #ifdef FUZZ
5454       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5455       {
5456          argc_pos++;
5457          if (argc < argc_pos + 2) usage(argv[0]);
5458          fuzz_input_type = argv[argc_pos];
5459          argc_pos++;
5460          fuzz_input_file = argv[argc_pos];
5461       }
5462       else if (strcmp(argv[argc_pos], "--stfu") == 0)
5463       {
5464          set_debug_level(LOG_LEVEL_STFU);
5465       }
5466 #endif
5467       else if (argc_pos + 1 != argc)
5468       {
5469          /*
5470           * This is neither the last command line
5471           * option, nor was it recognized before,
5472           * therefore it must be invalid.
5473           */
5474          usage(argv[0]);
5475       }
5476       else
5477
5478 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5479       {
5480          configfile = argv[argc_pos];
5481       }
5482
5483    } /* -END- while (more arguments) */
5484
5485    show_version(Argv[0]);
5486
5487 #if defined(unix)
5488    if (*configfile != '/')
5489    {
5490       char cwd[BUFFER_SIZE];
5491       char *abs_file;
5492       size_t abs_file_size;
5493
5494       /* make config-filename absolute here */
5495       if (NULL == getcwd(cwd, sizeof(cwd)))
5496       {
5497          perror("failed to get current working directory");
5498          exit(1);
5499       }
5500
5501       basedir = strdup_or_die(cwd);
5502       /* XXX: why + 5? */
5503       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5504       abs_file = malloc_or_die(abs_file_size);
5505       strlcpy(abs_file, basedir, abs_file_size);
5506       strlcat(abs_file, "/", abs_file_size);
5507       strlcat(abs_file, configfile, abs_file_size);
5508       configfile = abs_file;
5509    }
5510 #endif /* defined unix */
5511
5512
5513    files->next = NULL;
5514    clients->next = NULL;
5515
5516    /* XXX: factor out initialising after the next stable release. */
5517 #ifdef _WIN32
5518    InitWin32();
5519 #endif
5520
5521 #ifndef HAVE_ARC4RANDOM
5522    random_seed = (unsigned int)time(NULL);
5523 #ifdef HAVE_RANDOM
5524    srandom(random_seed);
5525 #else
5526    srand(random_seed);
5527 #endif /* ifdef HAVE_RANDOM */
5528 #endif /* ifndef HAVE_ARC4RANDOM */
5529
5530    /*
5531     * Unix signal handling
5532     *
5533     * Catch the abort, interrupt and terminate signals for a graceful exit
5534     * Catch the hangup signal so the errlog can be reopened.
5535     *
5536     * Ignore the broken pipe signal as connection failures
5537     * are handled when and where they occur without relying
5538     * on a signal.
5539     */
5540 #if !defined(_WIN32)
5541 {
5542    int idx;
5543    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5544
5545    for (idx = 0; idx < SZ(catched_signals); idx++)
5546    {
5547 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5548       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5549 #else
5550       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5551 #endif /* ifdef sun */
5552       {
5553          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5554       }
5555    }
5556
5557    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5558    {
5559       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5560    }
5561
5562 }
5563 #else /* ifdef _WIN32 */
5564 # ifdef _WIN_CONSOLE
5565    /*
5566     * We *are* in a windows console app.
5567     * Print a verbose messages about FAQ's and such
5568     */
5569    printf("%s", win32_blurb);
5570 # endif /* def _WIN_CONSOLE */
5571 #endif /* def _WIN32 */
5572
5573 #ifdef FUZZ
5574    if (fuzz_input_type != NULL)
5575    {
5576       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5577    }
5578    log_error(LOG_LEVEL_FATAL,
5579       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5580       "Various data structures are static which is unsafe when using threads.");
5581 #endif
5582
5583    if (do_config_test)
5584    {
5585       exit(NULL == load_config());
5586    }
5587
5588    /* Initialize the CGI subsystem */
5589    cgi_init_error_messages();
5590
5591    /*
5592     * If running on unix and without the --no-daemon
5593     * option, become a daemon. I.e. fork, detach
5594     * from tty and get process group leadership
5595     */
5596 #if defined(unix)
5597 {
5598    if (daemon_mode)
5599    {
5600       int fd;
5601       pid_t pid = fork();
5602
5603       if (pid < 0) /* error */
5604       {
5605          perror("fork");
5606          exit(3);
5607       }
5608       else if (pid != 0) /* parent */
5609       {
5610          int status;
5611          pid_t wpid;
5612          /*
5613           * must check for errors
5614           * child died due to missing files aso
5615           */
5616          sleep(1);
5617          wpid = waitpid(pid, &status, WNOHANG);
5618          if (wpid != 0)
5619          {
5620             exit(1);
5621          }
5622          exit(0);
5623       }
5624       /* child */
5625
5626       setsid();
5627
5628       /*
5629        * stderr (fd 2) will be closed later on,
5630        * when the config file has been parsed.
5631        */
5632       close(0);
5633       close(1);
5634
5635       /*
5636        * Reserve fd 0 and 1 to prevent abort() and friends
5637        * from sending stuff to the clients or servers.
5638        */
5639       fd = open("/dev/null", O_RDONLY);
5640       if (fd == -1)
5641       {
5642          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5643       }
5644       else if (fd != 0)
5645       {
5646          if (dup2(fd, 0) == -1)
5647          {
5648             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5649          }
5650          close(fd);
5651       }
5652       fd = open("/dev/null", O_WRONLY);
5653       if (fd == -1)
5654       {
5655          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5656       }
5657       else if (fd != 1)
5658       {
5659          if (dup2(fd, 1) == -1)
5660          {
5661             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5662          }
5663          close(fd);
5664       }
5665
5666 #ifdef FEATURE_EXTERNAL_FILTERS
5667       for (fd = 0; fd < 3; fd++)
5668       {
5669          mark_socket_for_close_on_execute(fd);
5670       }
5671 #endif
5672
5673       if (chdir("/") != 0)
5674       {
5675          log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5676       }
5677
5678    } /* -END- if (daemon_mode) */
5679
5680    /*
5681     * As soon as we have written the PID file, we can switch
5682     * to the user and group ID indicated by the --user option
5683     */
5684    if (pidfile != NULL)
5685    {
5686       write_pid_file(pidfile);
5687    }
5688    if (NULL != pw)
5689    {
5690       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5691       {
5692          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5693       }
5694       if (NULL != grp)
5695       {
5696          if (setgroups(1, &grp->gr_gid))
5697          {
5698             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5699          }
5700       }
5701       else if (initgroups(pw->pw_name, pw->pw_gid))
5702       {
5703          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5704       }
5705       if (do_chroot)
5706       {
5707          if (!pw->pw_dir)
5708          {
5709             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5710          }
5711          /* Read the time zone file from /etc before doing chroot. */
5712          tzset();
5713          if (NULL != pre_chroot_nslookup_to_load_resolver
5714              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5715          {
5716             /* Initialize resolver library. */
5717             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5718          }
5719          if (chroot(pw->pw_dir) < 0)
5720          {
5721             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5722          }
5723          if (chdir ("/"))
5724          {
5725             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5726          }
5727       }
5728       if (setuid(pw->pw_uid))
5729       {
5730          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5731       }
5732       if (do_chroot)
5733       {
5734          char putenv_dummy[64];
5735
5736          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5737          if (putenv(putenv_dummy) != 0)
5738          {
5739             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5740          }
5741
5742          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5743          if (putenv(putenv_dummy) != 0)
5744          {
5745             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5746          }
5747       }
5748    }
5749    else if (do_chroot)
5750    {
5751       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5752    }
5753 }
5754 #endif /* defined unix */
5755
5756 #ifdef _WIN32
5757    /* This will be FALSE unless the command line specified --service
5758     */
5759    if (bRunAsService)
5760    {
5761       /* Yup, so now we must attempt to establish a connection
5762        * with the service dispatcher. This will only work if this
5763        * process was launched by the service control manager to
5764        * actually run as a service. If this isn't the case, i've
5765        * known it take around 30 seconds or so for the call to return.
5766        */
5767
5768       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5769       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5770       {
5771          /* Service has run, and at this point is now being stopped, so just return */
5772          return 0;
5773       }
5774
5775 #ifdef _WIN_CONSOLE
5776       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5777 #endif
5778       /* An error occurred. Usually it's because --service was wrongly specified
5779        * and we were unable to connect to the Service Control Dispatcher because
5780        * it wasn't expecting us and is therefore not listening.
5781        *
5782        * For now, just continue below to call the listen_loop function.
5783        */
5784    }
5785 #endif /* def _WIN32 */
5786
5787    listen_loop();
5788
5789    /* NOTREACHED */
5790    return(-1);
5791
5792 }
5793
5794
5795 /*********************************************************************
5796  *
5797  * Function    :  bind_port_helper
5798  *
5799  * Description :  Bind the listen port.  Handles logging, and aborts
5800  *                on failure.
5801  *
5802  * Parameters  :
5803  *          1  :  haddr = Host address to bind to. Use NULL to bind to
5804  *                        INADDR_ANY.
5805  *          2  :  hport = Specifies port to bind to.
5806  *          3  :  backlog = Listen backlog.
5807  *
5808  * Returns     :  Port that was opened.
5809  *
5810  *********************************************************************/
5811 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5812 {
5813    int result;
5814    jb_socket bfd;
5815
5816    result = bind_port(haddr, hport, backlog, &bfd);
5817
5818    if (result < 0)
5819    {
5820       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5821       switch(result)
5822       {
5823          case -3:
5824             log_error(LOG_LEVEL_FATAL,
5825                "can't bind to %s:%d: There may be another Privoxy "
5826                "or some other proxy running on port %d",
5827                bind_address, hport, hport);
5828             exit(-1);
5829
5830          case -2:
5831             log_error(LOG_LEVEL_FATAL,
5832                "can't bind to %s:%d: The hostname is not resolvable",
5833                bind_address, hport);
5834             exit(-1);
5835
5836          default:
5837             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5838                bind_address, hport);
5839             exit(-1);
5840       }
5841
5842       /* shouldn't get here */
5843       return JB_INVALID_SOCKET;
5844    }
5845
5846 #ifndef HAVE_POLL
5847 #ifndef _WIN32
5848    if (bfd >= FD_SETSIZE)
5849    {
5850       log_error(LOG_LEVEL_FATAL,
5851          "Bind socket number too high to use select(): %d >= %d",
5852          bfd, FD_SETSIZE);
5853    }
5854 #endif
5855 #endif
5856
5857    if (haddr == NULL)
5858    {
5859       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5860          hport);
5861    }
5862    else
5863    {
5864       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5865          hport, haddr);
5866    }
5867
5868    return bfd;
5869 }
5870
5871
5872 /*********************************************************************
5873  *
5874  * Function    :  bind_ports_helper
5875  *
5876  * Description :  Bind the listen ports.  Handles logging, and aborts
5877  *                on failure.
5878  *
5879  * Parameters  :
5880  *          1  :  config = Privoxy configuration.  Specifies ports
5881  *                         to bind to.
5882  *          2  :  sockets = Preallocated array of opened sockets
5883  *                          corresponding to specification in config.
5884  *                          All non-opened sockets will be set to
5885  *                          JB_INVALID_SOCKET.
5886  *
5887  * Returns     :  Nothing. Inspect sockets argument.
5888  *
5889  *********************************************************************/
5890 static void bind_ports_helper(struct configuration_spec * config,
5891                               jb_socket sockets[])
5892 {
5893    int i;
5894
5895    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5896    {
5897       if (config->hport[i])
5898       {
5899          sockets[i] = bind_port_helper(config->haddr[i],
5900             config->hport[i], config->listen_backlog);
5901 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5902          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5903          {
5904             struct accept_filter_arg af_options;
5905             bzero(&af_options, sizeof(af_options));
5906             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5907             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5908                   sizeof(af_options)))
5909             {
5910                log_error(LOG_LEVEL_ERROR,
5911                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
5912             }
5913          }
5914 #endif
5915       }
5916       else
5917       {
5918          sockets[i] = JB_INVALID_SOCKET;
5919       }
5920    }
5921    config->need_bind = 0;
5922 }
5923
5924
5925 /*********************************************************************
5926  *
5927  * Function    :  close_ports_helper
5928  *
5929  * Description :  Close listenings ports.
5930  *
5931  * Parameters  :
5932  *          1  :  sockets = Array of opened and non-opened sockets to
5933  *                          close. All sockets will be set to
5934  *                          JB_INVALID_SOCKET.
5935  *
5936  * Returns     :  Nothing.
5937  *
5938  *********************************************************************/
5939 static void close_ports_helper(jb_socket sockets[])
5940 {
5941    int i;
5942
5943    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5944    {
5945       if (JB_INVALID_SOCKET != sockets[i])
5946       {
5947          close_socket(sockets[i]);
5948       }
5949       sockets[i] = JB_INVALID_SOCKET;
5950    }
5951 }
5952
5953
5954 #ifdef _WIN32
5955 /* Without this simple workaround we get this compiler warning from _beginthread
5956  *     warning C4028: formal parameter 1 different from declaration
5957  */
5958 void w32_service_listen_loop(void *p)
5959 {
5960    listen_loop();
5961 }
5962 #endif /* def _WIN32 */
5963
5964
5965 /*********************************************************************
5966  *
5967  * Function    :  listen_loop
5968  *
5969  * Description :  bind the listen port and enter a "FOREVER" listening loop.
5970  *
5971  * Parameters  :  N/A
5972  *
5973  * Returns     :  Never.
5974  *
5975  *********************************************************************/
5976 static void listen_loop(void)
5977 {
5978    struct client_states *csp_list = NULL;
5979    struct client_state *csp = NULL;
5980    jb_socket bfds[MAX_LISTENING_SOCKETS];
5981    struct configuration_spec *config;
5982    unsigned int active_threads = 0;
5983 #if defined(FEATURE_PTHREAD)
5984    pthread_attr_t attrs;
5985
5986    pthread_attr_init(&attrs);
5987    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5988 #endif
5989
5990    config = load_config();
5991
5992 #ifdef FEATURE_CONNECTION_SHARING
5993    /*
5994     * XXX: Should be relocated once it no
5995     * longer needs to emit log messages.
5996     */
5997    initialize_reusable_connections();
5998 #endif /* def FEATURE_CONNECTION_SHARING */
5999
6000    bind_ports_helper(config, bfds);
6001
6002 #ifdef FEATURE_GRACEFUL_TERMINATION
6003    while (!g_terminate)
6004 #else
6005    for (;;)
6006 #endif
6007    {
6008 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6009       while (waitpid(-1, NULL, WNOHANG) > 0)
6010       {
6011          /* zombie children */
6012       }
6013 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6014
6015       /*
6016        * Free data that was used by died threads
6017        */
6018       active_threads = sweep();
6019
6020 #if defined(unix)
6021       /*
6022        * Re-open the errlog after HUP signal
6023        */
6024       if (received_hup_signal)
6025       {
6026          if (NULL != config->logfile)
6027          {
6028             init_error_log(Argv[0], config->logfile);
6029          }
6030          received_hup_signal = 0;
6031       }
6032 #endif
6033
6034       csp_list = zalloc_or_die(sizeof(*csp_list));
6035       csp = &csp_list->csp;
6036
6037       log_error(LOG_LEVEL_CONNECT,
6038          "Waiting for the next client connection. Currently active threads: %u",
6039          active_threads);
6040
6041       /*
6042        * This config may be outdated, but for accept_connection()
6043        * it's fresh enough.
6044        */
6045       csp->config = config;
6046
6047       if (!accept_connection(csp, bfds))
6048       {
6049          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6050          freez(csp_list);
6051          continue;
6052       }
6053
6054       csp->flags |= CSP_FLAG_ACTIVE;
6055       csp->server_connection.sfd = JB_INVALID_SOCKET;
6056
6057       csp->config = config = load_config();
6058
6059       if (config->need_bind)
6060       {
6061          /*
6062           * Since we were listening to the "old port", we will not see
6063           * a "listen" param change until the next request.  So, at
6064           * least 1 more request must be made for us to find the new
6065           * setting.  I am simply closing the old socket and binding the
6066           * new one.
6067           *
6068           * Which-ever is correct, we will serve 1 more page via the
6069           * old settings.  This should probably be a "show-status"
6070           * request.  This should not be a so common of an operation
6071           * that this will hurt people's feelings.
6072           */
6073
6074          close_ports_helper(bfds);
6075
6076          bind_ports_helper(config, bfds);
6077       }
6078
6079 #ifdef FEATURE_TOGGLE
6080       if (global_toggle_state)
6081 #endif /* def FEATURE_TOGGLE */
6082       {
6083          csp->flags |= CSP_FLAG_TOGGLED_ON;
6084       }
6085
6086       if (run_loader(csp))
6087       {
6088          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6089          /* Never get here - LOG_LEVEL_FATAL causes program exit */
6090       }
6091
6092 #ifdef FEATURE_ACL
6093       if (block_acl(NULL,csp))
6094       {
6095          log_error(LOG_LEVEL_CONNECT,
6096             "Connection from %s on %s (socket %d) dropped due to ACL",
6097             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6098          close_socket(csp->cfd);
6099          freez(csp->ip_addr_str);
6100          freez(csp->listen_addr_str);
6101          freez(csp_list);
6102          continue;
6103       }
6104 #endif /* def FEATURE_ACL */
6105
6106       if ((0 != config->max_client_connections)
6107          && (active_threads >= config->max_client_connections))
6108       {
6109          log_error(LOG_LEVEL_ERROR,
6110             "Rejecting connection from %s. Maximum number of connections reached.",
6111             csp->ip_addr_str);
6112          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6113             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6114          close_socket(csp->cfd);
6115          freez(csp->ip_addr_str);
6116          freez(csp->listen_addr_str);
6117          freez(csp_list);
6118          continue;
6119       }
6120
6121       /* add it to the list of clients */
6122       csp_list->next = clients->next;
6123       clients->next = csp_list;
6124
6125       if (config->multi_threaded)
6126       {
6127          int child_id;
6128
6129 /* this is a switch () statement in the C preprocessor - ugh */
6130 #undef SELECTED_ONE_OPTION
6131
6132 /* Use Pthreads in preference to native code */
6133 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6134 #define SELECTED_ONE_OPTION
6135          {
6136             pthread_t the_thread;
6137             int ret;
6138
6139             ret = pthread_create(&the_thread, &attrs,
6140                (void * (*)(void *))serve, csp);
6141             child_id = ret ? -1 : 0;
6142          }
6143 #endif
6144
6145 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6146 #define SELECTED_ONE_OPTION
6147          child_id = _beginthread(
6148             (void (*)(void *))serve,
6149             64 * 1024,
6150             csp);
6151 #endif
6152
6153 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6154 #define SELECTED_ONE_OPTION
6155          {
6156             thread_id tid = spawn_thread
6157                (server_thread, "server", B_NORMAL_PRIORITY, csp);
6158
6159             if ((tid >= 0) && (resume_thread(tid) == B_OK))
6160             {
6161                child_id = (int) tid;
6162             }
6163             else
6164             {
6165                child_id = -1;
6166             }
6167          }
6168 #endif
6169
6170 #if !defined(SELECTED_ONE_OPTION)
6171          child_id = fork();
6172
6173          /* This block is only needed when using fork().
6174           * When using threads, the server thread was
6175           * created and run by the call to _beginthread().
6176           */
6177          if (child_id == 0)   /* child */
6178          {
6179             int rc = 0;
6180 #ifdef FEATURE_TOGGLE
6181             int inherited_toggle_state = global_toggle_state;
6182 #endif /* def FEATURE_TOGGLE */
6183
6184             serve(csp);
6185
6186             /*
6187              * If we've been toggled or we've blocked the request, tell Mom
6188              */
6189
6190 #ifdef FEATURE_TOGGLE
6191             if (inherited_toggle_state != global_toggle_state)
6192             {
6193                rc |= RC_FLAG_TOGGLED;
6194             }
6195 #endif /* def FEATURE_TOGGLE */
6196
6197 #ifdef FEATURE_STATISTICS
6198             if (csp->flags & CSP_FLAG_REJECTED)
6199             {
6200                rc |= RC_FLAG_BLOCKED;
6201             }
6202 #endif /* ndef FEATURE_STATISTICS */
6203
6204             _exit(rc);
6205          }
6206          else if (child_id > 0) /* parent */
6207          {
6208             /* in a fork()'d environment, the parent's
6209              * copy of the client socket and the CSP
6210              * are not used.
6211              */
6212             int child_status;
6213 #if !defined(_WIN32) && !defined(__CYGWIN__)
6214
6215             wait(&child_status);
6216
6217             /*
6218              * Evaluate child's return code: If the child has
6219              *  - been toggled, toggle ourselves
6220              *  - blocked its request, bump up the stats counter
6221              */
6222
6223 #ifdef FEATURE_TOGGLE
6224             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6225             {
6226                global_toggle_state = !global_toggle_state;
6227             }
6228 #endif /* def FEATURE_TOGGLE */
6229
6230 #ifdef FEATURE_STATISTICS
6231             urls_read++;
6232             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6233             {
6234                urls_rejected++;
6235             }
6236 #endif /* def FEATURE_STATISTICS */
6237
6238 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6239             close_socket(csp->cfd);
6240             csp->flags &= ~CSP_FLAG_ACTIVE;
6241          }
6242 #endif
6243
6244 #undef SELECTED_ONE_OPTION
6245 /* end of cpp switch () */
6246
6247          if (child_id < 0)
6248          {
6249             /*
6250              * Spawning the child failed, assume it's because
6251              * there are too many children running already.
6252              * XXX: If you assume ...
6253              */
6254             log_error(LOG_LEVEL_ERROR,
6255                "Unable to take any additional connections: %E. Active threads: %u",
6256                active_threads);
6257             write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6258                strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6259             close_socket(csp->cfd);
6260             csp->flags &= ~CSP_FLAG_ACTIVE;
6261          }
6262       }
6263       else
6264       {
6265          serve(csp);
6266       }
6267    }
6268
6269 #if defined(FEATURE_PTHREAD)
6270    pthread_attr_destroy(&attrs);
6271 #endif
6272
6273    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6274
6275 #ifdef FEATURE_GRACEFUL_TERMINATION
6276
6277    log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6278
6279    close_ports_helper(bfds);
6280
6281    unload_current_config_file();
6282    unload_current_actions_file();
6283    unload_current_re_filterfile();
6284 #ifdef FEATURE_TRUST
6285    unload_current_trust_file();
6286 #endif
6287
6288    if (config->multi_threaded)
6289    {
6290       int i = 60;
6291       do
6292       {
6293          sleep(1);
6294          sweep();
6295       } while ((clients->next != NULL) && (--i > 0));
6296
6297       if (i <= 0)
6298       {
6299          log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6300             "- still some live clients after 1 minute wait.");
6301       }
6302    }
6303    sweep();
6304    sweep();
6305
6306 #if defined(unix)
6307    freez(basedir);
6308 #endif
6309
6310 #ifdef FEATURE_HTTPS_INSPECTION
6311    /*
6312     * Only release TLS backed resources if there
6313     * are no active connections left.
6314     */
6315    if (clients->next == NULL)
6316    {
6317       ssl_release();
6318    }
6319 #endif
6320
6321    log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6322
6323 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6324    /* Cleanup - remove taskbar icon etc. */
6325    TermLogWindow();
6326 #endif
6327
6328    exit(0);
6329 #endif /* FEATURE_GRACEFUL_TERMINATION */
6330
6331 }
6332
6333
6334 /*
6335   Local Variables:
6336   tab-width: 3
6337   end:
6338 */