send_http_request(): Prevent memory leaks when handling errors
[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          freez(to_send);
2210          return 1;
2211       }
2212       csp->expected_client_content_length = 0;
2213    }
2214
2215    hdr = list_to_text(csp->headers);
2216    if (hdr == NULL)
2217    {
2218       /* FIXME Should handle error properly */
2219       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2220    }
2221    list_remove_all(csp->headers);
2222
2223    /*
2224     * Write the client's (modified) header to the server
2225     * (along with anything else that may be in the buffer)
2226     */
2227    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2228    freez(hdr);
2229
2230    if (write_failure)
2231    {
2232       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2233          csp->http->hostport);
2234       if (filter_client_body)
2235       {
2236          freez(to_send);
2237       }
2238       return 1;
2239    }
2240
2241    if (filter_client_body)
2242    {
2243       write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2244       freez(to_send);
2245       if (write_failure)
2246       {
2247          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2248             csp->http->hostport);
2249          return 1;
2250       }
2251    }
2252
2253    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2254       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2255    {
2256       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2257          csp->http->hostport);
2258       return 1;
2259    }
2260    return 0;
2261 }
2262
2263
2264 #ifdef FEATURE_HTTPS_INSPECTION
2265 /*********************************************************************
2266  *
2267  * Function    : read_https_request_body
2268  *
2269  * Description : Reads remaining request body from the client.
2270  *
2271  * Parameters  :
2272  *          1  :  csp = Current client state (buffers, headers, etc...)
2273  *
2274  * Returns     :  0 on success, anything else is an error.
2275  *
2276  *********************************************************************/
2277 static int read_https_request_body(struct client_state *csp)
2278 {
2279    size_t to_read = csp->expected_client_content_length;
2280    int len;
2281
2282    assert(to_read != 0);
2283
2284    /* check if all data has been already read */
2285    if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2286    {
2287       return 0;
2288    }
2289
2290    for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2291         to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2292           data_is_available(csp->cfd, csp->config->socket_timeout));
2293         to_read -= (unsigned)len)
2294    {
2295       unsigned char buf[BUFFER_SIZE];
2296       size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2297
2298       log_error(LOG_LEVEL_CONNECT,
2299          "Waiting for up to %lu bytes of request body from the client.",
2300          max_bytes_to_read);
2301       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2302          (unsigned)max_bytes_to_read);
2303       if (len <= 0)
2304       {
2305          log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2306          return 1;
2307       }
2308       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2309       {
2310          return 1;
2311       }
2312       assert(to_read >= len);
2313    }
2314
2315    if (to_read != 0)
2316    {
2317       log_error(LOG_LEVEL_CONNECT,
2318          "Not enough request body has been read: expected %lu more bytes",
2319          to_read);
2320       return 1;
2321    }
2322
2323    log_error(LOG_LEVEL_CONNECT,
2324       "The last %llu bytes of the request body have been read",
2325       csp->expected_client_content_length);
2326    return 0;
2327 }
2328
2329
2330 /*********************************************************************
2331  *
2332  * Function    : receive_and_send_encrypted_post_data
2333  *
2334  * Description : Reads remaining request body from the client and sends
2335  *               it to the server.
2336  *
2337  * Parameters  :
2338  *          1  :  csp = Current client state (buffers, headers, etc...)
2339  *
2340  * Returns     :  0 on success, anything else is an error.
2341  *
2342  *********************************************************************/
2343 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2344 {
2345    int content_length_known = csp->expected_client_content_length != 0;
2346
2347    while (is_ssl_pending(&(csp->ssl_client_attr))
2348       || (content_length_known && csp->expected_client_content_length != 0))
2349    {
2350       unsigned char buf[BUFFER_SIZE];
2351       int len;
2352       int max_bytes_to_read = sizeof(buf);
2353
2354       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2355       {
2356          max_bytes_to_read = (int)csp->expected_client_content_length;
2357       }
2358       log_error(LOG_LEVEL_CONNECT,
2359          "Waiting for up to %d bytes of request body from the client.",
2360          max_bytes_to_read);
2361       len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2362          (unsigned)max_bytes_to_read);
2363       if (len == -1)
2364       {
2365          return 1;
2366       }
2367       if (len == 0)
2368       {
2369          /* XXX: Does this actually happen? */
2370          break;
2371       }
2372       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2373          len);
2374       len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2375       if (len == -1)
2376       {
2377          return 1;
2378       }
2379       if (csp->expected_client_content_length != 0)
2380       {
2381          if (csp->expected_client_content_length >= len)
2382          {
2383             csp->expected_client_content_length -= (unsigned)len;
2384          }
2385          if (csp->expected_client_content_length == 0)
2386          {
2387             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2388             break;
2389          }
2390       }
2391    }
2392
2393    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2394
2395    return 0;
2396
2397 }
2398
2399
2400 /*********************************************************************
2401  *
2402  * Function    : send_https_request
2403  *
2404  * Description : Sends the HTTP headers from the client request
2405  *               and all the body data that has already been received.
2406  *
2407  * Parameters  :
2408  *          1  :  csp = Current client state (buffers, headers, etc...)
2409  *
2410  * Returns     :  0 on success, anything else is an error.
2411  *
2412  *********************************************************************/
2413 static int send_https_request(struct client_state *csp)
2414 {
2415    char *hdr;
2416    int ret;
2417    long flushed = 0;
2418    const char *to_send;
2419    size_t to_send_len;
2420    int filter_client_body = csp->expected_client_content_length != 0 &&
2421       client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2422
2423    if (filter_client_body)
2424    {
2425       if (read_https_request_body(csp))
2426       {
2427          return 1;
2428       }
2429       to_send_len = csp->expected_client_content_length;
2430       to_send = execute_client_body_filters(csp, &to_send_len);
2431       if (to_send == NULL)
2432       {
2433          /* just flush client_iob */
2434          filter_client_body = FALSE;
2435       }
2436       else if (to_send_len != csp->expected_client_content_length &&
2437          update_client_headers(csp, to_send_len))
2438       {
2439          log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2440          return 1;
2441       }
2442       csp->expected_client_content_length = 0;
2443    }
2444
2445    hdr = list_to_text(csp->https_headers);
2446    if (hdr == NULL)
2447    {
2448       /* FIXME Should handle error properly */
2449       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2450    }
2451    list_remove_all(csp->https_headers);
2452
2453    /*
2454     * Write the client's (modified) header to the server
2455     * (along with anything else that may be in the buffer)
2456     */
2457    ret = ssl_send_data(&(csp->ssl_server_attr),
2458       (const unsigned char *)hdr, strlen(hdr));
2459    freez(hdr);
2460
2461    if (ret < 0)
2462    {
2463       log_error(LOG_LEVEL_CONNECT,
2464          "Failed sending encrypted request headers to: %s: %E",
2465          csp->http->hostport);
2466       mark_server_socket_tainted(csp);
2467       return 1;
2468    }
2469
2470    if (filter_client_body)
2471    {
2472       ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2473       freez(to_send);
2474       if (ret < 0)
2475       {
2476          log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2477             csp->http->hostport);
2478          return 1;
2479       }
2480    }
2481
2482    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2483       && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2484             csp->client_iob)) < 0))
2485    {
2486       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2487          csp->http->hostport);
2488       return 1;
2489    }
2490    if (flushed != 0 || csp->expected_client_content_length != 0)
2491    {
2492       if (csp->expected_client_content_length != 0)
2493       {
2494          if (csp->expected_client_content_length < flushed)
2495          {
2496             log_error(LOG_LEVEL_ERROR,
2497                "Flushed %ld bytes of request body while only expecting %llu",
2498                flushed, csp->expected_client_content_length);
2499             csp->expected_client_content_length = 0;
2500          }
2501          else
2502          {
2503             log_error(LOG_LEVEL_CONNECT,
2504                "Flushed %ld bytes of request body while expecting %llu",
2505                flushed, csp->expected_client_content_length);
2506             csp->expected_client_content_length -= (unsigned)flushed;
2507             if (receive_and_send_encrypted_post_data(csp))
2508             {
2509                return 1;
2510             }
2511          }
2512       }
2513       else
2514       {
2515          log_error(LOG_LEVEL_CONNECT,
2516             "Flushed %ld bytes of request body", flushed);
2517       }
2518    }
2519
2520    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2521
2522    return 0;
2523
2524 }
2525
2526
2527 /*********************************************************************
2528  *
2529  * Function    :  receive_encrypted_request_headers
2530  *
2531  * Description :  Receives the encrypted request headers when
2532  *                https-inspecting.
2533  *
2534  * Parameters  :
2535  *          1  :  csp = Current client state (buffers, headers, etc...)
2536  *
2537  * Returns     :  JB_ERR_OK on success,
2538  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2539  *
2540  *********************************************************************/
2541 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2542 {
2543    char buf[BUFFER_SIZE];
2544    int len;
2545    char *p;
2546
2547    do
2548    {
2549       log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2550       if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2551           !data_is_available(csp->cfd, csp->config->socket_timeout))
2552       {
2553          log_error(LOG_LEVEL_CONNECT,
2554             "Socket %d timed out while waiting for client headers", csp->cfd);
2555          return JB_ERR_PARSE;
2556       }
2557       len = ssl_recv_data(&(csp->ssl_client_attr),
2558          (unsigned char *)buf, sizeof(buf));
2559       if (len == 0)
2560       {
2561          log_error(LOG_LEVEL_CONNECT,
2562             "Socket %d closed while waiting for client headers", csp->cfd);
2563          return JB_ERR_PARSE;
2564       }
2565       if (len == -1)
2566       {
2567          return JB_ERR_PARSE;
2568       }
2569       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2570       {
2571          return JB_ERR_MEMORY;
2572       }
2573       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2574    } while (p == NULL);
2575
2576    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2577
2578    return JB_ERR_OK;
2579 }
2580
2581
2582 /*********************************************************************
2583  *
2584  * Function    :  change_encrypted_request_destination
2585  *
2586  * Description :  Parse a (rewritten) request line from an encrypted
2587  *                request and regenerate the http request data.
2588  *
2589  * Parameters  :
2590  *          1  :  csp = Current client state (buffers, headers, etc...)
2591  *
2592  * Returns     :  Forwards the parse_http_request() return code.
2593  *                Terminates in case of memory problems.
2594  *
2595  *********************************************************************/
2596 static jb_err change_encrypted_request_destination(struct client_state *csp)
2597 {
2598    jb_err err;
2599    char *original_host = csp->http->host;
2600    int original_port = csp->http->port;
2601
2602    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2603       csp->https_headers->first->str);
2604    csp->http->host = NULL;
2605    free_http_request(csp->http);
2606    err = parse_http_request(csp->https_headers->first->str, csp->http);
2607    if (JB_ERR_OK != err)
2608    {
2609       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2610          jb_err_to_string(err));
2611       freez(original_host);
2612       return err;
2613    }
2614
2615    if (csp->http->host == NULL)
2616    {
2617       char port_string[10];
2618       /*
2619        * The rewritten request line did not specify a host
2620        * which means we can use the original host specified
2621        * by the client.
2622        */
2623       csp->http->host = original_host;
2624       csp->http->port = original_port;
2625       log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2626          csp->http->host);
2627       /*
2628        * If the rewritten request line didn't contain a host
2629        * it also didn't contain a port so we can reuse the host
2630        * port.
2631        */
2632       freez(csp->http->hostport);
2633       csp->http->hostport = strdup_or_die(csp->http->host);
2634       snprintf(port_string, sizeof(port_string), ":%d", original_port);
2635       err = string_append(&csp->http->hostport, port_string);
2636       if (err != JB_ERR_OK)
2637       {
2638          log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2639             jb_err_to_string(err));
2640          return err;
2641       }
2642
2643       /*
2644        * While the request line didn't mention it,
2645        * we're https-inspecting and want to speak TLS
2646        * with the server.
2647        */
2648       csp->http->server_ssl = 1;
2649       csp->http->ssl = 1;
2650    }
2651    else
2652    {
2653       /* The rewrite filter added a host so we can ditch the original */
2654       freez(original_host);
2655       csp->http->server_ssl = csp->http->ssl;
2656    }
2657
2658    csp->http->client_ssl = 1;
2659
2660    freez(csp->https_headers->first->str);
2661    build_request_line(csp, NULL, &csp->https_headers->first->str);
2662
2663    if (!server_use_ssl(csp))
2664    {
2665       log_error(LOG_LEVEL_REDIRECTS,
2666          "Rewritten request line results in downgrade to http");
2667       /*
2668        * Replace the unencryptd headers received with the
2669        * CONNECT request with the ones we received securely.
2670        */
2671       destroy_list(csp->headers);
2672       csp->headers->first = csp->https_headers->first;
2673       csp->headers->last  = csp->https_headers->last;
2674       csp->https_headers->first = NULL;
2675       csp->https_headers->last = NULL;
2676    }
2677
2678    return JB_ERR_OK;
2679
2680 }
2681
2682
2683 /*********************************************************************
2684  *
2685  * Function    :  process_encrypted_request_headers
2686  *
2687  * Description :  Receives and parses the encrypted headers send
2688  *                by the client when https-inspecting.
2689  *
2690  * Parameters  :
2691  *          1  :  csp = Current client state (buffers, headers, etc...)
2692  *
2693  * Returns     :  JB_ERR_OK on success,
2694  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2695  *
2696  *********************************************************************/
2697 static jb_err process_encrypted_request_headers(struct client_state *csp)
2698 {
2699    char *p;
2700    char *request_line;
2701    jb_err err;
2702    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2703    struct list header_list;
2704    struct list *headers = &header_list;
2705
2706    assert(csp->ssl_with_client_is_opened);
2707
2708 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2709    if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2710    {
2711       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2712    }
2713 #endif
2714    err = receive_encrypted_request_headers(csp);
2715    if (err != JB_ERR_OK)
2716    {
2717       if (csp->client_iob->cur == NULL ||
2718           csp->client_iob->cur == csp->client_iob->eod)
2719       {
2720          /*
2721           * We did not receive any data, most likely because the
2722           * client is done. Don't log this as a parse failure.
2723           */
2724          return JB_ERR_PARSE;
2725       }
2726       /* XXX: Also used for JB_ERR_MEMORY */
2727       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2728          jb_err_to_string(err));
2729       ssl_send_data_delayed(&(csp->ssl_client_attr),
2730          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2731       return err;
2732    }
2733
2734    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2735    request_line = get_header(csp->client_iob);
2736    if (request_line == NULL)
2737    {
2738       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2739       ssl_send_data_delayed(&(csp->ssl_client_attr),
2740          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2741       return JB_ERR_PARSE;
2742    }
2743    assert(*request_line != '\0');
2744
2745    if (client_protocol_is_unsupported(csp, request_line))
2746    {
2747       /*
2748        * If the protocol is unsupported we're done here.
2749        * client_protocol_is_unsupported() took care of sending
2750        * the error response and logging the error message.
2751        */
2752       return JB_ERR_PARSE;
2753    }
2754
2755 #ifdef FEATURE_FORCE_LOAD
2756    if (force_required(csp, request_line))
2757    {
2758       csp->flags |= CSP_FLAG_FORCED;
2759    }
2760 #endif /* def FEATURE_FORCE_LOAD */
2761
2762    free_http_request(csp->http);
2763
2764    err = parse_http_request(request_line, csp->http);
2765    /* XXX: Restore ssl setting. This is ugly */
2766    csp->http->client_ssl = 1;
2767    csp->http->server_ssl = 1;
2768
2769    freez(request_line);
2770    if (JB_ERR_OK != err)
2771    {
2772       ssl_send_data_delayed(&(csp->ssl_client_attr),
2773          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2774       /* XXX: Use correct size */
2775       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2776       log_error(LOG_LEVEL_ERROR,
2777          "Couldn't parse request line received from %s: %s",
2778          csp->ip_addr_str, jb_err_to_string(err));
2779
2780       free_http_request(csp->http);
2781       return JB_ERR_PARSE;
2782    }
2783
2784    /* Parse the rest of the client's headers. */
2785    init_list(headers);
2786    for (;;)
2787    {
2788       p = get_header(csp->client_iob);
2789
2790       if (p == NULL)
2791       {
2792          /* There are no additional headers to read. */
2793          break;
2794       }
2795       enlist(headers, p);
2796       freez(p);
2797    }
2798
2799    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2800    {
2801       /*
2802        * Our attempts to get the request destination
2803        * elsewhere failed.
2804        */
2805       log_error(LOG_LEVEL_ERROR,
2806          "Failed to get the encrypted request destination");
2807       ssl_send_data_delayed(&(csp->ssl_client_attr),
2808          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2809       return JB_ERR_PARSE;
2810    }
2811
2812    /* Split the domain we just got for pattern matching */
2813    init_domain_components(csp->http);
2814
2815 #ifdef FEATURE_CLIENT_TAGS
2816    /* XXX: If the headers were enlisted sooner, passing csp would do. */
2817    if (csp->client_address == NULL)
2818    {
2819       set_client_address(csp, headers);
2820       get_tag_list_for_client(csp->client_tags, csp->client_address);
2821    }
2822 #endif
2823
2824 #ifdef FEATURE_TOGGLE
2825    if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2826 #endif
2827    {
2828       /*
2829        * Determine the actions for this request after
2830        * clearing the ones from the previous one.
2831        */
2832       free_current_action(csp->action);
2833       get_url_actions(csp, csp->http);
2834    }
2835
2836    enlist(csp->https_headers, csp->http->cmd);
2837
2838    /* Append the previously read headers */
2839    err = list_append_list_unique(csp->https_headers, headers);
2840    destroy_list(headers);
2841    if (JB_ERR_OK != err)
2842    {
2843       /* XXX: Send error message */
2844       return err;
2845    }
2846
2847    /* XXX: Work around crash */
2848    csp->error_message = NULL;
2849
2850    /* XXX: Why do this here? */
2851    csp->http->ssl = 1;
2852
2853    err = sed_https(csp);
2854    if (JB_ERR_OK != err)
2855    {
2856       ssl_send_data_delayed(&(csp->ssl_client_attr),
2857          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2858       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2859          csp->ip_addr_str);
2860       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2861          csp->ip_addr_str, csp->http->cmd);
2862       return JB_ERR_PARSE;
2863    }
2864
2865    if ((NULL == csp->https_headers->first->str)
2866       || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2867          (JB_ERR_OK != change_encrypted_request_destination(csp))))
2868    {
2869       ssl_send_data_delayed(&(csp->ssl_client_attr),
2870          (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2871          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2872       log_error(LOG_LEVEL_ERROR,
2873          "Invalid request line after applying header filters.");
2874       /* XXX: Use correct size */
2875       log_error(LOG_LEVEL_CLF,
2876          "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2877
2878       return JB_ERR_PARSE;
2879    }
2880
2881    log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2882    log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2883       csp->http->path);
2884
2885    return err;
2886
2887 }
2888
2889 /*********************************************************************
2890  *
2891  * Function    :  cgi_page_requested
2892  *
2893  * Description :  Checks if a request is for an internal CGI page.
2894  *
2895  * Parameters  :
2896  *          1  :  host = The host requested by the client.
2897  *
2898  * Returns     :  1 if a CGI page has been requested, 0 otherwise
2899  *
2900  *********************************************************************/
2901 static int cgi_page_requested(const char *host)
2902 {
2903    if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2904     || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2905     || (0 == strcmpic(host, CGI_SITE_2_HOST))
2906     || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2907    {
2908       return 1;
2909    }
2910
2911    return 0;
2912
2913 }
2914
2915
2916 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2917 /*********************************************************************
2918  *
2919  * Function    :  continue_https_chat
2920  *
2921  * Description :  Behaves similar to chat() but only deals with
2922  *                https-inspected requests that arrive on an already
2923  *                established connection. The first request is always
2924  *                served by chat() which is a lot more complex as it
2925  *                has to deal with forwarding settings and connection
2926  *                failures etc.
2927  *
2928  *                If a connection to the server has already been
2929  *                opened it is reused unless the request is blocked
2930  *                or the forwarder changed.
2931  *
2932  *                If a connection to the server has not yet been
2933  *                opened (because the previous request was crunched),
2934  *                or the forwarder changed, the connection is dropped
2935  *                so that the client retries on a fresh one.
2936  *
2937  * Parameters  :
2938  *          1  :  csp = Current client state (buffers, headers, etc...)
2939  *
2940  * Returns     :  Nothing.
2941  *
2942  *********************************************************************/
2943 static void continue_https_chat(struct client_state *csp)
2944 {
2945    const struct forward_spec *fwd;
2946
2947    if (JB_ERR_OK != process_encrypted_request_headers(csp))
2948    {
2949       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2950       return;
2951    }
2952
2953    csp->requests_received_total++;
2954
2955    /*
2956     * We have an encrypted request. Check if one of the crunchers wants it.
2957     */
2958    if (crunch_response_triggered(csp, crunchers_all))
2959    {
2960       /*
2961        * Yes. The client got the crunch response and we're done here.
2962        */
2963       return;
2964    }
2965    if (csp->ssl_with_server_is_opened == 0)
2966    {
2967       log_error(LOG_LEVEL_CONNECT,
2968          "Dropping the client connection on socket %d. "
2969          "The server connection has not been established yet.",
2970          csp->cfd);
2971       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2972       return;
2973    }
2974    assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2975
2976    fwd = forward_url(csp, csp->http);
2977    if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2978    {
2979       log_error(LOG_LEVEL_CONNECT,
2980          "Dropping the client connection on socket %d with "
2981          "server socket %d connected to %s. The forwarder has changed.",
2982          csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2983       csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2984       return;
2985    }
2986
2987    log_applied_actions(csp->action);
2988
2989    log_error(LOG_LEVEL_CONNECT,
2990       "Reusing server socket %d connected to %s. Requests already sent: %u.",
2991       csp->server_connection.sfd, csp->server_connection.host,
2992       csp->server_connection.requests_sent_total);
2993
2994    if (send_https_request(csp))
2995    {
2996       /*
2997        * Most likely the server connection timed out. We can't easily
2998        * create a new one so simply drop the client connection without a
2999        * error response to let the client retry.
3000        */
3001       log_error(LOG_LEVEL_CONNECT,
3002          "Dropping client connection on socket %d. "
3003          "Forwarding the encrypted client request failed.",
3004          csp->cfd);
3005       return;
3006    }
3007    csp->server_connection.request_sent = time(NULL);
3008    csp->server_connection.requests_sent_total++;
3009    handle_established_connection(csp);
3010    freez(csp->receive_buffer);
3011 }
3012 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3013 #endif
3014
3015
3016 /*********************************************************************
3017  *
3018  * Function    :  handle_established_connection
3019  *
3020  * Description :  Shuffle data between client and server once the
3021  *                connection has been established and the request
3022  *                has been sent.
3023  *
3024  * Parameters  :
3025  *          1  :  csp = Current client state (buffers, headers, etc...)
3026  *
3027  * Returns     :  Nothing.
3028  *
3029  *********************************************************************/
3030 static void handle_established_connection(struct client_state *csp)
3031 {
3032    char *hdr;
3033    char *p;
3034    int n;
3035 #ifdef HAVE_POLL
3036    struct pollfd poll_fds[2];
3037 #else
3038    fd_set rfds;
3039    jb_socket maxfd;
3040    struct timeval timeout;
3041 #endif
3042    int server_body;
3043    int ms_iis5_hack = 0;
3044    unsigned long long byte_count = 0;
3045    struct http_request *http;
3046    long len = 0; /* for buffer sizes (and negative error codes) */
3047    int buffer_and_filter_content = 0;
3048    unsigned int write_delay;
3049 #ifdef FEATURE_HTTPS_INSPECTION
3050    int ret = 0;
3051    int use_ssl_tunnel = 0;
3052    csp->dont_verify_certificate = 0;
3053
3054    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3055    {
3056       /* Pass encrypted content without filtering. */
3057       use_ssl_tunnel = 1;
3058    }
3059 #endif
3060
3061    /* Skeleton for HTTP response, if we should intercept the request */
3062    struct http_response *rsp;
3063 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3064    int watch_client_socket;
3065 #endif
3066
3067    csp->receive_buffer_size = csp->config->receive_buffer_size;
3068    csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3069    if (csp->receive_buffer == NULL)
3070    {
3071       log_error(LOG_LEVEL_ERROR,
3072          "Out of memory. Failed to allocate the receive buffer.");
3073       rsp = cgi_error_memory();
3074       send_crunch_response(csp, rsp);
3075       return;
3076    }
3077
3078    http = csp->http;
3079
3080 #ifndef HAVE_POLL
3081    maxfd = (csp->cfd > csp->server_connection.sfd) ?
3082       csp->cfd : csp->server_connection.sfd;
3083 #endif
3084
3085    /* pass data between the client and server
3086     * until one or the other shuts down the connection.
3087     */
3088
3089    server_body = 0;
3090
3091 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3092    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3093 #endif
3094    write_delay = get_write_delay(csp);
3095
3096    for (;;)
3097    {
3098 #ifdef FEATURE_HTTPS_INSPECTION
3099       if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3100       {
3101          /*
3102           * It's possible that the TLS library already consumed all the
3103           * data the server intends to send. If that happens poll() and
3104           * select() will no longer see the data as available so we have
3105           * to skip the calls.
3106           */
3107          goto server_wants_to_talk;
3108       }
3109 #endif
3110 #ifndef HAVE_POLL
3111       FD_ZERO(&rfds);
3112 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3113       if (!watch_client_socket)
3114       {
3115          maxfd = csp->server_connection.sfd;
3116       }
3117       else
3118 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3119       {
3120          FD_SET(csp->cfd, &rfds);
3121       }
3122
3123       FD_SET(csp->server_connection.sfd, &rfds);
3124 #endif /* ndef HAVE_POLL */
3125
3126 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3127       if ((csp->flags & CSP_FLAG_CHUNKED)
3128          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3129          && ((csp->iob->eod - csp->iob->cur) >= 5)
3130          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3131       {
3132          /*
3133           * XXX: This check should be obsolete now,
3134           *      but let's wait a while to be sure.
3135           */
3136          log_error(LOG_LEVEL_CONNECT,
3137             "Looks like we got the last chunk together with "
3138             "the server headers but didn't detect it earlier. "
3139             "We better stop reading.");
3140          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3141          csp->expected_content_length = byte_count;
3142          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3143       }
3144       if (server_body && server_response_is_complete(csp, byte_count))
3145       {
3146          if (csp->expected_content_length == byte_count)
3147          {
3148             log_error(LOG_LEVEL_CONNECT,
3149                "Done reading from server. Content length: %llu as expected. "
3150                "Bytes most recently read: %ld.",
3151                byte_count, len);
3152          }
3153          else
3154          {
3155             log_error(LOG_LEVEL_CONNECT,
3156                "Done reading from server. Expected content length: %llu. "
3157                "Actual content length: %llu. Bytes most recently read: %ld.",
3158                csp->expected_content_length, byte_count, len);
3159          }
3160          len = 0;
3161          /*
3162           * XXX: Should not jump around, handle_established_connection()
3163           * is complicated enough already.
3164           */
3165          goto reading_done;
3166       }
3167 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3168
3169 #ifdef HAVE_POLL
3170       poll_fds[0].fd = csp->cfd;
3171 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3172       if (!watch_client_socket)
3173       {
3174          /*
3175           * Ignore incoming data, but still watch out
3176           * for disconnects etc. These flags are always
3177           * implied anyway but explicitly setting them
3178           * doesn't hurt.
3179           */
3180          poll_fds[0].events = POLLERR|POLLHUP;
3181       }
3182       else
3183 #endif
3184       {
3185          poll_fds[0].events = POLLIN;
3186       }
3187       poll_fds[1].fd = csp->server_connection.sfd;
3188       poll_fds[1].events = POLLIN;
3189       n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3190 #else
3191       timeout.tv_sec = csp->config->socket_timeout;
3192       timeout.tv_usec = 0;
3193       n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3194 #endif /* def HAVE_POLL */
3195
3196       /* Server or client not responding in timeout */
3197       if (n == 0)
3198       {
3199          log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3200             csp->config->socket_timeout, http->url);
3201          if ((byte_count == 0) && (http->ssl == 0))
3202          {
3203             send_crunch_response(csp, error_response(csp, "connection-timeout"));
3204          }
3205          mark_server_socket_tainted(csp);
3206 #ifdef FEATURE_HTTPS_INSPECTION
3207          close_client_and_server_ssl_connections(csp);
3208 #endif
3209          return;
3210       }
3211       else if (n < 0)
3212       {
3213 #ifdef HAVE_POLL
3214          log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3215 #else
3216          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3217 #endif
3218          mark_server_socket_tainted(csp);
3219 #ifdef FEATURE_HTTPS_INSPECTION
3220          close_client_and_server_ssl_connections(csp);
3221 #endif
3222          return;
3223       }
3224
3225       /*
3226        * This is the body of the browser's request,
3227        * just read and write it.
3228        *
3229        * Receives data from browser and sends it to server
3230        *
3231        * XXX: Make sure the client doesn't use pipelining
3232        * behind Privoxy's back.
3233        */
3234 #ifdef HAVE_POLL
3235       if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3236       {
3237          log_error(LOG_LEVEL_CONNECT,
3238             "The client socket %d has become unusable while "
3239             "the server socket %d is still open.",
3240             csp->cfd, csp->server_connection.sfd);
3241          mark_server_socket_tainted(csp);
3242          break;
3243       }
3244
3245       if (poll_fds[0].revents != 0)
3246 #else
3247       if (FD_ISSET(csp->cfd, &rfds))
3248 #endif /* def HAVE_POLL*/
3249       {
3250          int max_bytes_to_read = (int)csp->receive_buffer_size;
3251
3252 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3253          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3254          {
3255             if (data_is_available(csp->cfd, 0))
3256             {
3257                /*
3258                 * If the next request is already waiting, we have
3259                 * to stop select()ing the client socket. Otherwise
3260                 * we would always return right away and get nothing
3261                 * else done.
3262                 */
3263                watch_client_socket = 0;
3264                log_error(LOG_LEVEL_CONNECT,
3265                   "Stop watching client socket %d. "
3266                   "There's already another request waiting.",
3267                   csp->cfd);
3268                continue;
3269             }
3270             /*
3271              * If the client socket is set, but there's no data
3272              * available on the socket, the client went fishing
3273              * and continuing talking to the server makes no sense.
3274              */
3275             log_error(LOG_LEVEL_CONNECT,
3276                "The client closed socket %d while "
3277                "the server socket %d is still open.",
3278                csp->cfd, csp->server_connection.sfd);
3279             mark_server_socket_tainted(csp);
3280             break;
3281          }
3282          if (csp->expected_client_content_length != 0)
3283          {
3284             if (csp->expected_client_content_length < csp->receive_buffer_size)
3285             {
3286                max_bytes_to_read = (int)csp->expected_client_content_length;
3287             }
3288             log_error(LOG_LEVEL_CONNECT,
3289                "Waiting for up to %d bytes from the client.",
3290                max_bytes_to_read);
3291          }
3292          assert(max_bytes_to_read <= csp->receive_buffer_size);
3293 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3294
3295 #ifdef FEATURE_HTTPS_INSPECTION
3296          if (client_use_ssl(csp))
3297          {
3298             if (csp->http->status == 101)
3299             {
3300                len = ssl_recv_data(&(csp->ssl_client_attr),
3301                   (unsigned char *)csp->receive_buffer,
3302                   (size_t)max_bytes_to_read);
3303                if (len == -1)
3304                {
3305                   log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3306                      "on client socket %d for an upgraded connection",
3307                      csp->cfd);
3308                   break;
3309                }
3310                if (len == 0)
3311                {
3312                   log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3313                      "on client socket %d for an upgraded connection",
3314                      csp->cfd);
3315                   break;
3316                }
3317                byte_count += (unsigned long long)len;
3318                len = ssl_send_data(&(csp->ssl_server_attr),
3319                   (unsigned char *)csp->receive_buffer, (size_t)len);
3320                if (len == -1)
3321                {
3322                   log_error(LOG_LEVEL_ERROR, "Failed to send data "
3323                      "on server socket %d for an upgraded connection",
3324                      csp->server_connection.sfd);
3325                   break;
3326                }
3327                continue;
3328             }
3329             log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3330             break;
3331          }
3332          else
3333 #endif /* def FEATURE_HTTPS_INSPECTION */
3334          {
3335             len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3336
3337             if (len <= 0)
3338             {
3339                /* XXX: not sure if this is necessary. */
3340                mark_server_socket_tainted(csp);
3341                break; /* "game over, man" */
3342             }
3343
3344 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3345             if (csp->expected_client_content_length != 0)
3346             {
3347                assert(len <= max_bytes_to_read);
3348                csp->expected_client_content_length -= (unsigned)len;
3349                log_error(LOG_LEVEL_CONNECT,
3350                   "Expected client content length set to %llu "
3351                   "after reading %ld bytes.",
3352                   csp->expected_client_content_length, len);
3353                if (csp->expected_client_content_length == 0)
3354                {
3355                   log_error(LOG_LEVEL_CONNECT,
3356                      "Done reading from the client.");
3357                   csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3358                }
3359             }
3360 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3361
3362             if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3363             {
3364                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3365                mark_server_socket_tainted(csp);
3366                return;
3367             }
3368          }
3369          continue;
3370       }
3371
3372       /*
3373        * The server wants to talk. It could be the header or the body.
3374        * If `hdr' is null, then it's the header otherwise it's the body.
3375        * FIXME: Does `hdr' really mean `host'? No.
3376        */
3377 #ifdef HAVE_POLL
3378       if (poll_fds[1].revents != 0)
3379 #else
3380       if (FD_ISSET(csp->server_connection.sfd, &rfds))
3381 #endif /* HAVE_POLL */
3382       {
3383 #ifdef FEATURE_HTTPS_INSPECTION
3384          server_wants_to_talk:
3385 #endif
3386 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3387          /*
3388           * If we are buffering content, we don't want to eat up to
3389           * buffer-limit bytes if the client no longer cares about them.
3390           * If we aren't buffering, however, a dead client socket will be
3391           * noticed pretty much right away anyway, so we can reduce the
3392           * overhead by skipping the check.
3393           */
3394          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3395          {
3396 #ifdef _WIN32
3397             log_error(LOG_LEVEL_CONNECT,
3398                "The server still wants to talk, but the client may already have hung up on us.");
3399 #else
3400             log_error(LOG_LEVEL_CONNECT,
3401                "The server still wants to talk, but the client hung up on us.");
3402             mark_server_socket_tainted(csp);
3403 #ifdef FEATURE_HTTPS_INSPECTION
3404             close_client_and_server_ssl_connections(csp);
3405 #endif
3406             return;
3407 #endif /* def _WIN32 */
3408          }
3409 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3410
3411 #ifdef FEATURE_HTTPS_INSPECTION
3412          /*
3413           * Reading data from standard or secured connection (HTTP/HTTPS)
3414           */
3415          if (server_use_ssl(csp))
3416          {
3417             len = ssl_recv_data(&(csp->ssl_server_attr),
3418                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3419          }
3420          else
3421 #endif
3422          {
3423             len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3424                (int)csp->receive_buffer_size);
3425          }
3426
3427          if (len < 0)
3428          {
3429             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3430
3431             if ((http->ssl && (csp->fwd == NULL))
3432 #ifdef FEATURE_HTTPS_INSPECTION
3433                && use_ssl_tunnel
3434 #endif
3435                 )
3436             {
3437                /*
3438                 * Just hang up. We already confirmed the client's CONNECT
3439                 * request with status code 200 and unencrypted content is
3440                 * no longer welcome.
3441                 */
3442                log_error(LOG_LEVEL_ERROR,
3443                   "CONNECT already confirmed. Unable to tell the client about the problem.");
3444                return;
3445             }
3446             else if (byte_count)
3447             {
3448                /*
3449                 * Just hang up. We already transmitted the original headers
3450                 * and parts of the original content and therefore missed the
3451                 * chance to send an error message (without risking data corruption).
3452                 *
3453                 * XXX: we could retry with a fancy range request here.
3454                 */
3455                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3456                   "Unable to tell the client about the problem.");
3457                mark_server_socket_tainted(csp);
3458 #ifdef FEATURE_HTTPS_INSPECTION
3459                close_client_and_server_ssl_connections(csp);
3460 #endif
3461                return;
3462             }
3463             /*
3464              * XXX: Consider handling the cases above the same.
3465              */
3466             mark_server_socket_tainted(csp);
3467             len = 0;
3468          }
3469
3470 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3471          if (csp->flags & CSP_FLAG_CHUNKED)
3472          {
3473             if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3474             {
3475                /* XXX: this is a temporary hack */
3476                log_error(LOG_LEVEL_CONNECT,
3477                   "Looks like we reached the end of the last chunk. "
3478                   "We better stop reading.");
3479                csp->expected_content_length = byte_count + (unsigned long long)len;
3480                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3481             }
3482          }
3483          reading_done:
3484 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
3485
3486          /*
3487           * This is guaranteed by allocating with zalloc_or_die()
3488           * and never (intentionally) writing to the last byte.
3489           *
3490           * csp->receive_buffer_size is the size of the part of the
3491           * buffer we intentionally write to, but we actually
3492           * allocated csp->receive_buffer_size+1 bytes so the assertion
3493           * stays within the allocated range.
3494           */
3495          assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3496
3497          /*
3498           * Add a trailing zero to let be able to use string operations.
3499           * XXX: do we still need this with filter_popups gone?
3500           */
3501          assert(len <= csp->receive_buffer_size);
3502          csp->receive_buffer[len] = '\0';
3503
3504          /*
3505           * Normally, this would indicate that we've read
3506           * as much as the server has sent us and we can
3507           * close the client connection.  However, Microsoft
3508           * in its wisdom has released IIS/5 with a bug that
3509           * prevents it from sending the trailing \r\n in
3510           * a 302 redirect header (and possibly other headers).
3511           * To work around this if we've haven't parsed
3512           * a full header we'll append a trailing \r\n
3513           * and see if this now generates a valid one.
3514           *
3515           * This hack shouldn't have any impacts.  If we've
3516           * already transmitted the header or if this is a
3517           * SSL connection, then we won't bother with this
3518           * hack.  So we only work on partially received
3519           * headers.  If we append a \r\n and this still
3520           * doesn't generate a valid header, then we won't
3521           * transmit anything to the client.
3522           */
3523          if (len == 0)
3524          {
3525
3526             if (server_body || (http->ssl
3527 #ifdef FEATURE_HTTPS_INSPECTION
3528                   && use_ssl_tunnel
3529 #endif
3530                ))
3531             {
3532                /*
3533                 * If we have been buffering up the document,
3534                 * now is the time to apply content modification
3535                 * and send the result to the client.
3536                 */
3537                if (buffer_and_filter_content)
3538                {
3539                   p = execute_content_filters(csp);
3540                   /*
3541                    * If content filtering fails, use the original
3542                    * buffer and length.
3543                    * (see p != NULL ? p : csp->iob->cur below)
3544                    */
3545                   if (NULL == p)
3546                   {
3547                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3548                   }
3549 #ifdef FEATURE_COMPRESSION
3550                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3551                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3552                   {
3553                      char *compressed_content = compress_buffer(p,
3554                         (size_t *)&csp->content_length, csp->config->compression_level);
3555                      if (compressed_content != NULL)
3556                      {
3557                         freez(p);
3558                         p = compressed_content;
3559                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3560                      }
3561                   }
3562 #endif
3563
3564                   if (JB_ERR_OK != update_server_headers(csp))
3565                   {
3566                      log_error(LOG_LEVEL_FATAL,
3567                         "Failed to update server headers. after filtering.");
3568                   }
3569
3570                   hdr = list_to_text(csp->headers);
3571                   if (hdr == NULL)
3572                   {
3573                      /* FIXME Should handle error properly */
3574                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3575                   }
3576
3577 #ifdef FEATURE_HTTPS_INSPECTION
3578                   /*
3579                    * Sending data with standard or secured connection (HTTP/HTTPS)
3580                    */
3581                   if (client_use_ssl(csp))
3582                   {
3583                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3584                               (const unsigned char *)hdr, strlen(hdr),
3585                               get_write_delay(csp)) < 0)
3586                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3587                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3588                               csp->content_length, get_write_delay(csp)) < 0))
3589                      {
3590                         log_error(LOG_LEVEL_ERROR,
3591                            "Failed to send the modified content to the client over TLS");
3592                         freez(hdr);
3593                         freez(p);
3594                         mark_server_socket_tainted(csp);
3595                         close_client_and_server_ssl_connections(csp);
3596                         return;
3597                      }
3598                   }
3599                   else
3600 #endif /* def FEATURE_HTTPS_INSPECTION */
3601                   {
3602                      if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3603                       || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3604                          (size_t)csp->content_length, write_delay))
3605                      {
3606                         log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3607                         freez(hdr);
3608                         freez(p);
3609                         mark_server_socket_tainted(csp);
3610                         return;
3611                      }
3612                   }
3613
3614                   freez(hdr);
3615                   freez(p);
3616                }
3617
3618                break; /* "game over, man" */
3619             }
3620
3621             /*
3622              * This is not the body, so let's pretend the server just sent
3623              * us a blank line.
3624              */
3625             snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3626             len = (int)strlen(csp->receive_buffer);
3627
3628             /*
3629              * Now, let the normal header parsing algorithm below do its
3630              * job.  If it fails, we'll exit instead of continuing.
3631              */
3632
3633             ms_iis5_hack = 1;
3634          }
3635
3636          /*
3637           * If we're in the body of the server document, just write it to
3638           * the client, unless we need to buffer the body for later
3639           * content-filtering.
3640           */
3641          if (server_body || (http->ssl
3642 #ifdef FEATURE_HTTPS_INSPECTION
3643                && use_ssl_tunnel
3644 #endif
3645             ))
3646          {
3647             if (buffer_and_filter_content)
3648             {
3649                /*
3650                 * If there is no memory left for buffering the content, or the buffer limit
3651                 * has been reached, switch to non-filtering mode, i.e. make & write the
3652                 * header, flush the iob and buf, and get out of the way.
3653                 */
3654                if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3655                {
3656                   size_t hdrlen;
3657                   long flushed;
3658
3659                   log_error(LOG_LEVEL_INFO,
3660                      "Flushing header and buffers. Stepping back from filtering.");
3661
3662                   hdr = list_to_text(csp->headers);
3663                   if (hdr == NULL)
3664                   {
3665                      /*
3666                       * Memory is too tight to even generate the header.
3667                       * Send our static "Out-of-memory" page.
3668                       */
3669                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3670                      rsp = cgi_error_memory();
3671                      send_crunch_response(csp, rsp);
3672                      mark_server_socket_tainted(csp);
3673 #ifdef FEATURE_HTTPS_INSPECTION
3674                      close_client_and_server_ssl_connections(csp);
3675 #endif
3676                      return;
3677                   }
3678                   hdrlen = strlen(hdr);
3679
3680 #ifdef FEATURE_HTTPS_INSPECTION
3681                   /*
3682                    * Sending data with standard or secured connection (HTTP/HTTPS)
3683                    */
3684                   if (client_use_ssl(csp))
3685                   {
3686                      if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3687                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3688                         || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3689                                 csp->iob)) < 0)
3690                         || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3691                               (const unsigned char *)csp->receive_buffer, (size_t)len,
3692                               get_write_delay(csp)) < 0))
3693                      {
3694                         log_error(LOG_LEVEL_CONNECT,
3695                            "Flush header and buffers to client failed");
3696                         freez(hdr);
3697                         mark_server_socket_tainted(csp);
3698                         close_client_and_server_ssl_connections(csp);
3699                         return;
3700                      }
3701                   }
3702                   else
3703 #endif /* def FEATURE_HTTPS_INSPECTION */
3704                   {
3705                      if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3706                       || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3707                       || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3708                             write_delay))
3709                      {
3710                         log_error(LOG_LEVEL_CONNECT,
3711                            "Flush header and buffers to client failed: %E");
3712                         freez(hdr);
3713                         mark_server_socket_tainted(csp);
3714                         return;
3715                      }
3716                   }
3717
3718                   /*
3719                    * Reset the byte_count to the amount of bytes
3720                    * we just flushed. len will be added a few lines below,
3721                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
3722                    */
3723                   byte_count = (unsigned long long)flushed;
3724                   freez(hdr);
3725                   buffer_and_filter_content = 0;
3726                   server_body = 1;
3727                }
3728             }
3729             else
3730             {
3731 #ifdef FEATURE_HTTPS_INSPECTION
3732                /*
3733                 * Sending data with standard or secured connection (HTTP/HTTPS)
3734                 */
3735                if (client_use_ssl(csp))
3736                {
3737                   ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3738                      (const unsigned char *)csp->receive_buffer, (size_t)len,
3739                      get_write_delay(csp));
3740                   if (ret < 0)
3741                   {
3742                      log_error(LOG_LEVEL_ERROR,
3743                         "Sending data to client failed");
3744                      mark_server_socket_tainted(csp);
3745                      close_client_and_server_ssl_connections(csp);
3746                      return;
3747                   }
3748                }
3749                else
3750 #endif /* def FEATURE_HTTPS_INSPECTION */
3751                {
3752                   if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3753                         (size_t)len, write_delay))
3754                   {
3755                      log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3756                      mark_server_socket_tainted(csp);
3757                      return;
3758                   }
3759                }
3760             }
3761             byte_count += (unsigned long long)len;
3762             continue;
3763          }
3764          else
3765          {
3766             /*
3767              * We're still looking for the end of the server's header.
3768              * Buffer up the data we just read.  If that fails, there's
3769              * little we can do but send our static out-of-memory page.
3770              */
3771             if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3772             {
3773                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3774                rsp = cgi_error_memory();
3775                send_crunch_response(csp, rsp);
3776                mark_server_socket_tainted(csp);
3777 #ifdef FEATURE_HTTPS_INSPECTION
3778                close_client_and_server_ssl_connections(csp);
3779 #endif
3780                return;
3781             }
3782
3783             /* Convert iob into something sed() can digest */
3784             if (JB_ERR_PARSE == get_server_headers(csp))
3785             {
3786                if (ms_iis5_hack)
3787                {
3788                   /*
3789                    * Well, we tried our MS IIS/5 hack and it didn't work.
3790                    * The header is incomplete and there isn't anything
3791                    * we can do about it.
3792                    */
3793                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3794                      "Applying the MS IIS5 hack didn't help.");
3795                   log_error(LOG_LEVEL_CLF,
3796                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3797 #ifdef FEATURE_HTTPS_INSPECTION
3798                   /*
3799                    * Sending data with standard or secured connection (HTTP/HTTPS)
3800                    */
3801                   if (client_use_ssl(csp))
3802                   {
3803                      ssl_send_data_delayed(&(csp->ssl_client_attr),
3804                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3805                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3806                   }
3807                   else
3808 #endif /* def FEATURE_HTTPS_INSPECTION */
3809                   {
3810                      write_socket_delayed(csp->cfd,
3811                         INVALID_SERVER_HEADERS_RESPONSE,
3812                         strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3813                   }
3814                   mark_server_socket_tainted(csp);
3815 #ifdef FEATURE_HTTPS_INSPECTION
3816                   close_client_and_server_ssl_connections(csp);
3817 #endif
3818                   return;
3819                }
3820                else
3821                {
3822                   /*
3823                    * Since we have to wait for more from the server before
3824                    * we can parse the headers we just continue here.
3825                    */
3826                   log_error(LOG_LEVEL_CONNECT,
3827                      "Continuing buffering server headers from socket %d. "
3828                      "Bytes most recently read: %ld.", csp->cfd, len);
3829                   continue;
3830                }
3831             }
3832             else
3833             {
3834                /*
3835                 * Account for the content bytes we
3836                 * might have gotten with the headers.
3837                 */
3838                assert(csp->iob->eod >= csp->iob->cur);
3839                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3840             }
3841
3842             /* Did we actually get anything? */
3843             if (NULL == csp->headers->first)
3844             {
3845                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3846                {
3847                   log_error(LOG_LEVEL_ERROR,
3848                      "No server or forwarder response received on socket %d. "
3849                      "Closing client socket %d without sending data.",
3850                      csp->server_connection.sfd, csp->cfd);
3851                   log_error(LOG_LEVEL_CLF,
3852                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3853                }
3854                else
3855                {
3856                   log_error(LOG_LEVEL_ERROR,
3857                      "No server or forwarder response received on socket %d.",
3858                      csp->server_connection.sfd);
3859                   send_crunch_response(csp, error_response(csp, "no-server-data"));
3860                }
3861                free_http_request(http);
3862                mark_server_socket_tainted(csp);
3863 #ifdef FEATURE_HTTPS_INSPECTION
3864                close_client_and_server_ssl_connections(csp);
3865 #endif
3866                return;
3867             }
3868
3869             if (!csp->headers->first->str)
3870             {
3871                log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3872             }
3873             assert(csp->headers->first->str);
3874
3875             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3876                 strncmpic(csp->headers->first->str, "ICY", 3))
3877             {
3878                /*
3879                 * It doesn't look like a HTTP (or Shoutcast) response:
3880                 * tell the client and log the problem.
3881                 */
3882                if (strlen(csp->headers->first->str) > 30)
3883                {
3884                   csp->headers->first->str[30] = '\0';
3885                }
3886                log_error(LOG_LEVEL_ERROR,
3887                   "Invalid server or forwarder response. Starts with: %s",
3888                   csp->headers->first->str);
3889                log_error(LOG_LEVEL_CLF,
3890                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3891 #ifdef FEATURE_HTTPS_INSPECTION
3892                /*
3893                 * Sending data with standard or secured connection (HTTP/HTTPS)
3894                 */
3895                if (client_use_ssl(csp))
3896                {
3897                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3898                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3899                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3900                      get_write_delay(csp));
3901                }
3902                else
3903 #endif /* def FEATURE_HTTPS_INSPECTION */
3904                {
3905                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3906                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3907                }
3908                free_http_request(http);
3909                mark_server_socket_tainted(csp);
3910 #ifdef FEATURE_HTTPS_INSPECTION
3911                close_client_and_server_ssl_connections(csp);
3912 #endif
3913                return;
3914             }
3915
3916             /*
3917              * Disable redirect checkers, so that they will be only run
3918              * again if the user also enables them through tags.
3919              *
3920              * From a performance point of view it doesn't matter,
3921              * but it prevents duplicated log messages.
3922              */
3923 #ifdef FEATURE_FAST_REDIRECTS
3924             csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3925 #endif
3926             csp->action->flags &= ~ACTION_REDIRECT;
3927
3928             /*
3929              * We have now received the entire server header,
3930              * filter it and send the result to the client
3931              */
3932             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3933             {
3934                log_error(LOG_LEVEL_CLF,
3935                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3936 #ifdef FEATURE_HTTPS_INSPECTION
3937                /*
3938                 * Sending data with standard or secured connection (HTTP/HTTPS)
3939                 */
3940                if (client_use_ssl(csp))
3941                {
3942                   ssl_send_data_delayed(&(csp->ssl_client_attr),
3943                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3944                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3945                      get_write_delay(csp));
3946                }
3947                else
3948 #endif
3949                {
3950                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3951                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3952                }
3953                free_http_request(http);
3954                mark_server_socket_tainted(csp);
3955 #ifdef FEATURE_HTTPS_INSPECTION
3956                close_client_and_server_ssl_connections(csp);
3957 #endif
3958                return;
3959             }
3960             hdr = list_to_text(csp->headers);
3961             if (hdr == NULL)
3962             {
3963                /* FIXME Should handle error properly */
3964                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3965             }
3966
3967             if ((csp->flags & CSP_FLAG_CHUNKED)
3968                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3969                && ((csp->iob->eod - csp->iob->cur) >= 5)
3970                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3971             {
3972                log_error(LOG_LEVEL_CONNECT,
3973                   "Looks like we got the last chunk together with "
3974                   "the server headers. We better stop reading.");
3975                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3976                csp->expected_content_length = byte_count;
3977                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3978             }
3979
3980             csp->server_connection.response_received = time(NULL);
3981
3982             if (crunch_response_triggered(csp, crunchers_light))
3983             {
3984                /*
3985                 * One of the tags created by a server-header
3986                 * tagger triggered a crunch. We already
3987                 * delivered the crunch response to the client
3988                 * and are done here after cleaning up.
3989                 */
3990                freez(hdr);
3991                mark_server_socket_tainted(csp);
3992 #ifdef FEATURE_HTTPS_INSPECTION
3993                close_client_and_server_ssl_connections(csp);
3994 #endif
3995                return;
3996             }
3997
3998             /* Buffer and pcrs filter this if appropriate. */
3999             buffer_and_filter_content = content_requires_filtering(csp);
4000
4001             if (!buffer_and_filter_content)
4002             {
4003                /*
4004                 * Write the server's (modified) header to
4005                 * the client (along with anything else that
4006                 * may be in the buffer). Use standard or secured
4007                 * connection.
4008                 */
4009 #ifdef FEATURE_HTTPS_INSPECTION
4010                if (client_use_ssl(csp))
4011                {
4012                   if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
4013                           (const unsigned char *)hdr, strlen(hdr),
4014                           get_write_delay(csp)) < 0)
4015                      || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4016                             csp->iob)) < 0))
4017                   {
4018                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
4019
4020                      /*
4021                       * The write failed, so don't bother mentioning it
4022                       * to the client... it probably can't hear us anyway.
4023                       */
4024                      freez(hdr);
4025                      mark_server_socket_tainted(csp);
4026 #ifdef FEATURE_HTTPS_INSPECTION
4027                      close_client_and_server_ssl_connections(csp);
4028 #endif
4029                      return;
4030                   }
4031                }
4032                else
4033 #endif /* def FEATURE_HTTPS_INSPECTION */
4034                {
4035                   if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4036                      || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4037                   {
4038                      log_error(LOG_LEVEL_ERROR,
4039                         "write header to client failed");
4040                      /*
4041                       * The write failed, so don't bother mentioning it
4042                       * to the client... it probably can't hear us anyway.
4043                       */
4044                      freez(hdr);
4045                      mark_server_socket_tainted(csp);
4046                      return;
4047                   }
4048                }
4049                                 }
4050
4051             /* we're finished with the server's header */
4052
4053             freez(hdr);
4054             server_body = 1;
4055
4056             /*
4057              * If this was a MS IIS/5 hack then it means the server
4058              * has already closed the connection. Nothing more to read.
4059              * Time to bail.
4060              */
4061             if (ms_iis5_hack)
4062             {
4063                log_error(LOG_LEVEL_ERROR,
4064                   "Closed server connection detected. "
4065                   "Applying the MS IIS5 hack didn't help.");
4066                log_error(LOG_LEVEL_CLF,
4067                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4068 #ifdef FEATURE_HTTPS_INSPECTION
4069                /*
4070                 * Sending data with standard or secured connection (HTTP/HTTPS)
4071                 */
4072                if (client_use_ssl(csp))
4073                {
4074                   ssl_send_data_delayed(&(csp->ssl_client_attr),
4075                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4076                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
4077                      get_write_delay(csp));
4078                }
4079                else
4080 #endif /* def FEATURE_HTTPS_INSPECTION */
4081                {
4082                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4083                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4084                }
4085                mark_server_socket_tainted(csp);
4086 #ifdef FEATURE_HTTPS_INSPECTION
4087                close_client_and_server_ssl_connections(csp);
4088 #endif
4089                return;
4090             }
4091          }
4092          continue;
4093       }
4094       mark_server_socket_tainted(csp);
4095 #ifdef FEATURE_HTTPS_INSPECTION
4096       close_client_and_server_ssl_connections(csp);
4097 #endif
4098       return; /* huh? we should never get here */
4099    }
4100
4101    if (csp->content_length == 0)
4102    {
4103       /*
4104        * If Privoxy didn't recalculate the Content-Length,
4105        * byte_count is still correct.
4106        */
4107       csp->content_length = byte_count;
4108    }
4109
4110 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4111    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4112       && (csp->expected_content_length != byte_count))
4113    {
4114       log_error(LOG_LEVEL_CONNECT,
4115          "Received %llu bytes while expecting %llu.",
4116          byte_count, csp->expected_content_length);
4117       mark_server_socket_tainted(csp);
4118    }
4119 #endif
4120
4121 #ifdef FEATURE_HTTPS_INSPECTION
4122    if (client_use_ssl(csp))
4123    {
4124       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4125          csp->ip_addr_str, http->gpc, http->hostport, http->path,
4126          http->version, csp->content_length);
4127    }
4128    else
4129 #endif
4130    {
4131       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4132          csp->ip_addr_str, http->ocmd, csp->content_length);
4133    }
4134    csp->server_connection.timestamp = time(NULL);
4135 }
4136
4137
4138 /*********************************************************************
4139  *
4140  * Function    :  chat
4141  *
4142  * Description :  Once a connection from the client has been accepted,
4143  *                this function is called (via serve()) to handle the
4144  *                main business of the communication.  This function
4145  *                returns after dealing with a single request. It can
4146  *                be called multiple times with the same client socket
4147  *                if the client is keeping the connection alive.
4148  *
4149  *                The decision whether or not a client connection will
4150  *                be kept alive is up to the caller which also must
4151  *                close the client socket when done.
4152  *
4153  *                FIXME: chat is nearly thousand lines long.
4154  *                Ridiculous.
4155  *
4156  * Parameters  :
4157  *          1  :  csp = Current client state (buffers, headers, etc...)
4158  *
4159  * Returns     :  Nothing.
4160  *
4161  *********************************************************************/
4162 static void chat(struct client_state *csp)
4163 {
4164    const struct forward_spec *fwd;
4165    struct http_request *http;
4166    /* Skeleton for HTTP response, if we should intercept the request */
4167    struct http_response *rsp;
4168 #ifdef FEATURE_HTTPS_INSPECTION
4169    int use_ssl_tunnel = 0;
4170 #endif
4171
4172    http = csp->http;
4173
4174    if (receive_client_request(csp) != JB_ERR_OK)
4175    {
4176       return;
4177    }
4178    if (parse_client_request(csp) != JB_ERR_OK)
4179    {
4180       return;
4181    }
4182
4183 #ifdef FEATURE_HTTPS_INSPECTION
4184    /*
4185     * Setting flags to use old solution with SSL tunnel and to disable
4186     * certificate verification.
4187     */
4188    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4189       && !cgi_page_requested(csp->http->host))
4190    {
4191       use_ssl_tunnel = 1;
4192    }
4193
4194    if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4195    {
4196       csp->dont_verify_certificate = 1;
4197    }
4198 #endif
4199
4200    /*
4201     * build the http request to send to the server
4202     * we have to do one of the following:
4203     *
4204     * create =    use the original HTTP request to create a new
4205     *             HTTP request that has either the path component
4206     *             without the http://domainspec (w/path) or the
4207     *             full orininal URL (w/url)
4208     *             Note that the path and/or the HTTP version may
4209     *             have been altered by now.
4210     *
4211     * SSL proxy = Open a socket to the host:port of the server
4212     *             and create TLS/SSL connection with server and
4213     *             with client. Then behave like mediator between
4214     *             client and server over TLS/SSL.
4215     *
4216     * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4217     *    with     request to a parent proxy. Note that we'll be sending
4218     * forwarding  the CFAIL message ourselves if connecting to the parent
4219     *             fails, but we won't send a CSUCCEED message if it works,
4220     *             since that would result in a double message (ours and the
4221     *             parent's). After sending the request to the parent, we
4222     *             must parse answer and send it to client. If connection
4223     *             with server is established, we do TLS/SSL proxy. Otherwise
4224     *             we send parent response to client and close connections.
4225     *
4226     * here's the matrix:
4227     *                        SSL
4228     *                    0        1
4229     *                +--------+--------+
4230     *                |        |        |
4231     *             0  | create |   SSL  |
4232     *                | w/path |  proxy |
4233     *  Forwarding    +--------+--------+
4234     *                |        |   SSL  |
4235     *             1  | create |  proxy |
4236     *                | w/url  |+forward|
4237     *                +--------+--------+
4238     *
4239     */
4240
4241 #ifdef FEATURE_HTTPS_INSPECTION
4242    /*
4243     * Presetting SSL client and server flags
4244     */
4245    if (http->ssl && !use_ssl_tunnel)
4246    {
4247       http->client_ssl = 1;
4248       http->server_ssl = 1;
4249    }
4250    else
4251    {
4252       http->client_ssl = 0;
4253       http->server_ssl = 0;
4254    }
4255 #endif
4256
4257 #ifdef FEATURE_HTTPS_INSPECTION
4258    /*
4259     * Log the request unless we're https inspecting
4260     * in which case we don't have the path yet and
4261     * will log the request later.
4262     */
4263    if (!client_use_ssl(csp))
4264 #endif
4265    {
4266       log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4267    }
4268
4269    if (http->ssl && connect_port_is_forbidden(csp))
4270    {
4271       const char *acceptable_connect_ports =
4272          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4273       assert(NULL != acceptable_connect_ports);
4274       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4275          "limit-connect{%s} doesn't allow CONNECT requests to %s",
4276          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4277       csp->action->flags |= ACTION_BLOCK;
4278       http->ssl = 0;
4279 #ifdef FEATURE_HTTPS_INSPECTION
4280       http->client_ssl = 0;
4281       http->server_ssl = 0;
4282 #endif
4283    }
4284
4285    /*
4286     * We have a request. Check if one of the crunchers wants it
4287     * unless the client wants to use TLS/SSL in which case we
4288     * haven't setup the TLS context yet and will send the crunch
4289     * response later.
4290     */
4291    if (
4292 #ifdef FEATURE_HTTPS_INSPECTION
4293        !client_use_ssl(csp) &&
4294 #endif
4295        crunch_response_triggered(csp, crunchers_all))
4296    {
4297       /*
4298        * Yes. The client got the crunch response and we're done here.
4299        */
4300       return;
4301    }
4302
4303 #ifdef FEATURE_HTTPS_INSPECTION
4304    if (client_use_ssl(csp) && !use_ssl_tunnel)
4305    {
4306       int ret;
4307       /*
4308        * Creating a SSL proxy.
4309        *
4310        * By sending the CSUCCEED message we're lying to the client as
4311        * the connection hasn't actually been established yet. We don't
4312        * establish the connection until we have seen and parsed the
4313        * encrypted client headers.
4314        */
4315       if (write_socket_delayed(csp->cfd, CSUCCEED,
4316             strlen(CSUCCEED), get_write_delay(csp)) != 0)
4317       {
4318          log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4319          return;
4320       }
4321
4322       ret = create_client_ssl_connection(csp);
4323       if (ret != 0)
4324       {
4325          log_error(LOG_LEVEL_ERROR,
4326             "Failed to open a secure connection with the client");
4327          return;
4328       }
4329       if (JB_ERR_OK != process_encrypted_request_headers(csp))
4330       {
4331          close_client_ssl_connection(csp);
4332          return;
4333       }
4334       /*
4335        * We have an encrypted request. Check if one of the crunchers now
4336        * wants it (for example because the previously invisible path was
4337        * required to match).
4338        */
4339       if (crunch_response_triggered(csp, crunchers_all))
4340       {
4341          /*
4342           * Yes. The client got the crunch response and we're done here.
4343           */
4344          return;
4345       }
4346    }
4347 #endif
4348
4349    log_applied_actions(csp->action);
4350
4351    /* decide how to route the HTTP request */
4352    fwd = forward_url(csp, http);
4353
4354    freez(csp->headers->first->str);
4355    build_request_line(csp, fwd, &csp->headers->first->str);
4356
4357    if (fwd->forward_host)
4358    {
4359       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4360          fwd->forward_host, fwd->forward_port, http->hostport);
4361    }
4362    else
4363    {
4364       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4365    }
4366
4367    /* here we connect to the server, gateway, or the forwarder */
4368
4369 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4370    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4371       && socket_is_still_alive(csp->server_connection.sfd)
4372       && connection_destination_matches(&csp->server_connection, http, fwd))
4373    {
4374       log_error(LOG_LEVEL_CONNECT,
4375          "Reusing server socket %d connected to %s. Total requests: %u.",
4376          csp->server_connection.sfd, csp->server_connection.host,
4377          csp->server_connection.requests_sent_total);
4378    }
4379    else
4380    {
4381       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4382       {
4383 #ifdef FEATURE_CONNECTION_SHARING
4384          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4385 #ifdef FEATURE_HTTPS_INSPECTION
4386             && !server_use_ssl(csp)
4387 #endif
4388             )
4389          {
4390             remember_connection(&csp->server_connection);
4391          }
4392          else
4393 #endif /* def FEATURE_CONNECTION_SHARING */
4394          {
4395             log_error(LOG_LEVEL_CONNECT,
4396                "Closing server socket %d connected to %s. Total requests: %u.",
4397                csp->server_connection.sfd, csp->server_connection.host,
4398                csp->server_connection.requests_sent_total);
4399             close_socket(csp->server_connection.sfd);
4400          }
4401          mark_connection_closed(&csp->server_connection);
4402       }
4403 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4404
4405       /*
4406        * Connecting to destination server
4407        */
4408       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4409
4410       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4411       {
4412          if (fwd->type != SOCKS_NONE)
4413          {
4414             /* Socks error. */
4415             rsp = error_response(csp, "forwarding-failed");
4416          }
4417          else if (errno == EINVAL)
4418          {
4419             rsp = error_response(csp, "no-such-domain");
4420          }
4421          else
4422          {
4423             rsp = error_response(csp, "connect-failed");
4424          }
4425
4426          /* Write the answer to the client */
4427          if (rsp != NULL)
4428          {
4429             send_crunch_response(csp, rsp);
4430          }
4431
4432          /*
4433           * Temporary workaround to prevent already-read client
4434           * bodies from being parsed as new requests. For now we
4435           * err on the safe side and throw all the following
4436           * requests under the bus, even if no client body has been
4437           * buffered. A compliant client will repeat the dropped
4438           * requests on an untainted connection.
4439           *
4440           * The proper fix is to discard the no longer needed
4441           * client body in the buffer (if there is one) and to
4442           * continue parsing the bytes that follow.
4443           */
4444 #ifdef FEATURE_HTTPS_INSPECTION
4445          close_client_ssl_connection(csp);
4446 #endif
4447          drain_and_close_socket(csp->cfd);
4448          csp->cfd = JB_INVALID_SOCKET;
4449
4450          return;
4451       }
4452
4453 #ifdef FEATURE_HTTPS_INSPECTION
4454       /*
4455        * Creating TLS/SSL connections with destination server or parent
4456        * proxy. If forwarding is enabled, we must send client request to
4457        * parent proxy and receive, parse and resend parent proxy answer.
4458        */
4459       if (http->ssl && !use_ssl_tunnel)
4460       {
4461          if (fwd->forward_host != NULL)
4462          {
4463             char server_response[BUFFER_SIZE];
4464             int ret = 0;
4465             int len = 0;
4466             char *hdr = list_to_text(csp->headers);
4467             memset(server_response, 0, sizeof(server_response));
4468
4469             if (hdr == NULL)
4470             {
4471                log_error(LOG_LEVEL_FATAL,
4472                   "Out of memory parsing client header");
4473             }
4474             list_remove_all(csp->headers);
4475
4476             /*
4477              * Sending client's CONNECT request to the parent proxy
4478              */
4479             ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4480
4481             freez(hdr);
4482
4483             if (ret != 0)
4484             {
4485                log_error(LOG_LEVEL_CONNECT,
4486                   "Sending request headers to: %s failed", http->hostport);
4487                mark_server_socket_tainted(csp);
4488                close_client_ssl_connection(csp);
4489                return;
4490             }
4491
4492             /* Waiting for parent proxy server response */
4493             len = read_socket(csp->server_connection.sfd, server_response,
4494                sizeof(server_response)-1);
4495
4496             if (len <= 0)
4497             {
4498                log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4499                   "server on socket %d.", csp->server_connection.sfd);
4500
4501                rsp = error_response(csp, "no-server-data");
4502                if (rsp)
4503                {
4504                   send_crunch_response(csp, rsp);
4505                }
4506                mark_server_socket_tainted(csp);
4507                close_client_ssl_connection(csp);
4508                return;
4509             }
4510
4511             /*
4512              * Test if the connection to the destination server was
4513              * established successfully by the parent proxy.
4514              */
4515             if (!tunnel_established_successfully(server_response, (unsigned int)len))
4516             {
4517                log_error(LOG_LEVEL_ERROR,
4518                   "The forwarder %s failed to establish a connection with %s",
4519                   fwd->forward_host, http->host);
4520                rsp = error_response(csp, "connect-failed");
4521                if (rsp)
4522                {
4523                   send_crunch_response(csp, rsp);
4524                }
4525                mark_server_socket_tainted(csp);
4526                close_client_ssl_connection(csp);
4527                return;
4528             }
4529          } /* -END- if (fwd->forward_host != NULL) */
4530
4531          /*
4532           * We can now create the TLS/SSL connection with the destination server.
4533           */
4534          int ret = create_server_ssl_connection(csp);
4535          if (ret != 0)
4536          {
4537             if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4538                 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4539             {
4540                /*
4541                 * If the server certificate is invalid, we must inform
4542                 * the client and then close connection to the client.
4543                 */
4544                ssl_send_certificate_error(csp);
4545                close_client_and_server_ssl_connections(csp);
4546                return;
4547             }
4548             if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4549              || csp->server_cert_verification_result == SSL_CERT_VALID)
4550             {
4551                /*
4552                 * The TLS/SSL connection wasn't created but an invalid
4553                 * certificate wasn't detected. Report it as connection
4554                 * failure.
4555                 */
4556                rsp = error_response(csp, "connect-failed");
4557                if (rsp)
4558                {
4559                   send_crunch_response(csp, rsp);
4560                }
4561                close_client_and_server_ssl_connections(csp);
4562                return;
4563             }
4564          }
4565       }/* -END- if (http->ssl) */
4566 #endif /* def FEATURE_HTTPS_INSPECTION */
4567
4568 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4569       save_connection_destination(csp->server_connection.sfd,
4570          http, fwd, &csp->server_connection);
4571       csp->server_connection.keep_alive_timeout =
4572          (unsigned)csp->config->keep_alive_timeout;
4573    }
4574 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4575
4576    csp->server_connection.requests_sent_total++;
4577
4578    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4579    {
4580       /* Client headers have been sent optimistically */
4581       assert(csp->headers->last == NULL);
4582    }
4583    else if (http->ssl == 0 || (fwd->forward_host
4584 #ifdef FEATURE_HTTPS_INSPECTION
4585          && use_ssl_tunnel
4586 #endif
4587            ))
4588    {
4589       if (send_http_request(csp))
4590       {
4591          rsp = error_response(csp, "connect-failed");
4592          if (rsp)
4593          {
4594             send_crunch_response(csp, rsp);
4595          }
4596          return;
4597       }
4598    }
4599    else
4600    {
4601       /*
4602        * Using old solution with SSL tunnel or new solution with SSL proxy
4603        */
4604       list_remove_all(csp->headers);
4605 #ifdef FEATURE_HTTPS_INSPECTION
4606       if (use_ssl_tunnel)
4607 #endif
4608       {
4609          /*
4610          * We're running an SSL tunnel and we're not forwarding,
4611          * so just ditch the client headers, send the "connect succeeded"
4612          * message to the client, flush the rest, and get out of the way.
4613          */
4614          if (write_socket_delayed(csp->cfd, CSUCCEED,
4615                strlen(CSUCCEED), get_write_delay(csp)))
4616          {
4617             return;
4618          }
4619       }
4620 #ifdef FEATURE_HTTPS_INSPECTION
4621       else
4622       {
4623          /*
4624           * If server certificate has been verified and is invalid,
4625           * we must inform the client and then close the connection
4626           * with client and server.
4627           */
4628          if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4629              csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4630          {
4631             ssl_send_certificate_error(csp);
4632             close_client_and_server_ssl_connections(csp);
4633             return;
4634          }
4635          if (send_https_request(csp))
4636          {
4637             rsp = error_response(csp, "connect-failed");
4638             if (rsp)
4639             {
4640                send_crunch_response(csp, rsp);
4641             }
4642             close_client_and_server_ssl_connections(csp);
4643             return;
4644          }
4645       }
4646 #endif /* def FEATURE_HTTPS_INSPECTION */
4647       clear_iob(csp->client_iob);
4648    }/* -END- else ... if (http->ssl == 1) */
4649
4650    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4651
4652    /* XXX: should the time start earlier for optimistically sent data? */
4653    csp->server_connection.request_sent = time(NULL);
4654
4655    handle_established_connection(csp);
4656    freez(csp->receive_buffer);
4657 }
4658
4659
4660 #ifdef FUZZ
4661 /*********************************************************************
4662  *
4663  * Function    :  fuzz_server_response
4664  *
4665  * Description :  Treat the input as a whole server response.
4666  *
4667  * Parameters  :
4668  *          1  :  csp = Current client state (buffers, headers, etc...)
4669  *          2  :  fuzz_input_file = File to read the input from.
4670  *
4671  * Returns     :  0
4672  *
4673  *********************************************************************/
4674 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4675 {
4676    static struct forward_spec fwd; /* Zero'd due to being static */
4677    csp->cfd = 0;
4678
4679    if (strcmp(fuzz_input_file, "-") == 0)
4680    {
4681       /* XXX: Doesn't work yet. */
4682       csp->server_connection.sfd = 0;
4683    }
4684    else
4685    {
4686       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4687       if (csp->server_connection.sfd == -1)
4688       {
4689          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4690             fuzz_input_file);
4691       }
4692    }
4693    csp->fwd = &fwd;
4694    csp->content_type |= CT_GIF;
4695    csp->action->flags |= ACTION_DEANIMATE;
4696    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4697
4698    csp->http->path = strdup_or_die("/");
4699    csp->http->host = strdup_or_die("fuzz.example.org");
4700    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4701    /* Prevent client socket monitoring */
4702    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4703    csp->flags |= CSP_FLAG_CHUNKED;
4704
4705    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4706    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4707
4708    csp->content_type |= CT_DECLARED|CT_GIF;
4709
4710    csp->config->socket_timeout = 0;
4711
4712    cgi_init_error_messages();
4713
4714    handle_established_connection(csp);
4715    freez(csp->receive_buffer);
4716
4717    return 0;
4718 }
4719 #endif
4720
4721
4722 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4723 /*********************************************************************
4724  *
4725  * Function    :  prepare_csp_for_next_request
4726  *
4727  * Description :  Put the csp in a mostly vergin state.
4728  *
4729  * Parameters  :
4730  *          1  :  csp = Current client state (buffers, headers, etc...)
4731  *
4732  * Returns     :  N/A
4733  *
4734  *********************************************************************/
4735 static void prepare_csp_for_next_request(struct client_state *csp)
4736 {
4737    csp->content_type = 0;
4738    csp->content_length = 0;
4739    csp->expected_content_length = 0;
4740    csp->expected_client_content_length = 0;
4741    list_remove_all(csp->headers);
4742    clear_iob(csp->iob);
4743    freez(csp->error_message);
4744    free_http_request(csp->http);
4745    destroy_list(csp->headers);
4746 #ifdef FEATURE_HTTPS_INSPECTION
4747    destroy_list(csp->https_headers);
4748 #endif
4749    destroy_list(csp->tags);
4750 #ifdef FEATURE_CLIENT_TAGS
4751    destroy_list(csp->client_tags);
4752    freez(csp->client_address);
4753 #endif
4754    free_current_action(csp->action);
4755    if (NULL != csp->fwd)
4756    {
4757       unload_forward_spec(csp->fwd);
4758       csp->fwd = NULL;
4759    }
4760    /* XXX: Store per-connection flags someplace else. */
4761    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4762 #ifdef FEATURE_TOGGLE
4763    if (global_toggle_state)
4764 #endif /* def FEATURE_TOGGLE */
4765    {
4766       csp->flags |= CSP_FLAG_TOGGLED_ON;
4767    }
4768
4769    if (csp->client_iob->eod > csp->client_iob->cur)
4770    {
4771       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4772       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4773
4774       assert(bytes_to_shift > 0);
4775       assert(data_length > 0);
4776
4777       log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4778          data_length, bytes_to_shift);
4779       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4780       csp->client_iob->cur = csp->client_iob->buf;
4781       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4782       csp->client_iob->eod = csp->client_iob->buf + data_length;
4783       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4784
4785       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4786    }
4787    else
4788    {
4789       /*
4790        * We mainly care about resetting client_iob->cur so we don't
4791        * waste buffer space at the beginning and don't mess up the
4792        * request restoration done by cgi_show_request().
4793        *
4794        * Freeing the buffer itself isn't technically necessary,
4795        * but makes debugging more convenient.
4796        */
4797       clear_iob(csp->client_iob);
4798    }
4799 }
4800 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4801
4802
4803 /*********************************************************************
4804  *
4805  * Function    :  serve
4806  *
4807  * Description :  This is little more than chat.  We only "serve" to
4808  *                to close (or remember) any socket that chat may have
4809  *                opened.
4810  *
4811  * Parameters  :
4812  *          1  :  csp = Current client state (buffers, headers, etc...)
4813  *
4814  * Returns     :  N/A
4815  *
4816  *********************************************************************/
4817 static void serve(struct client_state *csp)
4818 {
4819    int config_file_change_detected = 0; /* Only used for debugging */
4820 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4821 #ifdef FEATURE_CONNECTION_SHARING
4822    static int monitor_thread_running = 0;
4823 #endif /* def FEATURE_CONNECTION_SHARING */
4824    int continue_chatting = 0;
4825
4826    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4827       csp->ip_addr_str, csp->cfd);
4828
4829    do
4830    {
4831       unsigned int latency;
4832
4833 #ifdef FEATURE_HTTPS_INSPECTION
4834       if (continue_chatting && client_use_ssl(csp))
4835       {
4836          continue_https_chat(csp);
4837       }
4838       else
4839 #endif
4840       {
4841          chat(csp);
4842       }
4843
4844       /*
4845        * If the request has been crunched,
4846        * the calculated latency is zero.
4847        */
4848       latency = (unsigned)(csp->server_connection.response_received -
4849          csp->server_connection.request_sent) / 2;
4850
4851       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4852          && (csp->flags & CSP_FLAG_CRUNCHED)
4853          && (csp->expected_client_content_length != 0))
4854       {
4855          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4856          log_error(LOG_LEVEL_CONNECT,
4857             "Tainting client socket %d due to unread data.", csp->cfd);
4858       }
4859
4860       continue_chatting = (csp->config->feature_flags
4861          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4862          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4863          && (csp->cfd != JB_INVALID_SOCKET)
4864          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4865          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4866             || (csp->flags & CSP_FLAG_CHUNKED));
4867
4868       if (!(csp->flags & CSP_FLAG_CRUNCHED)
4869          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4870       {
4871          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4872          {
4873             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4874          }
4875          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4876             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4877             || !socket_is_still_alive(csp->server_connection.sfd)
4878             || !(latency < csp->server_connection.keep_alive_timeout))
4879          {
4880             log_error(LOG_LEVEL_CONNECT,
4881                "Closing server socket %d connected to %s. "
4882                "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4883                csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4884                csp->server_connection.host : csp->http->host,
4885                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4886                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4887                socket_is_still_alive(csp->server_connection.sfd),
4888                csp->server_connection.keep_alive_timeout);
4889 #ifdef FEATURE_CONNECTION_SHARING
4890             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4891             {
4892                forget_connection(csp->server_connection.sfd);
4893             }
4894 #endif /* def FEATURE_CONNECTION_SHARING */
4895 #ifdef FEATURE_HTTPS_INSPECTION
4896             close_server_ssl_connection(csp);
4897 #endif
4898             close_socket(csp->server_connection.sfd);
4899             mark_connection_closed(&csp->server_connection);
4900 #ifdef FEATURE_HTTPS_INSPECTION
4901             if (continue_chatting && client_use_ssl(csp))
4902             {
4903                /*
4904                 * Close the client socket as well as Privoxy currently
4905                 * can't establish a new server connection when the client
4906                 * socket is reused and would drop the connection in
4907                 * continue_https_chat() anyway.
4908                 */
4909                continue_chatting = 0;
4910                csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4911                log_error(LOG_LEVEL_CONNECT,
4912                   "Client socket %d is no longer usable. "
4913                   "The server socket has been closed.", csp->cfd);
4914             }
4915 #endif
4916          }
4917       }
4918
4919       if (continue_chatting && any_loaded_file_changed(csp))
4920       {
4921          continue_chatting = 0;
4922          config_file_change_detected = 1;
4923       }
4924 #ifdef FEATURE_HTTPS_INSPECTION
4925       if (continue_chatting && client_use_ssl(csp) &&
4926          csp->ssl_with_client_is_opened == 0)
4927       {
4928          continue_chatting = 0;
4929          log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4930             "The TLS session has been terminated.", csp->cfd);
4931       }
4932 #endif
4933
4934       if (continue_chatting)
4935       {
4936          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4937             && socket_is_still_alive(csp->cfd))
4938          {
4939             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4940                "pipelined on socket %d and the socket is still alive.",
4941                csp->requests_received_total+1, csp->cfd);
4942             prepare_csp_for_next_request(csp);
4943             continue;
4944          }
4945
4946          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4947          {
4948             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4949             {
4950                log_error(LOG_LEVEL_CONNECT,
4951                   "Waiting for the next client request on socket %d. "
4952                   "Keeping the server socket %d to %s open.",
4953                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4954             }
4955             else
4956             {
4957                log_error(LOG_LEVEL_CONNECT,
4958                   "Waiting for the next client request on socket %d. "
4959                   "No server socket to keep open.", csp->cfd);
4960             }
4961          }
4962
4963          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4964             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4965             && socket_is_still_alive(csp->cfd))
4966          {
4967             log_error(LOG_LEVEL_CONNECT,
4968                "Data arrived in time on client socket %d. Requests so far: %u",
4969                csp->cfd, csp->requests_received_total);
4970             prepare_csp_for_next_request(csp);
4971          }
4972          else
4973          {
4974 #ifdef FEATURE_CONNECTION_SHARING
4975             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4976                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4977                && (socket_is_still_alive(csp->server_connection.sfd))
4978 #ifdef FEATURE_HTTPS_INSPECTION
4979                && !server_use_ssl(csp)
4980 #endif
4981                 )
4982             {
4983                time_t time_open = time(NULL) - csp->server_connection.timestamp;
4984
4985                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4986                {
4987                   break;
4988                }
4989
4990                remember_connection(&csp->server_connection);
4991                csp->server_connection.sfd = JB_INVALID_SOCKET;
4992                drain_and_close_socket(csp->cfd);
4993                csp->cfd = JB_INVALID_SOCKET;
4994                privoxy_mutex_lock(&connection_reuse_mutex);
4995                if (!monitor_thread_running)
4996                {
4997                   monitor_thread_running = 1;
4998                   privoxy_mutex_unlock(&connection_reuse_mutex);
4999                   wait_for_alive_connections();
5000                   privoxy_mutex_lock(&connection_reuse_mutex);
5001                   monitor_thread_running = 0;
5002                }
5003                privoxy_mutex_unlock(&connection_reuse_mutex);
5004             }
5005 #endif /* def FEATURE_CONNECTION_SHARING */
5006             break;
5007          }
5008       }
5009       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5010       {
5011          log_error(LOG_LEVEL_CONNECT,
5012             "Closing server socket %d connected to %s. Keep-alive: %u. "
5013             "Tainted: %u. Socket alive: %u. Timeout: %u. "
5014             "Configuration file change detected: %u",
5015             csp->server_connection.sfd, csp->server_connection.host,
5016             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5017             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5018             socket_is_still_alive(csp->server_connection.sfd),
5019             csp->server_connection.keep_alive_timeout,
5020             config_file_change_detected);
5021       }
5022    } while (continue_chatting);
5023
5024 #else
5025    chat(csp);
5026 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5027
5028    if (csp->cfd != JB_INVALID_SOCKET)
5029    {
5030       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5031          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5032          "Configuration file change detected: %u. Requests received: %u.",
5033          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5034          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5035          config_file_change_detected, csp->requests_received_total);
5036 #ifdef FEATURE_HTTPS_INSPECTION
5037       close_client_ssl_connection(csp);
5038 #endif
5039       drain_and_close_socket(csp->cfd);
5040    }
5041
5042    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5043    {
5044 #ifdef FEATURE_CONNECTION_SHARING
5045       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5046       {
5047          forget_connection(csp->server_connection.sfd);
5048       }
5049 #endif /* def FEATURE_CONNECTION_SHARING */
5050
5051 #ifdef FEATURE_HTTPS_INSPECTION
5052       close_server_ssl_connection(csp);
5053 #endif /* def FEATURE_HTTPS_INSPECTION */
5054
5055       close_socket(csp->server_connection.sfd);
5056    }
5057
5058 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5059    mark_connection_closed(&csp->server_connection);
5060 #endif
5061
5062    free_csp_resources(csp);
5063
5064    csp->flags &= ~CSP_FLAG_ACTIVE;
5065
5066 }
5067
5068
5069 #ifdef __BEOS__
5070 /*********************************************************************
5071  *
5072  * Function    :  server_thread
5073  *
5074  * Description :  We only exist to call `serve' in a threaded environment.
5075  *
5076  * Parameters  :
5077  *          1  :  data = Current client state (buffers, headers, etc...)
5078  *
5079  * Returns     :  Always 0.
5080  *
5081  *********************************************************************/
5082 static int32 server_thread(void *data)
5083 {
5084    serve((struct client_state *) data);
5085    return 0;
5086
5087 }
5088 #endif
5089
5090
5091 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5092 /*********************************************************************
5093  *
5094  * Function    :  usage
5095  *
5096  * Description :  Print usage info & exit.
5097  *
5098  * Parameters  :  Pointer to argv[0] for identifying ourselves
5099  *
5100  * Returns     :  No. ,-)
5101  *
5102  *********************************************************************/
5103 static void usage(const char *name)
5104 {
5105    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5106           "Usage: %s [--config-test] "
5107 #if defined(unix)
5108           "[--chroot] "
5109 #endif /* defined(unix) */
5110           "[--help] "
5111 #if defined(unix)
5112           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5113 #endif /* defined(unix) */
5114          "[--version] [configfile]\n",
5115           name);
5116
5117 #ifdef FUZZ
5118    show_fuzz_usage(name);
5119 #endif
5120
5121    printf("Aborting\n");
5122
5123    exit(2);
5124
5125 }
5126 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5127
5128
5129 #ifdef MUTEX_LOCKS_AVAILABLE
5130 /*********************************************************************
5131  *
5132  * Function    :  privoxy_mutex_lock
5133  *
5134  * Description :  Locks a mutex.
5135  *
5136  * Parameters  :
5137  *          1  :  mutex = The mutex to lock.
5138  *
5139  * Returns     :  Void. May exit in case of errors.
5140  *
5141  *********************************************************************/
5142 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5143 {
5144 #ifdef FEATURE_PTHREAD
5145    int err = pthread_mutex_lock(mutex);
5146    if (err)
5147    {
5148       if (mutex != &log_mutex)
5149       {
5150          log_error(LOG_LEVEL_FATAL,
5151             "Mutex locking failed: %s.\n", strerror(err));
5152       }
5153       exit(1);
5154    }
5155 #else
5156    EnterCriticalSection(mutex);
5157 #endif /* def FEATURE_PTHREAD */
5158 }
5159
5160
5161 /*********************************************************************
5162  *
5163  * Function    :  privoxy_mutex_unlock
5164  *
5165  * Description :  Unlocks a mutex.
5166  *
5167  * Parameters  :
5168  *          1  :  mutex = The mutex to unlock.
5169  *
5170  * Returns     :  Void. May exit in case of errors.
5171  *
5172  *********************************************************************/
5173 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5174 {
5175 #ifdef FEATURE_PTHREAD
5176    int err = pthread_mutex_unlock(mutex);
5177    if (err)
5178    {
5179       if (mutex != &log_mutex)
5180       {
5181          log_error(LOG_LEVEL_FATAL,
5182             "Mutex unlocking failed: %s.\n", strerror(err));
5183       }
5184       exit(1);
5185    }
5186 #else
5187    LeaveCriticalSection(mutex);
5188 #endif /* def FEATURE_PTHREAD */
5189 }
5190
5191
5192 /*********************************************************************
5193  *
5194  * Function    :  privoxy_mutex_init
5195  *
5196  * Description :  Prepares a mutex.
5197  *
5198  * Parameters  :
5199  *          1  :  mutex = The mutex to initialize.
5200  *
5201  * Returns     :  Void. May exit in case of errors.
5202  *
5203  *********************************************************************/
5204 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5205 {
5206 #ifdef FEATURE_PTHREAD
5207    int err = pthread_mutex_init(mutex, 0);
5208    if (err)
5209    {
5210       printf("Fatal error. Mutex initialization failed: %s.\n",
5211          strerror(err));
5212       exit(1);
5213    }
5214 #else
5215    InitializeCriticalSection(mutex);
5216 #endif /* def FEATURE_PTHREAD */
5217 }
5218 #endif /* def MUTEX_LOCKS_AVAILABLE */
5219
5220 /*********************************************************************
5221  *
5222  * Function    :  initialize_mutexes
5223  *
5224  * Description :  Prepares mutexes if mutex support is available.
5225  *
5226  * Parameters  :  None
5227  *
5228  * Returns     :  Void, exits in case of errors.
5229  *
5230  *********************************************************************/
5231 static void initialize_mutexes(void)
5232 {
5233 #ifdef MUTEX_LOCKS_AVAILABLE
5234    /*
5235     * Prepare global mutex semaphores
5236     */
5237
5238 #ifdef FEATURE_HTTPS_INSPECTION
5239    privoxy_mutex_init(&certificate_mutex);
5240    privoxy_mutex_init(&ssl_init_mutex);
5241 #endif
5242
5243    privoxy_mutex_init(&log_mutex);
5244    privoxy_mutex_init(&log_init_mutex);
5245    privoxy_mutex_init(&connection_reuse_mutex);
5246 #ifdef FEATURE_EXTERNAL_FILTERS
5247    privoxy_mutex_init(&external_filter_mutex);
5248 #endif
5249 #ifdef FEATURE_CLIENT_TAGS
5250    privoxy_mutex_init(&client_tags_mutex);
5251 #endif
5252 #ifdef FEATURE_EXTENDED_STATISTICS
5253    privoxy_mutex_init(&filter_statistics_mutex);
5254    privoxy_mutex_init(&block_statistics_mutex);
5255 #endif
5256
5257    /*
5258     * XXX: The assumptions below are a bit naive
5259     * and can cause locks that aren't necessary.
5260     *
5261     * For example older FreeBSD versions (< 6.x?)
5262     * have no gethostbyname_r, but gethostbyname is
5263     * thread safe.
5264     */
5265 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5266    privoxy_mutex_init(&resolver_mutex);
5267 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5268    /*
5269     * XXX: should we use a single mutex for
5270     * localtime() and gmtime() as well?
5271     */
5272 #ifndef HAVE_GMTIME_R
5273    privoxy_mutex_init(&gmtime_mutex);
5274 #endif /* ndef HAVE_GMTIME_R */
5275
5276 #ifndef HAVE_LOCALTIME_R
5277    privoxy_mutex_init(&localtime_mutex);
5278 #endif /* ndef HAVE_GMTIME_R */
5279
5280 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5281    privoxy_mutex_init(&rand_mutex);
5282 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5283
5284 #endif /* def MUTEX_LOCKS_AVAILABLE */
5285 }
5286
5287 /*********************************************************************
5288  *
5289  * Function    :  main
5290  *
5291  * Description :  Load the config file and start the listen loop.
5292  *                This function is a lot more *sane* with the `load_config'
5293  *                and `listen_loop' functions; although it stills does
5294  *                a *little* too much for my taste.
5295  *
5296  * Parameters  :
5297  *          1  :  argc = Number of parameters (including $0).
5298  *          2  :  argv = Array of (char *)'s to the parameters.
5299  *
5300  * Returns     :  1 if : can't open config file, unrecognized directive,
5301  *                stats requested in multi-thread mode, can't open the
5302  *                log file, can't open the jar file, listen port is invalid,
5303  *                any load fails, and can't bind port.
5304  *
5305  *                Else main never returns, the process must be signaled
5306  *                to terminate execution.  Or, on Windows, use the
5307  *                "File", "Exit" menu option.
5308  *
5309  *********************************************************************/
5310 #ifdef __MINGW32__
5311 int real_main(int argc, char **argv)
5312 #else
5313 int main(int argc, char **argv)
5314 #endif
5315 {
5316    int argc_pos = 0;
5317    int do_config_test = 0;
5318 #ifndef HAVE_ARC4RANDOM
5319    unsigned int random_seed;
5320 #endif
5321 #ifdef unix
5322    struct passwd *pw = NULL;
5323    struct group *grp = NULL;
5324    int do_chroot = 0;
5325    char *pre_chroot_nslookup_to_load_resolver = NULL;
5326 #endif
5327 #ifdef FUZZ
5328    char *fuzz_input_type = NULL;
5329    char *fuzz_input_file = NULL;
5330 #endif
5331
5332    Argc = argc;
5333    Argv = argv;
5334
5335    configfile =
5336 #if !defined(_WIN32)
5337    "config"
5338 #else
5339    "config.txt"
5340 #endif
5341       ;
5342
5343    /* Prepare mutexes if supported and necessary. */
5344    initialize_mutexes();
5345
5346    /* Enable logging until further notice. */
5347    init_log_module();
5348
5349    /*
5350     * Parse the command line arguments
5351     *
5352     * XXX: simply printing usage information in case of
5353     * invalid arguments isn't particularly user friendly.
5354     */
5355    while (++argc_pos < argc)
5356    {
5357 #ifdef _WIN32
5358       /* Check to see if the service must be installed or uninstalled */
5359       if (strncmp(argv[argc_pos], "--install", 9) == 0)
5360       {
5361          const char *pName = argv[argc_pos] + 9;
5362          if (*pName == ':')
5363             pName++;
5364          exit((install_service(pName)) ? 0 : 1);
5365       }
5366       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5367       {
5368          const char *pName = argv[argc_pos] + 11;
5369          if (*pName == ':')
5370             pName++;
5371          exit((uninstall_service(pName)) ? 0 : 1);
5372       }
5373       else if (strcmp(argv[argc_pos], "--service") == 0)
5374       {
5375          bRunAsService = TRUE;
5376          w32_set_service_cwd();
5377          atexit(w32_service_exit_notify);
5378       }
5379       else
5380 #endif /* defined(_WIN32) */
5381
5382
5383 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5384
5385       if (strcmp(argv[argc_pos], "--help") == 0)
5386       {
5387          usage(argv[0]);
5388       }
5389
5390       else if (strcmp(argv[argc_pos], "--version") == 0)
5391       {
5392          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5393          exit(0);
5394       }
5395
5396 #if defined(unix)
5397
5398       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5399       {
5400          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5401          daemon_mode = 0;
5402       }
5403
5404       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5405       {
5406          if (++argc_pos == argc) usage(argv[0]);
5407          pidfile = strdup_or_die(argv[argc_pos]);
5408       }
5409
5410       else if (strcmp(argv[argc_pos], "--user") == 0)
5411       {
5412          char *user_arg;
5413          char *group_name;
5414
5415          if (++argc_pos == argc) usage(argv[argc_pos]);
5416
5417          user_arg = strdup_or_die(argv[argc_pos]);
5418          group_name = strchr(user_arg, '.');
5419          if (NULL != group_name)
5420          {
5421             /* Nul-terminate the user name */
5422             *group_name = '\0';
5423
5424             /* Skip the former delimiter to actually reach the group name */
5425             group_name++;
5426
5427             grp = getgrnam(group_name);
5428             if (NULL == grp)
5429             {
5430                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5431             }
5432          }
5433          pw = getpwnam(user_arg);
5434          if (NULL == pw)
5435          {
5436             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5437          }
5438
5439          freez(user_arg);
5440       }
5441
5442       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5443       {
5444          if (++argc_pos == argc) usage(argv[0]);
5445          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5446       }
5447
5448       else if (strcmp(argv[argc_pos], "--chroot") == 0)
5449       {
5450          do_chroot = 1;
5451       }
5452 #endif /* defined(unix) */
5453
5454       else if (strcmp(argv[argc_pos], "--config-test") == 0)
5455       {
5456          do_config_test = 1;
5457       }
5458 #ifdef FUZZ
5459       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5460       {
5461          argc_pos++;
5462          if (argc < argc_pos + 2) usage(argv[0]);
5463          fuzz_input_type = argv[argc_pos];
5464          argc_pos++;
5465          fuzz_input_file = argv[argc_pos];
5466       }
5467       else if (strcmp(argv[argc_pos], "--stfu") == 0)
5468       {
5469          set_debug_level(LOG_LEVEL_STFU);
5470       }
5471 #endif
5472       else if (argc_pos + 1 != argc)
5473       {
5474          /*
5475           * This is neither the last command line
5476           * option, nor was it recognized before,
5477           * therefore it must be invalid.
5478           */
5479          usage(argv[0]);
5480       }
5481       else
5482
5483 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5484       {
5485          configfile = argv[argc_pos];
5486       }
5487
5488    } /* -END- while (more arguments) */
5489
5490    show_version(Argv[0]);
5491
5492 #if defined(unix)
5493    if (*configfile != '/')
5494    {
5495       char cwd[BUFFER_SIZE];
5496       char *abs_file;
5497       size_t abs_file_size;
5498
5499       /* make config-filename absolute here */
5500       if (NULL == getcwd(cwd, sizeof(cwd)))
5501       {
5502          perror("failed to get current working directory");
5503          exit(1);
5504       }
5505
5506       basedir = strdup_or_die(cwd);
5507       /* XXX: why + 5? */
5508       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5509       abs_file = malloc_or_die(abs_file_size);
5510       strlcpy(abs_file, basedir, abs_file_size);
5511       strlcat(abs_file, "/", abs_file_size);
5512       strlcat(abs_file, configfile, abs_file_size);
5513       configfile = abs_file;
5514    }
5515 #endif /* defined unix */
5516
5517
5518    files->next = NULL;
5519    clients->next = NULL;
5520
5521    /* XXX: factor out initialising after the next stable release. */
5522 #ifdef _WIN32
5523    InitWin32();
5524 #endif
5525
5526 #ifndef HAVE_ARC4RANDOM
5527    random_seed = (unsigned int)time(NULL);
5528 #ifdef HAVE_RANDOM
5529    srandom(random_seed);
5530 #else
5531    srand(random_seed);
5532 #endif /* ifdef HAVE_RANDOM */
5533 #endif /* ifndef HAVE_ARC4RANDOM */
5534
5535    /*
5536     * Unix signal handling
5537     *
5538     * Catch the abort, interrupt and terminate signals for a graceful exit
5539     * Catch the hangup signal so the errlog can be reopened.
5540     *
5541     * Ignore the broken pipe signal as connection failures
5542     * are handled when and where they occur without relying
5543     * on a signal.
5544     */
5545 #if !defined(_WIN32)
5546 {
5547    int idx;
5548    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5549
5550    for (idx = 0; idx < SZ(catched_signals); idx++)
5551    {
5552 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5553       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5554 #else
5555       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5556 #endif /* ifdef sun */
5557       {
5558          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5559       }
5560    }
5561
5562    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5563    {
5564       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5565    }
5566
5567 }
5568 #else /* ifdef _WIN32 */
5569 # ifdef _WIN_CONSOLE
5570    /*
5571     * We *are* in a windows console app.
5572     * Print a verbose messages about FAQ's and such
5573     */
5574    printf("%s", win32_blurb);
5575 # endif /* def _WIN_CONSOLE */
5576 #endif /* def _WIN32 */
5577
5578 #ifdef FUZZ
5579    if (fuzz_input_type != NULL)
5580    {
5581       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5582    }
5583    log_error(LOG_LEVEL_FATAL,
5584       "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5585       "Various data structures are static which is unsafe when using threads.");
5586 #endif
5587
5588    if (do_config_test)
5589    {
5590       exit(NULL == load_config());
5591    }
5592
5593    /* Initialize the CGI subsystem */
5594    cgi_init_error_messages();
5595
5596    /*
5597     * If running on unix and without the --no-daemon
5598     * option, become a daemon. I.e. fork, detach
5599     * from tty and get process group leadership
5600     */
5601 #if defined(unix)
5602 {
5603    if (daemon_mode)
5604    {
5605       int fd;
5606       pid_t pid = fork();
5607
5608       if (pid < 0) /* error */
5609       {
5610          perror("fork");
5611          exit(3);
5612       }
5613       else if (pid != 0) /* parent */
5614       {
5615          int status;
5616          pid_t wpid;
5617          /*
5618           * must check for errors
5619           * child died due to missing files aso
5620           */
5621          sleep(1);
5622          wpid = waitpid(pid, &status, WNOHANG);
5623          if (wpid != 0)
5624          {
5625             exit(1);
5626          }
5627          exit(0);
5628       }
5629       /* child */
5630
5631       setsid();
5632
5633       /*
5634        * stderr (fd 2) will be closed later on,
5635        * when the config file has been parsed.
5636        */
5637       close(0);
5638       close(1);
5639
5640       /*
5641        * Reserve fd 0 and 1 to prevent abort() and friends
5642        * from sending stuff to the clients or servers.
5643        */
5644       fd = open("/dev/null", O_RDONLY);
5645       if (fd == -1)
5646       {
5647          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5648       }
5649       else if (fd != 0)
5650       {
5651          if (dup2(fd, 0) == -1)
5652          {
5653             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5654          }
5655          close(fd);
5656       }
5657       fd = open("/dev/null", O_WRONLY);
5658       if (fd == -1)
5659       {
5660          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5661       }
5662       else if (fd != 1)
5663       {
5664          if (dup2(fd, 1) == -1)
5665          {
5666             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5667          }
5668          close(fd);
5669       }
5670
5671 #ifdef FEATURE_EXTERNAL_FILTERS
5672       for (fd = 0; fd < 3; fd++)
5673       {
5674          mark_socket_for_close_on_execute(fd);
5675       }
5676 #endif
5677
5678       if (chdir("/") != 0)
5679       {
5680          log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5681       }
5682
5683    } /* -END- if (daemon_mode) */
5684
5685    /*
5686     * As soon as we have written the PID file, we can switch
5687     * to the user and group ID indicated by the --user option
5688     */
5689    if (pidfile != NULL)
5690    {
5691       write_pid_file(pidfile);
5692    }
5693    if (NULL != pw)
5694    {
5695       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5696       {
5697          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5698       }
5699       if (NULL != grp)
5700       {
5701          if (setgroups(1, &grp->gr_gid))
5702          {
5703             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5704          }
5705       }
5706       else if (initgroups(pw->pw_name, pw->pw_gid))
5707       {
5708          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5709       }
5710       if (do_chroot)
5711       {
5712          if (!pw->pw_dir)
5713          {
5714             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5715          }
5716          /* Read the time zone file from /etc before doing chroot. */
5717          tzset();
5718          if (NULL != pre_chroot_nslookup_to_load_resolver
5719              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5720          {
5721             /* Initialize resolver library. */
5722             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5723          }
5724          if (chroot(pw->pw_dir) < 0)
5725          {
5726             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5727          }
5728          if (chdir ("/"))
5729          {
5730             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5731          }
5732       }
5733       if (setuid(pw->pw_uid))
5734       {
5735          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5736       }
5737       if (do_chroot)
5738       {
5739          char putenv_dummy[64];
5740
5741          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5742          if (putenv(putenv_dummy) != 0)
5743          {
5744             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5745          }
5746
5747          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5748          if (putenv(putenv_dummy) != 0)
5749          {
5750             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5751          }
5752       }
5753    }
5754    else if (do_chroot)
5755    {
5756       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5757    }
5758 }
5759 #endif /* defined unix */
5760
5761 #ifdef _WIN32
5762    /* This will be FALSE unless the command line specified --service
5763     */
5764    if (bRunAsService)
5765    {
5766       /* Yup, so now we must attempt to establish a connection
5767        * with the service dispatcher. This will only work if this
5768        * process was launched by the service control manager to
5769        * actually run as a service. If this isn't the case, i've
5770        * known it take around 30 seconds or so for the call to return.
5771        */
5772
5773       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5774       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5775       {
5776          /* Service has run, and at this point is now being stopped, so just return */
5777          return 0;
5778       }
5779
5780 #ifdef _WIN_CONSOLE
5781       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5782 #endif
5783       /* An error occurred. Usually it's because --service was wrongly specified
5784        * and we were unable to connect to the Service Control Dispatcher because
5785        * it wasn't expecting us and is therefore not listening.
5786        *
5787        * For now, just continue below to call the listen_loop function.
5788        */
5789    }
5790 #endif /* def _WIN32 */
5791
5792    listen_loop();
5793
5794    /* NOTREACHED */
5795    return(-1);
5796
5797 }
5798
5799
5800 /*********************************************************************
5801  *
5802  * Function    :  bind_port_helper
5803  *
5804  * Description :  Bind the listen port.  Handles logging, and aborts
5805  *                on failure.
5806  *
5807  * Parameters  :
5808  *          1  :  haddr = Host address to bind to. Use NULL to bind to
5809  *                        INADDR_ANY.
5810  *          2  :  hport = Specifies port to bind to.
5811  *          3  :  backlog = Listen backlog.
5812  *
5813  * Returns     :  Port that was opened.
5814  *
5815  *********************************************************************/
5816 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5817 {
5818    int result;
5819    jb_socket bfd;
5820
5821    result = bind_port(haddr, hport, backlog, &bfd);
5822
5823    if (result < 0)
5824    {
5825       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5826       switch(result)
5827       {
5828          case -3:
5829             log_error(LOG_LEVEL_FATAL,
5830                "can't bind to %s:%d: There may be another Privoxy "
5831                "or some other proxy running on port %d",
5832                bind_address, hport, hport);
5833             exit(-1);
5834
5835          case -2:
5836             log_error(LOG_LEVEL_FATAL,
5837                "can't bind to %s:%d: The hostname is not resolvable",
5838                bind_address, hport);
5839             exit(-1);
5840
5841          default:
5842             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5843                bind_address, hport);
5844             exit(-1);
5845       }
5846
5847       /* shouldn't get here */
5848       return JB_INVALID_SOCKET;
5849    }
5850
5851 #ifndef HAVE_POLL
5852 #ifndef _WIN32
5853    if (bfd >= FD_SETSIZE)
5854    {
5855       log_error(LOG_LEVEL_FATAL,
5856          "Bind socket number too high to use select(): %d >= %d",
5857          bfd, FD_SETSIZE);
5858    }
5859 #endif
5860 #endif
5861
5862    if (haddr == NULL)
5863    {
5864       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5865          hport);
5866    }
5867    else
5868    {
5869       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5870          hport, haddr);
5871    }
5872
5873    return bfd;
5874 }
5875
5876
5877 /*********************************************************************
5878  *
5879  * Function    :  bind_ports_helper
5880  *
5881  * Description :  Bind the listen ports.  Handles logging, and aborts
5882  *                on failure.
5883  *
5884  * Parameters  :
5885  *          1  :  config = Privoxy configuration.  Specifies ports
5886  *                         to bind to.
5887  *          2  :  sockets = Preallocated array of opened sockets
5888  *                          corresponding to specification in config.
5889  *                          All non-opened sockets will be set to
5890  *                          JB_INVALID_SOCKET.
5891  *
5892  * Returns     :  Nothing. Inspect sockets argument.
5893  *
5894  *********************************************************************/
5895 static void bind_ports_helper(struct configuration_spec * config,
5896                               jb_socket sockets[])
5897 {
5898    int i;
5899
5900    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5901    {
5902       if (config->hport[i])
5903       {
5904          sockets[i] = bind_port_helper(config->haddr[i],
5905             config->hport[i], config->listen_backlog);
5906 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5907          if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5908          {
5909             struct accept_filter_arg af_options;
5910             bzero(&af_options, sizeof(af_options));
5911             strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5912             if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5913                   sizeof(af_options)))
5914             {
5915                log_error(LOG_LEVEL_ERROR,
5916                   "Enabling accept filter for socket %d failed: %E", sockets[i]);
5917             }
5918          }
5919 #endif
5920       }
5921       else
5922       {
5923          sockets[i] = JB_INVALID_SOCKET;
5924       }
5925    }
5926    config->need_bind = 0;
5927 }
5928
5929
5930 /*********************************************************************
5931  *
5932  * Function    :  close_ports_helper
5933  *
5934  * Description :  Close listenings ports.
5935  *
5936  * Parameters  :
5937  *          1  :  sockets = Array of opened and non-opened sockets to
5938  *                          close. All sockets will be set to
5939  *                          JB_INVALID_SOCKET.
5940  *
5941  * Returns     :  Nothing.
5942  *
5943  *********************************************************************/
5944 static void close_ports_helper(jb_socket sockets[])
5945 {
5946    int i;
5947
5948    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5949    {
5950       if (JB_INVALID_SOCKET != sockets[i])
5951       {
5952          close_socket(sockets[i]);
5953       }
5954       sockets[i] = JB_INVALID_SOCKET;
5955    }
5956 }
5957
5958
5959 #ifdef _WIN32
5960 /* Without this simple workaround we get this compiler warning from _beginthread
5961  *     warning C4028: formal parameter 1 different from declaration
5962  */
5963 void w32_service_listen_loop(void *p)
5964 {
5965    listen_loop();
5966 }
5967 #endif /* def _WIN32 */
5968
5969
5970 /*********************************************************************
5971  *
5972  * Function    :  listen_loop
5973  *
5974  * Description :  bind the listen port and enter a "FOREVER" listening loop.
5975  *
5976  * Parameters  :  N/A
5977  *
5978  * Returns     :  Never.
5979  *
5980  *********************************************************************/
5981 static void listen_loop(void)
5982 {
5983    struct client_states *csp_list = NULL;
5984    struct client_state *csp = NULL;
5985    jb_socket bfds[MAX_LISTENING_SOCKETS];
5986    struct configuration_spec *config;
5987    unsigned int active_threads = 0;
5988 #if defined(FEATURE_PTHREAD)
5989    pthread_attr_t attrs;
5990
5991    pthread_attr_init(&attrs);
5992    pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5993 #endif
5994
5995    config = load_config();
5996
5997 #ifdef FEATURE_CONNECTION_SHARING
5998    /*
5999     * XXX: Should be relocated once it no
6000     * longer needs to emit log messages.
6001     */
6002    initialize_reusable_connections();
6003 #endif /* def FEATURE_CONNECTION_SHARING */
6004
6005    bind_ports_helper(config, bfds);
6006
6007 #ifdef FEATURE_GRACEFUL_TERMINATION
6008    while (!g_terminate)
6009 #else
6010    for (;;)
6011 #endif
6012    {
6013 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6014       while (waitpid(-1, NULL, WNOHANG) > 0)
6015       {
6016          /* zombie children */
6017       }
6018 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6019
6020       /*
6021        * Free data that was used by died threads
6022        */
6023       active_threads = sweep();
6024
6025 #if defined(unix)
6026       /*
6027        * Re-open the errlog after HUP signal
6028        */
6029       if (received_hup_signal)
6030       {
6031          if (NULL != config->logfile)
6032          {
6033             init_error_log(Argv[0], config->logfile);
6034          }
6035          received_hup_signal = 0;
6036       }
6037 #endif
6038
6039       csp_list = zalloc_or_die(sizeof(*csp_list));
6040       csp = &csp_list->csp;
6041
6042       log_error(LOG_LEVEL_CONNECT,
6043          "Waiting for the next client connection. Currently active threads: %u",
6044          active_threads);
6045
6046       /*
6047        * This config may be outdated, but for accept_connection()
6048        * it's fresh enough.
6049        */
6050       csp->config = config;
6051
6052       if (!accept_connection(csp, bfds))
6053       {
6054          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6055          freez(csp_list);
6056          continue;
6057       }
6058
6059       csp->flags |= CSP_FLAG_ACTIVE;
6060       csp->server_connection.sfd = JB_INVALID_SOCKET;
6061
6062       csp->config = config = load_config();
6063
6064       if (config->need_bind)
6065       {
6066          /*
6067           * Since we were listening to the "old port", we will not see
6068           * a "listen" param change until the next request.  So, at
6069           * least 1 more request must be made for us to find the new
6070           * setting.  I am simply closing the old socket and binding the
6071           * new one.
6072           *
6073           * Which-ever is correct, we will serve 1 more page via the
6074           * old settings.  This should probably be a "show-status"
6075           * request.  This should not be a so common of an operation
6076           * that this will hurt people's feelings.
6077           */
6078
6079          close_ports_helper(bfds);
6080
6081          bind_ports_helper(config, bfds);
6082       }
6083
6084 #ifdef FEATURE_TOGGLE
6085       if (global_toggle_state)
6086 #endif /* def FEATURE_TOGGLE */
6087       {
6088          csp->flags |= CSP_FLAG_TOGGLED_ON;
6089       }
6090
6091       if (run_loader(csp))
6092       {
6093          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6094          /* Never get here - LOG_LEVEL_FATAL causes program exit */
6095       }
6096
6097 #ifdef FEATURE_ACL
6098       if (block_acl(NULL,csp))
6099       {
6100          log_error(LOG_LEVEL_CONNECT,
6101             "Connection from %s on %s (socket %d) dropped due to ACL",
6102             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6103          close_socket(csp->cfd);
6104          freez(csp->ip_addr_str);
6105          freez(csp->listen_addr_str);
6106          freez(csp_list);
6107          continue;
6108       }
6109 #endif /* def FEATURE_ACL */
6110
6111       if ((0 != config->max_client_connections)
6112          && (active_threads >= config->max_client_connections))
6113       {
6114          log_error(LOG_LEVEL_ERROR,
6115             "Rejecting connection from %s. Maximum number of connections reached.",
6116             csp->ip_addr_str);
6117          write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6118             strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6119          close_socket(csp->cfd);
6120          freez(csp->ip_addr_str);
6121          freez(csp->listen_addr_str);
6122          freez(csp_list);
6123          continue;
6124       }
6125
6126       /* add it to the list of clients */
6127       csp_list->next = clients->next;
6128       clients->next = csp_list;
6129
6130       if (config->multi_threaded)
6131       {
6132          int child_id;
6133
6134 /* this is a switch () statement in the C preprocessor - ugh */
6135 #undef SELECTED_ONE_OPTION
6136
6137 /* Use Pthreads in preference to native code */
6138 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6139 #define SELECTED_ONE_OPTION
6140          {
6141             pthread_t the_thread;
6142             int ret;
6143
6144             ret = pthread_create(&the_thread, &attrs,
6145                (void * (*)(void *))serve, csp);
6146             child_id = ret ? -1 : 0;
6147          }
6148 #endif
6149
6150 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6151 #define SELECTED_ONE_OPTION
6152          child_id = _beginthread(
6153             (void (*)(void *))serve,
6154             64 * 1024,
6155             csp);
6156 #endif
6157
6158 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6159 #define SELECTED_ONE_OPTION
6160          {
6161             thread_id tid = spawn_thread
6162                (server_thread, "server", B_NORMAL_PRIORITY, csp);
6163
6164             if ((tid >= 0) && (resume_thread(tid) == B_OK))
6165             {
6166                child_id = (int) tid;
6167             }
6168             else
6169             {
6170                child_id = -1;
6171             }
6172          }
6173 #endif
6174
6175 #if !defined(SELECTED_ONE_OPTION)
6176          child_id = fork();
6177
6178          /* This block is only needed when using fork().
6179           * When using threads, the server thread was
6180           * created and run by the call to _beginthread().
6181           */
6182          if (child_id == 0)   /* child */
6183          {
6184             int rc = 0;
6185 #ifdef FEATURE_TOGGLE
6186             int inherited_toggle_state = global_toggle_state;
6187 #endif /* def FEATURE_TOGGLE */
6188
6189             serve(csp);
6190
6191             /*
6192              * If we've been toggled or we've blocked the request, tell Mom
6193              */
6194
6195 #ifdef FEATURE_TOGGLE
6196             if (inherited_toggle_state != global_toggle_state)
6197             {
6198                rc |= RC_FLAG_TOGGLED;
6199             }
6200 #endif /* def FEATURE_TOGGLE */
6201
6202 #ifdef FEATURE_STATISTICS
6203             if (csp->flags & CSP_FLAG_REJECTED)
6204             {
6205                rc |= RC_FLAG_BLOCKED;
6206             }
6207 #endif /* ndef FEATURE_STATISTICS */
6208
6209             _exit(rc);
6210          }
6211          else if (child_id > 0) /* parent */
6212          {
6213             /* in a fork()'d environment, the parent's
6214              * copy of the client socket and the CSP
6215              * are not used.
6216              */
6217             int child_status;
6218 #if !defined(_WIN32) && !defined(__CYGWIN__)
6219
6220             wait(&child_status);
6221
6222             /*
6223              * Evaluate child's return code: If the child has
6224              *  - been toggled, toggle ourselves
6225              *  - blocked its request, bump up the stats counter
6226              */
6227
6228 #ifdef FEATURE_TOGGLE
6229             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6230             {
6231                global_toggle_state = !global_toggle_state;
6232             }
6233 #endif /* def FEATURE_TOGGLE */
6234
6235 #ifdef FEATURE_STATISTICS
6236             urls_read++;
6237             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6238             {
6239                urls_rejected++;
6240             }
6241 #endif /* def FEATURE_STATISTICS */
6242
6243 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6244             close_socket(csp->cfd);
6245             csp->flags &= ~CSP_FLAG_ACTIVE;
6246          }
6247 #endif
6248
6249 #undef SELECTED_ONE_OPTION
6250 /* end of cpp switch () */
6251
6252          if (child_id < 0)
6253          {
6254             /*
6255              * Spawning the child failed, assume it's because
6256              * there are too many children running already.
6257              * XXX: If you assume ...
6258              */
6259             log_error(LOG_LEVEL_ERROR,
6260                "Unable to take any additional connections: %E. Active threads: %u",
6261                active_threads);
6262             write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6263                strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6264             close_socket(csp->cfd);
6265             csp->flags &= ~CSP_FLAG_ACTIVE;
6266          }
6267       }
6268       else
6269       {
6270          serve(csp);
6271       }
6272    }
6273
6274 #if defined(FEATURE_PTHREAD)
6275    pthread_attr_destroy(&attrs);
6276 #endif
6277
6278    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6279
6280 #ifdef FEATURE_GRACEFUL_TERMINATION
6281
6282    log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6283
6284    close_ports_helper(bfds);
6285
6286    unload_current_config_file();
6287    unload_current_actions_file();
6288    unload_current_re_filterfile();
6289 #ifdef FEATURE_TRUST
6290    unload_current_trust_file();
6291 #endif
6292
6293    if (config->multi_threaded)
6294    {
6295       int i = 60;
6296       do
6297       {
6298          sleep(1);
6299          sweep();
6300       } while ((clients->next != NULL) && (--i > 0));
6301
6302       if (i <= 0)
6303       {
6304          log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6305             "- still some live clients after 1 minute wait.");
6306       }
6307    }
6308    sweep();
6309    sweep();
6310
6311 #if defined(unix)
6312    freez(basedir);
6313 #endif
6314
6315 #ifdef FEATURE_HTTPS_INSPECTION
6316    /*
6317     * Only release TLS backed resources if there
6318     * are no active connections left.
6319     */
6320    if (clients->next == NULL)
6321    {
6322       ssl_release();
6323    }
6324 #endif
6325
6326    log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6327
6328 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6329    /* Cleanup - remove taskbar icon etc. */
6330    TermLogWindow();
6331 #endif
6332
6333    exit(0);
6334 #endif /* FEATURE_GRACEFUL_TERMINATION */
6335
6336 }
6337
6338
6339 /*
6340   Local Variables:
6341   tab-width: 3
6342   end:
6343 */