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