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