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