receive_encrypted_request(): Use the socket-timeout when waiting for new data
[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 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
591       /* Split the domain we just got for pattern matching */
592       init_domain_components(csp->http);
593 #endif
594
595       return JB_ERR_OK;
596    }
597    else
598    {
599       /* We can't work without destination. Go spread the news.*/
600
601       req = list_to_text(headers);
602       chomp(req);
603       /* XXX: Use correct size */
604       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
605          csp->ip_addr_str, csp->http->cmd);
606       log_error(LOG_LEVEL_ERROR,
607          "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
608          csp->ip_addr_str, csp->http->cmd, req);
609       freez(req);
610
611       write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
612          strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
613       destroy_list(headers);
614
615       return JB_ERR_PARSE;
616    }
617    /*
618     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
619     * to get the destination IP address, use it as host directly
620     * or do a reverse DNS lookup first.
621     */
622 }
623
624
625 /*********************************************************************
626  *
627  * Function    :  get_server_headers
628  *
629  * Description :  Parses server headers in iob and fills them
630  *                into csp->headers so that they can later be
631  *                handled by sed().
632  *
633  * Parameters  :
634  *          1  :  csp = Current client state (buffers, headers, etc...)
635  *
636  * Returns     :  JB_ERR_OK if everything went fine, or
637  *                JB_ERR_PARSE if the headers were incomplete.
638  *
639  *********************************************************************/
640 static jb_err get_server_headers(struct client_state *csp)
641 {
642    int continue_hack_in_da_house = 0;
643    char * header;
644
645    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
646    {
647       if (header == NULL)
648       {
649          /*
650           * continue hack in da house. Ignore the ending of
651           * this head and continue enlisting header lines.
652           * The reason is described below.
653           */
654          enlist(csp->headers, "");
655          continue_hack_in_da_house = 0;
656          continue;
657       }
658       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
659       {
660          /*
661           * It's a bodyless continue response, don't
662           * stop header parsing after reaching its end.
663           *
664           * As a result Privoxy will concatenate the
665           * next response's head and parse and deliver
666           * the headers as if they belonged to one request.
667           *
668           * The client will separate them because of the
669           * empty line between them.
670           *
671           * XXX: What we're doing here is clearly against
672           * the intended purpose of the continue header,
673           * and under some conditions (HTTP/1.0 client request)
674           * it's a standard violation.
675           *
676           * Anyway, "sort of against the spec" is preferable
677           * to "always getting confused by Continue responses"
678           * (Privoxy's behaviour before this hack was added)
679           */
680          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
681          continue_hack_in_da_house = 1;
682       }
683       else if (*header == '\0')
684       {
685          /*
686           * If the header is empty, but the Continue hack
687           * isn't active, we can assume that we reached the
688           * end of the buffer before we hit the end of the
689           * head.
690           *
691           * Inform the caller an let it decide how to handle it.
692           */
693          return JB_ERR_PARSE;
694       }
695
696       if (JB_ERR_MEMORY == enlist(csp->headers, header))
697       {
698          /*
699           * XXX: Should we quit the request and return a
700           * out of memory error page instead?
701           */
702          log_error(LOG_LEVEL_ERROR,
703             "Out of memory while enlisting server headers. %s lost.",
704             header);
705       }
706       freez(header);
707    }
708
709    return JB_ERR_OK;
710 }
711
712
713 /*********************************************************************
714  *
715  * Function    :  crunch_reason
716  *
717  * Description :  Translates the crunch reason code into a string.
718  *
719  * Parameters  :
720  *          1  :  rsp = a http_response
721  *
722  * Returns     :  A string with the crunch reason or an error description.
723  *
724  *********************************************************************/
725 static const char *crunch_reason(const struct http_response *rsp)
726 {
727    char * reason = NULL;
728
729    assert(rsp != NULL);
730    if (rsp == NULL)
731    {
732       return "Internal error while searching for crunch reason";
733    }
734
735    switch (rsp->crunch_reason)
736    {
737       case UNSUPPORTED:
738          reason = "Unsupported HTTP feature";
739          break;
740       case BLOCKED:
741          reason = "Blocked";
742          break;
743       case UNTRUSTED:
744          reason = "Untrusted";
745          break;
746       case REDIRECTED:
747          reason = "Redirected";
748          break;
749       case CGI_CALL:
750          reason = "CGI Call";
751          break;
752       case NO_SUCH_DOMAIN:
753          reason = "DNS failure";
754          break;
755       case FORWARDING_FAILED:
756          reason = "Forwarding failed";
757          break;
758       case CONNECT_FAILED:
759          reason = "Connection failure";
760          break;
761       case OUT_OF_MEMORY:
762          reason = "Out of memory (may mask other reasons)";
763          break;
764       case CONNECTION_TIMEOUT:
765          reason = "Connection timeout";
766          break;
767       case NO_SERVER_DATA:
768          reason = "No server data received";
769          break;
770       default:
771          reason = "No reason recorded";
772          break;
773    }
774
775    return reason;
776 }
777
778
779 /*********************************************************************
780  *
781  * Function    :  log_applied_actions
782  *
783  * Description :  Logs the applied actions if LOG_LEVEL_ACTIONS is
784  *                enabled.
785  *
786  * Parameters  :
787  *          1  :  actions = Current action spec to log
788  *
789  * Returns     :  Nothing.
790  *
791  *********************************************************************/
792 static void log_applied_actions(const struct current_action_spec *actions)
793 {
794    /*
795     * The conversion to text requires lots of memory allocations so
796     * we only do the conversion if the user is actually interested.
797     */
798    if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
799    {
800       char *actions_as_text = actions_to_line_of_text(actions);
801       log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
802       freez(actions_as_text);
803    }
804 }
805
806
807 /*********************************************************************
808  *
809  * Function    :  send_crunch_response
810  *
811  * Description :  Delivers already prepared response for
812  *                intercepted requests, logs the interception
813  *                and frees the response.
814  *
815  * Parameters  :
816  *          1  :  csp = Current client state (buffers, headers, etc...)
817  *          2  :  rsp = Fully prepared response. Will be freed on exit.
818  *
819  * Returns     :  Nothing.
820  *
821  *********************************************************************/
822 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
823 {
824       const struct http_request *http = csp->http;
825       char status_code[4];
826
827       assert(rsp != NULL);
828       assert(rsp->head != NULL);
829
830       if (rsp == NULL)
831       {
832          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
833       }
834
835       /*
836        * Extract the status code from the actual head
837        * that will be send to the client. It is the only
838        * way to get it right for all requests, including
839        * the fixed ones for out-of-memory problems.
840        *
841        * A head starts like this: 'HTTP/1.1 200...'
842        *                           0123456789|11
843        *                                     10
844        */
845       status_code[0] = rsp->head[9];
846       status_code[1] = rsp->head[10];
847       status_code[2] = rsp->head[11];
848       status_code[3] = '\0';
849
850       /* Log that the request was crunched and why. */
851       log_applied_actions(csp->action);
852 #ifdef FEATURE_HTTPS_INSPECTION
853       if (client_use_ssl(csp))
854       {
855          log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
856             http->hostport, http->path);
857          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
858             csp->ip_addr_str, http->gpc, http->hostport, http->path,
859             http->version, status_code, rsp->content_length);
860       }
861       else
862 #endif
863       {
864          log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
865          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
866             csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
867       }
868       /* Write the answer to the client */
869 #ifdef FEATURE_HTTPS_INSPECTION
870       if (client_use_ssl(csp))
871       {
872          if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
873                 (const unsigned char *)rsp->head, rsp->head_length,
874                 get_write_delay(csp)) < 0)
875           || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
876                 (const unsigned char *)rsp->body, rsp->content_length,
877                 get_write_delay(csp)) < 0))
878          {
879             /* There is nothing we can do about it. */
880             log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
881                "for %s through client socket %d using TLS/SSL",
882                http->url, csp->cfd);
883          }
884       }
885       else
886 #endif
887       {
888          if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
889                 get_write_delay(csp))
890           || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
891                 get_write_delay(csp)))
892          {
893             /* There is nothing we can do about it. */
894             log_error(LOG_LEVEL_CONNECT,
895                "Couldn't deliver the error message for %s through client socket %d: %E",
896                http->url, csp->cfd);
897          }
898       }
899
900       /* Clean up and return */
901       if (cgi_error_memory() != rsp)
902       {
903          free_http_response(rsp);
904       }
905       return;
906 }
907
908
909 /*********************************************************************
910  *
911  * Function    :  crunch_response_triggered
912  *
913  * Description :  Checks if the request has to be crunched,
914  *                and delivers the crunch response if necessary.
915  *
916  * Parameters  :
917  *          1  :  csp = Current client state (buffers, headers, etc...)
918  *          2  :  crunchers = list of cruncher functions to run
919  *
920  * Returns     :  TRUE if the request was answered with a crunch response
921  *                FALSE otherwise.
922  *
923  *********************************************************************/
924 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
925 {
926    struct http_response *rsp = NULL;
927    const struct cruncher *c;
928
929    /*
930     * If CGI request crunching is disabled,
931     * check the CGI dispatcher out of order to
932     * prevent unintentional blocks or redirects.
933     */
934    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
935        && (NULL != (rsp = dispatch_cgi(csp))))
936    {
937       /* Deliver, log and free the interception response. */
938       send_crunch_response(csp, rsp);
939       csp->flags |= CSP_FLAG_CRUNCHED;
940       return TRUE;
941    }
942
943    for (c = crunchers; c->cruncher != NULL; c++)
944    {
945       /*
946        * Check the cruncher if either Privoxy is toggled
947        * on and the request isn't forced, or if the cruncher
948        * applies to forced requests as well.
949        */
950       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
951           !(csp->flags & CSP_FLAG_FORCED)) ||
952           (c->flags & CF_IGNORE_FORCE))
953       {
954          rsp = c->cruncher(csp);
955          if (NULL != rsp)
956          {
957             /* Deliver, log and free the interception response. */
958             send_crunch_response(csp, rsp);
959             csp->flags |= CSP_FLAG_CRUNCHED;
960 #ifdef FEATURE_STATISTICS
961             if (c->flags & CF_COUNT_AS_REJECT)
962             {
963                csp->flags |= CSP_FLAG_REJECTED;
964             }
965 #endif /* def FEATURE_STATISTICS */
966
967             return TRUE;
968          }
969       }
970    }
971
972    return FALSE;
973 }
974
975
976 /*********************************************************************
977  *
978  * Function    :  build_request_line
979  *
980  * Description :  Builds the HTTP request line.
981  *
982  *                If a HTTP forwarder is used it expects the whole URL,
983  *                web servers only get the path.
984  *
985  * Parameters  :
986  *          1  :  csp = Current client state (buffers, headers, etc...)
987  *          2  :  fwd = The forwarding spec used for the request
988  *                XXX: Should use http->fwd instead.
989  *          3  :  request_line = The old request line which will be replaced.
990  *
991  * Returns     :  Nothing. Terminates in case of memory problems.
992  *
993  *********************************************************************/
994 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
995 {
996    struct http_request *http = csp->http;
997
998    /*
999     * Downgrade http version from 1.1 to 1.0
1000     * if +downgrade action applies.
1001     */
1002    if ((csp->action->flags & ACTION_DOWNGRADE)
1003      && (!strcmpic(http->version, "HTTP/1.1")))
1004    {
1005       freez(http->version);
1006       http->version = strdup_or_die("HTTP/1.0");
1007    }
1008
1009    /*
1010     * Rebuild the request line.
1011     */
1012    freez(*request_line);
1013    *request_line = strdup(http->gpc);
1014    string_append(request_line, " ");
1015
1016    if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1017    {
1018       string_append(request_line, http->url);
1019    }
1020    else
1021    {
1022       string_append(request_line, http->path);
1023    }
1024    string_append(request_line, " ");
1025    string_append(request_line, http->version);
1026
1027    if (*request_line == NULL)
1028    {
1029       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1030    }
1031    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1032 }
1033
1034
1035 /*********************************************************************
1036  *
1037  * Function    :  change_request_destination
1038  *
1039  * Description :  Parse a (rewritten) request line and regenerate
1040  *                the http request data.
1041  *
1042  * Parameters  :
1043  *          1  :  csp = Current client state (buffers, headers, etc...)
1044  *
1045  * Returns     :  Forwards the parse_http_request() return code.
1046  *                Terminates in case of memory problems.
1047  *
1048  *********************************************************************/
1049 static jb_err change_request_destination(struct client_state *csp)
1050 {
1051    struct http_request *http = csp->http;
1052    jb_err err;
1053
1054    log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1055       csp->headers->first->str);
1056    free_http_request(http);
1057    err = parse_http_request(csp->headers->first->str, http);
1058    if (JB_ERR_OK != err)
1059    {
1060       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1061          jb_err_to_string(err));
1062    }
1063
1064    return err;
1065 }
1066
1067
1068 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1069 /*********************************************************************
1070  *
1071  * Function    :  server_response_is_complete
1072  *
1073  * Description :  Determines whether we should stop reading
1074  *                from the server socket.
1075  *
1076  * Parameters  :
1077  *          1  :  csp = Current client state (buffers, headers, etc...)
1078  *          2  :  content_length = Length of content received so far.
1079  *
1080  * Returns     :  TRUE if the response is complete,
1081  *                FALSE otherwise.
1082  *
1083  *********************************************************************/
1084 static int server_response_is_complete(struct client_state *csp,
1085    unsigned long long content_length)
1086 {
1087    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1088
1089    if (!strcmpic(csp->http->gpc, "HEAD"))
1090    {
1091       /*
1092        * "HEAD" implies no body, we are thus expecting
1093        * no content. XXX: incomplete "list" of methods?
1094        */
1095       csp->expected_content_length = 0;
1096       content_length_known = TRUE;
1097       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1098    }
1099
1100    if (csp->http->status == 204 || csp->http->status == 304)
1101    {
1102       /*
1103        * Expect no body. XXX: incomplete "list" of status codes?
1104        */
1105       csp->expected_content_length = 0;
1106       content_length_known = TRUE;
1107       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1108    }
1109
1110    return (content_length_known && ((0 == csp->expected_content_length)
1111             || (csp->expected_content_length <= content_length)));
1112 }
1113
1114
1115 #ifdef FEATURE_CONNECTION_SHARING
1116 /*********************************************************************
1117  *
1118  * Function    :  wait_for_alive_connections
1119  *
1120  * Description :  Waits for alive connections to timeout.
1121  *
1122  * Parameters  :  N/A
1123  *
1124  * Returns     :  N/A
1125  *
1126  *********************************************************************/
1127 static void wait_for_alive_connections(void)
1128 {
1129    int connections_alive = close_unusable_connections();
1130
1131    while (0 < connections_alive)
1132    {
1133       log_error(LOG_LEVEL_CONNECT,
1134          "Waiting for %d connections to timeout.",
1135          connections_alive);
1136       sleep(60);
1137       connections_alive = close_unusable_connections();
1138    }
1139
1140    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1141
1142 }
1143 #endif /* def FEATURE_CONNECTION_SHARING */
1144
1145
1146 /*********************************************************************
1147  *
1148  * Function    :  save_connection_destination
1149  *
1150  * Description :  Remembers a connection for reuse later on.
1151  *
1152  * Parameters  :
1153  *          1  :  sfd  = Open socket to remember.
1154  *          2  :  http = The destination for the connection.
1155  *          3  :  fwd  = The forwarder settings used.
1156  *          4  :  server_connection  = storage.
1157  *
1158  * Returns     : void
1159  *
1160  *********************************************************************/
1161 void save_connection_destination(jb_socket sfd,
1162                                  const struct http_request *http,
1163                                  const struct forward_spec *fwd,
1164                                  struct reusable_connection *server_connection)
1165 {
1166    assert(sfd != JB_INVALID_SOCKET);
1167    assert(NULL != http->host);
1168
1169    server_connection->sfd = sfd;
1170    server_connection->host = strdup_or_die(http->host);
1171    server_connection->port = http->port;
1172
1173    assert(NULL != fwd);
1174    assert(server_connection->gateway_host == NULL);
1175    assert(server_connection->gateway_port == 0);
1176    assert(server_connection->forwarder_type == 0);
1177    assert(server_connection->forward_host == NULL);
1178    assert(server_connection->forward_port == 0);
1179
1180    server_connection->forwarder_type = fwd->type;
1181    if (NULL != fwd->gateway_host)
1182    {
1183       server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1184    }
1185    else
1186    {
1187       server_connection->gateway_host = NULL;
1188    }
1189    server_connection->gateway_port = fwd->gateway_port;
1190
1191    if (NULL != fwd->forward_host)
1192    {
1193       server_connection->forward_host = strdup_or_die(fwd->forward_host);
1194    }
1195    else
1196    {
1197       server_connection->forward_host = NULL;
1198    }
1199    server_connection->forward_port = fwd->forward_port;
1200 }
1201
1202
1203 /*********************************************************************
1204  *
1205  * Function    : verify_request_length
1206  *
1207  * Description : Checks if we already got the whole client requests
1208  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1209  *               we do.
1210  *
1211  *               Data that doesn't belong to the current request is
1212  *               either thrown away to let the client retry on a clean
1213  *               socket, or stashed to be dealt with after the current
1214  *               request is served.
1215  *
1216  * Parameters  :
1217  *          1  :  csp = Current client state (buffers, headers, etc...)
1218  *
1219  * Returns     :  void
1220  *
1221  *********************************************************************/
1222 static void verify_request_length(struct client_state *csp)
1223 {
1224    unsigned long long buffered_request_bytes =
1225       (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1226
1227    if ((csp->expected_client_content_length != 0)
1228       && (buffered_request_bytes != 0))
1229    {
1230       if (csp->expected_client_content_length >= buffered_request_bytes)
1231       {
1232          csp->expected_client_content_length -= buffered_request_bytes;
1233          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1234             "to account for the %llu ones we already got.",
1235             csp->expected_client_content_length, buffered_request_bytes);
1236       }
1237       else
1238       {
1239          assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1240          csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1241          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1242             "Marking the server socket tainted after throwing %llu bytes away.",
1243             buffered_request_bytes - csp->expected_client_content_length);
1244          csp->expected_client_content_length = 0;
1245          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1246       }
1247
1248       if (csp->expected_client_content_length == 0)
1249       {
1250          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1251       }
1252    }
1253
1254    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1255       && ((csp->client_iob->cur < csp->client_iob->eod)
1256          || (csp->expected_client_content_length != 0)))
1257    {
1258       if (strcmpic(csp->http->gpc, "GET")
1259          && strcmpic(csp->http->gpc, "HEAD")
1260          && strcmpic(csp->http->gpc, "TRACE")
1261          && strcmpic(csp->http->gpc, "OPTIONS")
1262          && strcmpic(csp->http->gpc, "DELETE"))
1263       {
1264          /* XXX: this is an incomplete hack */
1265          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1266          log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1267       }
1268       else
1269       {
1270          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1271
1272          if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1273          {
1274             csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1275             log_error(LOG_LEVEL_CONNECT,
1276                "Possible pipeline attempt detected. The connection will not "
1277                "be kept alive and we will only serve the first request.");
1278             /* Nuke the pipelined requests from orbit, just to be sure. */
1279             clear_iob(csp->client_iob);
1280          }
1281          else
1282          {
1283             /*
1284              * Keep the pipelined data around for now, we'll deal with
1285              * it once we're done serving the current request.
1286              */
1287             csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1288             assert(csp->client_iob->eod >= csp->client_iob->cur);
1289             log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1290                "%d bytes of pipelined data received.",
1291                (int)(csp->client_iob->eod - csp->client_iob->cur));
1292          }
1293       }
1294    }
1295    else
1296    {
1297       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1298       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1299    }
1300 }
1301 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1302
1303
1304 /*********************************************************************
1305  *
1306  * Function    :  mark_server_socket_tainted
1307  *
1308  * Description :  Makes sure we don't reuse a server socket
1309  *                (if we didn't read everything the server sent
1310  *                us reusing the socket would lead to garbage).
1311  *
1312  * Parameters  :
1313  *          1  :  csp = Current client state (buffers, headers, etc...)
1314  *
1315  * Returns     :  void.
1316  *
1317  *********************************************************************/
1318 static void mark_server_socket_tainted(struct client_state *csp)
1319 {
1320    /*
1321     * For consistency we always mark the server socket
1322     * tainted, however, to reduce the log noise we only
1323     * emit a log message if the server socket could have
1324     * actually been reused.
1325     */
1326    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1327       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1328    {
1329       log_error(LOG_LEVEL_CONNECT,
1330          "Marking the server socket %d tainted.",
1331          csp->server_connection.sfd);
1332    }
1333    csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1334 }
1335
1336 /*********************************************************************
1337  *
1338  * Function    :  get_request_line
1339  *
1340  * Description : Read the client request line.
1341  *
1342  * Parameters  :
1343  *          1  :  csp = Current client state (buffers, headers, etc...)
1344  *
1345  * Returns     :  Pointer to request line or NULL in case of errors.
1346  *
1347  *********************************************************************/
1348 static char *get_request_line(struct client_state *csp)
1349 {
1350    char buf[BUFFER_SIZE];
1351    char *request_line = NULL;
1352    int len;
1353
1354    memset(buf, 0, sizeof(buf));
1355
1356    if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1357    {
1358       /*
1359        * If there are multiple pipelined requests waiting,
1360        * the flag will be set again once the next request
1361        * has been parsed.
1362        */
1363       csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1364
1365       request_line = get_header(csp->client_iob);
1366       if ((NULL != request_line) && ('\0' != *request_line))
1367       {
1368          return request_line;
1369       }
1370       else
1371       {
1372          log_error(LOG_LEVEL_CONNECT, "No complete request line "
1373             "received yet. Continuing reading from %d.", csp->cfd);
1374       }
1375    }
1376
1377    do
1378    {
1379       if (
1380 #ifdef FUZZ
1381           0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1382 #endif
1383           !data_is_available(csp->cfd, csp->config->socket_timeout)
1384           )
1385       {
1386          if (socket_is_still_alive(csp->cfd))
1387          {
1388             log_error(LOG_LEVEL_CONNECT,
1389                "No request line on socket %d received in time. Timeout: %d.",
1390                csp->cfd, csp->config->socket_timeout);
1391             write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1392                strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1393                get_write_delay(csp));
1394          }
1395          else
1396          {
1397             log_error(LOG_LEVEL_CONNECT,
1398                "The client side of the connection on socket %d got "
1399                "closed without sending a complete request line.", csp->cfd);
1400          }
1401          return NULL;
1402       }
1403
1404       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1405
1406       if (len <= 0) return NULL;
1407
1408       /*
1409        * If there is no memory left for buffering the
1410        * request, there is nothing we can do but hang up
1411        */
1412       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1413       {
1414          return NULL;
1415       }
1416
1417       request_line = get_header(csp->client_iob);
1418
1419    } while ((NULL != request_line) && ('\0' == *request_line));
1420
1421    return request_line;
1422
1423 }
1424
1425 enum chunk_status
1426 {
1427    CHUNK_STATUS_MISSING_DATA,
1428    CHUNK_STATUS_BODY_COMPLETE,
1429    CHUNK_STATUS_PARSE_ERROR
1430 };
1431
1432
1433 /*********************************************************************
1434  *
1435  * Function    :  chunked_body_is_complete
1436  *
1437  * Description :  Figures out whether or not a chunked body is complete.
1438  *
1439  *                Currently it always starts at the beginning of the
1440  *                buffer which is somewhat wasteful and prevents Privoxy
1441  *                from starting to forward the correctly parsed chunks
1442  *                as soon as theoretically possible.
1443  *
1444  *                Should be modified to work with a common buffer,
1445  *                and allow the caller to skip already parsed chunks.
1446  *
1447  *                This would allow the function to be used for unbuffered
1448  *                response bodies as well.
1449  *
1450  * Parameters  :
1451  *          1  :  iob = Buffer with the body to check.
1452  *          2  :  length = Length of complete body
1453  *
1454  * Returns     :  Enum with the result of the check.
1455  *
1456  *********************************************************************/
1457 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1458 {
1459    unsigned int chunksize;
1460    char *p = iob->cur;
1461
1462    do
1463    {
1464       /*
1465        * We need at least a single digit, followed by "\r\n",
1466        * followed by an unknown amount of data, followed by "\r\n".
1467        */
1468       if (p + 5 > iob->eod)
1469       {
1470          return CHUNK_STATUS_MISSING_DATA;
1471       }
1472       if (sscanf(p, "%x", &chunksize) != 1)
1473       {
1474          return CHUNK_STATUS_PARSE_ERROR;
1475       }
1476
1477       /*
1478        * We want at least a single digit, followed by "\r\n",
1479        * followed by the specified amount of data, followed by "\r\n".
1480        */
1481       if (p + chunksize + 5 > iob->eod)
1482       {
1483          return CHUNK_STATUS_MISSING_DATA;
1484       }
1485
1486       /* Skip chunk-size. */
1487       p = strstr(p, "\r\n");
1488       if (NULL == p)
1489       {
1490          return CHUNK_STATUS_PARSE_ERROR;
1491       }
1492       /* Move beyond the chunkdata. */
1493       p += 2 + chunksize;
1494
1495       /* There should be another "\r\n" to skip */
1496       if (memcmp(p, "\r\n", 2))
1497       {
1498          return CHUNK_STATUS_PARSE_ERROR;
1499       }
1500       p += 2;
1501    } while (chunksize > 0U);
1502
1503    *length = (size_t)(p - iob->cur);
1504    assert(*length <= (size_t)(iob->eod - iob->cur));
1505    assert(p <= iob->eod);
1506
1507    return CHUNK_STATUS_BODY_COMPLETE;
1508
1509 }
1510
1511
1512 /*********************************************************************
1513  *
1514  * Function    : receive_chunked_client_request_body
1515  *
1516  * Description : Read the chunk-encoded client request body.
1517  *               Failures are dealt with.
1518  *
1519  * Parameters  :
1520  *          1  :  csp = Current client state (buffers, headers, etc...)
1521  *
1522  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1523  *
1524  *********************************************************************/
1525 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1526 {
1527    size_t body_length;
1528    enum chunk_status status;
1529
1530    while (CHUNK_STATUS_MISSING_DATA ==
1531       (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1532    {
1533       char buf[BUFFER_SIZE];
1534       int len;
1535
1536       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1537       {
1538          log_error(LOG_LEVEL_ERROR,
1539             "Timeout while waiting for the client body.");
1540          break;
1541       }
1542       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1543       if (len <= 0)
1544       {
1545          log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1546          break;
1547       }
1548       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1549       {
1550          break;
1551       }
1552    }
1553    if (status != CHUNK_STATUS_BODY_COMPLETE)
1554    {
1555       write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1556          strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1557       log_error(LOG_LEVEL_CLF,
1558          "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1559       return JB_ERR_PARSE;
1560    }
1561    log_error(LOG_LEVEL_CONNECT,
1562       "Chunked client body completely read. Length: %d", body_length);
1563    csp->expected_client_content_length = body_length;
1564
1565    return JB_ERR_OK;
1566
1567 }
1568
1569
1570 #ifdef FUZZ
1571 /*********************************************************************
1572  *
1573  * Function    :  fuzz_chunked_transfer_encoding
1574  *
1575  * Description :  Treat the fuzzed input as chunked transfer encoding
1576  *                to check and dechunk.
1577  *
1578  * Parameters  :
1579  *          1  :  csp      = Used to store the data.
1580  *          2  :  fuzz_input_file = File to read the input from.
1581  *
1582  * Returns     : Result of dechunking
1583  *
1584  *********************************************************************/
1585 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1586 {
1587    size_t length;
1588    size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1589    enum chunk_status status;
1590
1591    status = chunked_body_is_complete(csp->iob, &length);
1592    if (CHUNK_STATUS_BODY_COMPLETE != status)
1593    {
1594       log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1595    }
1596
1597    return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1598
1599 }
1600
1601
1602 /*********************************************************************
1603  *
1604  * Function    : fuzz_client_request
1605  *
1606  * Description : Try to get a client request from the fuzzed input.
1607  *
1608  * Parameters  :
1609  *          1  :  csp = Current client state (buffers, headers, etc...)
1610  *          2  :  fuzz_input_file = File to read the input from.
1611  *
1612  * Returns     :  Result of fuzzing.
1613  *
1614  *********************************************************************/
1615 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1616 {
1617    jb_err err;
1618
1619    csp->cfd = 0;
1620    csp->ip_addr_str = "fuzzer";
1621
1622    if (strcmp(fuzz_input_file, "-") != 0)
1623    {
1624       log_error(LOG_LEVEL_FATAL,
1625          "Fuzzed client requests can currently only be read from stdin (-).");
1626    }
1627    err = receive_client_request(csp);
1628    if (err != JB_ERR_OK)
1629    {
1630       return 1;
1631    }
1632    err = parse_client_request(csp);
1633    if (err != JB_ERR_OK)
1634    {
1635       return 1;
1636    }
1637
1638    return 0;
1639
1640 }
1641 #endif  /* def FUZZ */
1642
1643
1644 #ifdef FEATURE_FORCE_LOAD
1645 /*********************************************************************
1646  *
1647  * Function    :  force_required
1648  *
1649  * Description : Checks a request line to see if it contains
1650  *               the FORCE_PREFIX. If it does, it is removed
1651  *               unless enforcing requests has beend disabled.
1652  *
1653  * Parameters  :
1654  *          1  :  request_line = HTTP request line
1655  *
1656  * Returns     :  TRUE if force is required, FALSE otherwise.
1657  *
1658  *********************************************************************/
1659 static int force_required(const struct client_state *csp, char *request_line)
1660 {
1661    char *p;
1662
1663    p = strstr(request_line, "http://");
1664    if (p != NULL)
1665    {
1666       /* Skip protocol */
1667       p += strlen("http://");
1668    }
1669    else
1670    {
1671       /* Intercepted request usually don't specify the protocol. */
1672       p = request_line;
1673    }
1674
1675    /* Go to the beginning of the path */
1676    p = strstr(p, "/");
1677    if (p == NULL)
1678    {
1679       /*
1680        * If the path is missing the request line is invalid and we
1681        * are done here. The client-visible rejection happens later on.
1682        */
1683       return 0;
1684    }
1685
1686    if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1687    {
1688       if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1689       {
1690          /* XXX: Should clean more carefully */
1691          strclean(request_line, FORCE_PREFIX);
1692          log_error(LOG_LEVEL_FORCE,
1693             "Enforcing request: \"%s\".", request_line);
1694
1695          return 1;
1696       }
1697       log_error(LOG_LEVEL_FORCE,
1698          "Ignored force prefix in request: \"%s\".", request_line);
1699    }
1700
1701    return 0;
1702
1703 }
1704 #endif /* def FEATURE_FORCE_LOAD */
1705
1706
1707 /*********************************************************************
1708  *
1709  * Function    :  receive_client_request
1710  *
1711  * Description : Read the client's request (more precisely the
1712  *               client headers) and answer it if necessary.
1713  *
1714  * Parameters  :
1715  *          1  :  csp = Current client state (buffers, headers, etc...)
1716  *
1717  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1718  *
1719  *********************************************************************/
1720 static jb_err receive_client_request(struct client_state *csp)
1721 {
1722    char buf[BUFFER_SIZE];
1723    char *p;
1724    char *req = NULL;
1725    struct http_request *http;
1726    int len;
1727    jb_err err;
1728
1729    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1730    struct list header_list;
1731    struct list *headers = &header_list;
1732
1733    /* We don't care if the arriving data is a valid HTTP request or not. */
1734    csp->requests_received_total++;
1735
1736    http = csp->http;
1737
1738    memset(buf, 0, sizeof(buf));
1739
1740    req = get_request_line(csp);
1741    if (req == NULL)
1742    {
1743       mark_server_socket_tainted(csp);
1744       return JB_ERR_PARSE;
1745    }
1746    assert(*req != '\0');
1747
1748    if (client_protocol_is_unsupported(csp, req))
1749    {
1750       return JB_ERR_PARSE;
1751    }
1752
1753 #ifdef FEATURE_FORCE_LOAD
1754    if (force_required(csp, req))
1755    {
1756       csp->flags |= CSP_FLAG_FORCED;
1757    }
1758 #endif /* def FEATURE_FORCE_LOAD */
1759
1760    err = parse_http_request(req, http);
1761    freez(req);
1762    if (JB_ERR_OK != err)
1763    {
1764       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1765          get_write_delay(csp));
1766       /* XXX: Use correct size */
1767       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1768       log_error(LOG_LEVEL_ERROR,
1769          "Couldn't parse request line received from %s: %s",
1770          csp->ip_addr_str, jb_err_to_string(err));
1771
1772       free_http_request(http);
1773       return JB_ERR_PARSE;
1774    }
1775
1776    /* grab the rest of the client's headers */
1777    init_list(headers);
1778    for (;;)
1779    {
1780       p = get_header(csp->client_iob);
1781
1782       if (p == NULL)
1783       {
1784          /* There are no additional headers to read. */
1785          break;
1786       }
1787
1788       if (*p == '\0')
1789       {
1790          /*
1791           * We didn't receive a complete header
1792           * line yet, get the rest of it.
1793           */
1794          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1795          {
1796             log_error(LOG_LEVEL_ERROR,
1797                "Stopped grabbing the client headers.");
1798             destroy_list(headers);
1799             return JB_ERR_PARSE;
1800          }
1801
1802          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1803          if (len <= 0)
1804          {
1805             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1806             destroy_list(headers);
1807             return JB_ERR_PARSE;
1808          }
1809
1810          if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1811          {
1812             /*
1813              * If there is no memory left for buffering the
1814              * request, there is nothing we can do but hang up
1815              */
1816             destroy_list(headers);
1817             return JB_ERR_MEMORY;
1818          }
1819       }
1820       else
1821       {
1822          if (!strncmpic(p, "Transfer-Encoding:", 18))
1823          {
1824             /*
1825              * XXX: should be called through sed()
1826              *      but currently can't.
1827              */
1828             client_transfer_encoding(csp, &p);
1829          }
1830          /*
1831           * We were able to read a complete
1832           * header and can finally enlist it.
1833           */
1834          enlist(headers, p);
1835          freez(p);
1836       }
1837    }
1838
1839    if (http->host == NULL)
1840    {
1841       /*
1842        * If we still don't know the request destination,
1843        * the request is invalid or the client uses
1844        * Privoxy without its knowledge.
1845        */
1846       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1847       {
1848          /*
1849           * Our attempts to get the request destination
1850           * elsewhere failed or Privoxy is configured
1851           * to only accept proxy requests.
1852           *
1853           * An error response has already been send
1854           * and we're done here.
1855           */
1856          return JB_ERR_PARSE;
1857       }
1858    }
1859
1860 #ifdef FEATURE_CLIENT_TAGS
1861    /* XXX: If the headers were enlisted sooner, passing csp would do. */
1862    set_client_address(csp, headers);
1863    get_tag_list_for_client(csp->client_tags, csp->client_address);
1864 #endif
1865
1866    /*
1867     * Determine the actions for this URL
1868     */
1869 #ifdef FEATURE_TOGGLE
1870    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1871    {
1872       /* Most compatible set of actions (i.e. none) */
1873       init_current_action(csp->action);
1874    }
1875    else
1876 #endif /* ndef FEATURE_TOGGLE */
1877    {
1878       get_url_actions(csp, http);
1879    }
1880
1881    enlist(csp->headers, http->cmd);
1882
1883    /* Append the previously read headers */
1884    err = list_append_list_unique(csp->headers, headers);
1885    destroy_list(headers);
1886
1887    return err;
1888
1889 }
1890
1891
1892 /*********************************************************************
1893  *
1894  * Function    : parse_client_request
1895  *
1896  * Description : Parses the client's request and decides what to do
1897  *               with it.
1898  *
1899  *               Note that since we're not using select() we could get
1900  *               blocked here if a client connected, then didn't say
1901  *               anything!
1902  *
1903  * Parameters  :
1904  *          1  :  csp = Current client state (buffers, headers, etc...)
1905  *
1906  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1907  *
1908  *********************************************************************/
1909 static jb_err parse_client_request(struct client_state *csp)
1910 {
1911    struct http_request *http = csp->http;
1912    jb_err err;
1913
1914 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1915    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1916     && (!strcmpic(csp->http->version, "HTTP/1.1"))
1917     && (csp->http->ssl == 0))
1918    {
1919       /* Assume persistence until further notice */
1920       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1921    }
1922
1923    if (csp->http->ssl == 0)
1924    {
1925       /*
1926        * This whole block belongs to chat() but currently
1927        * has to be executed before sed().
1928        */
1929       if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1930       {
1931          if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1932          {
1933             return JB_ERR_PARSE;
1934          }
1935       }
1936       else
1937       {
1938          csp->expected_client_content_length = get_expected_content_length(csp->headers);
1939       }
1940       verify_request_length(csp);
1941    }
1942    else
1943    {
1944       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1945    }
1946 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1947
1948    err = sed(csp, FILTER_CLIENT_HEADERS);
1949    if (JB_ERR_OK != err)
1950    {
1951       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1952          csp->ip_addr_str);
1953       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1954          csp->ip_addr_str, csp->http->cmd);
1955       write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1956       return JB_ERR_PARSE;
1957    }
1958    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1959
1960    /* Check request line for rewrites. */
1961    if ((NULL == csp->headers->first->str)
1962       || (strcmp(http->cmd, csp->headers->first->str) &&
1963          (JB_ERR_OK != change_request_destination(csp))))
1964    {
1965       /*
1966        * A header filter broke the request line - bail out.
1967        */
1968       write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1969          strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1970       /* XXX: Use correct size */
1971       log_error(LOG_LEVEL_CLF,
1972          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1973       log_error(LOG_LEVEL_ERROR,
1974          "Invalid request line after applying header filters.");
1975       free_http_request(http);
1976
1977       return JB_ERR_PARSE;
1978    }
1979
1980    if (client_has_unsupported_expectations(csp))
1981    {
1982       return JB_ERR_PARSE;
1983    }
1984
1985    return JB_ERR_OK;
1986
1987 }
1988
1989
1990 /*********************************************************************
1991  *
1992  * Function    : send_http_request
1993  *
1994  * Description : Sends the HTTP headers from the client request
1995  *               and all the body data that has already been received.
1996  *
1997  * Parameters  :
1998  *          1  :  csp = Current client state (buffers, headers, etc...)
1999  *
2000  * Returns     :  0 on success, anything else is an error.
2001  *
2002  *********************************************************************/
2003 static int send_http_request(struct client_state *csp)
2004 {
2005    char *hdr;
2006    int write_failure;
2007
2008    hdr = list_to_text(csp->headers);
2009    if (hdr == NULL)
2010    {
2011       /* FIXME Should handle error properly */
2012       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2013    }
2014    list_remove_all(csp->headers);
2015
2016    /*
2017     * Write the client's (modified) header to the server
2018     * (along with anything else that may be in the buffer)
2019     */
2020    write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2021    freez(hdr);
2022
2023    if (write_failure)
2024    {
2025       log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2026          csp->http->hostport);
2027    }
2028    else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2029       && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2030    {
2031       write_failure = 1;
2032       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2033          csp->http->hostport);
2034    }
2035
2036    return write_failure;
2037
2038 }
2039
2040
2041 #ifdef FEATURE_HTTPS_INSPECTION
2042 /*********************************************************************
2043  *
2044  * Function    : receive_and_send_encrypted_post_data
2045  *
2046  * Description : Reads remaining POST data from the client and sends
2047  *               it to the server.
2048  *
2049  * Parameters  :
2050  *          1  :  csp = Current client state (buffers, headers, etc...)
2051  *
2052  * Returns     :  0 on success, anything else is an error.
2053  *
2054  *********************************************************************/
2055 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2056 {
2057    int content_length_known = csp->expected_client_content_length != 0;
2058
2059    while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl))
2060       || (content_length_known && csp->expected_client_content_length != 0))
2061    {
2062       unsigned char buf[BUFFER_SIZE];
2063       int len;
2064       int max_bytes_to_read = sizeof(buf);
2065
2066       if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2067       {
2068          max_bytes_to_read = (int)csp->expected_client_content_length;
2069       }
2070       log_error(LOG_LEVEL_CONNECT,
2071          "Waiting for up to %d bytes of POST data from the client.",
2072          max_bytes_to_read);
2073       len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
2074          (unsigned)max_bytes_to_read);
2075       if (len == -1)
2076       {
2077          return 1;
2078       }
2079       if (len == 0)
2080       {
2081          /* XXX: Does this actually happen? */
2082          break;
2083       }
2084       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2085          len);
2086       len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2087       if (len == -1)
2088       {
2089          return 1;
2090       }
2091       if (csp->expected_client_content_length != 0)
2092       {
2093          if (csp->expected_client_content_length >= len)
2094          {
2095             csp->expected_client_content_length -= (unsigned)len;
2096          }
2097          if (csp->expected_client_content_length == 0)
2098          {
2099             log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2100             break;
2101          }
2102       }
2103    }
2104
2105    log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2106
2107    return 0;
2108
2109 }
2110
2111
2112 /*********************************************************************
2113  *
2114  * Function    : send_https_request
2115  *
2116  * Description : Sends the HTTP headers from the client request
2117  *               and all the body data that has already been received.
2118  *
2119  * Parameters  :
2120  *          1  :  csp = Current client state (buffers, headers, etc...)
2121  *
2122  * Returns     :  0 on success, anything else is an error.
2123  *
2124  *********************************************************************/
2125 static int send_https_request(struct client_state *csp)
2126 {
2127    char *hdr;
2128    int ret;
2129    long flushed = 0;
2130
2131    hdr = list_to_text(csp->https_headers);
2132    if (hdr == NULL)
2133    {
2134       /* FIXME Should handle error properly */
2135       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2136    }
2137    list_remove_all(csp->https_headers);
2138
2139    /*
2140     * Write the client's (modified) header to the server
2141     * (along with anything else that may be in the buffer)
2142     */
2143    ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2144       (const unsigned char *)hdr, strlen(hdr));
2145    freez(hdr);
2146
2147    if (ret < 0)
2148    {
2149       log_error(LOG_LEVEL_CONNECT,
2150          "Failed sending encrypted request headers to: %s: %E",
2151          csp->http->hostport);
2152       mark_server_socket_tainted(csp);
2153       return 1;
2154    }
2155
2156    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2157       && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2158             csp->client_iob)) < 0))
2159    {
2160       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2161          csp->http->hostport);
2162       return 1;
2163    }
2164    if (flushed != 0)
2165    {
2166       if (csp->expected_client_content_length != 0)
2167       {
2168          if (csp->expected_client_content_length < flushed)
2169          {
2170             log_error(LOG_LEVEL_ERROR,
2171                "Flushed %d bytes of request body while only expecting %llu",
2172                flushed, csp->expected_client_content_length);
2173             csp->expected_client_content_length = 0;
2174          }
2175          else
2176          {
2177             log_error(LOG_LEVEL_CONNECT,
2178                "Flushed %d bytes of request body while expecting %llu",
2179                flushed, csp->expected_client_content_length);
2180             csp->expected_client_content_length -= (unsigned)flushed;
2181             if (receive_and_send_encrypted_post_data(csp))
2182             {
2183                return 1;
2184             }
2185          }
2186       }
2187       else
2188       {
2189          log_error(LOG_LEVEL_CONNECT,
2190             "Flushed %d bytes of request body", flushed);
2191       }
2192    }
2193
2194    log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2195
2196    return 0;
2197
2198 }
2199
2200
2201 /*********************************************************************
2202  *
2203  * Function    :  receive_encrypted_request
2204  *
2205  * Description :  Receives an encrypted request.
2206  *
2207  * Parameters  :
2208  *          1  :  csp = Current client state (buffers, headers, etc...)
2209  *
2210  * Returns     :  JB_ERR_OK on success,
2211  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2212  *
2213  *********************************************************************/
2214 static jb_err receive_encrypted_request(struct client_state *csp)
2215 {
2216    char buf[BUFFER_SIZE];
2217    int len;
2218    char *p;
2219
2220    do
2221    {
2222       log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2223       if (!is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) &&
2224           !data_is_available(csp->cfd, csp->config->socket_timeout))
2225       {
2226          log_error(LOG_LEVEL_CONNECT,
2227             "Socket %d timed out while waiting for client headers", csp->cfd);
2228          return JB_ERR_PARSE;
2229       }
2230       len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2231          (unsigned char *)buf, sizeof(buf));
2232       if (len == -1)
2233       {
2234          return JB_ERR_PARSE;
2235       }
2236       if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2237       {
2238          return JB_ERR_MEMORY;
2239       }
2240       p = strstr(csp->client_iob->cur, "\r\n\r\n");
2241    } while (p == NULL);
2242
2243    log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2244
2245    return JB_ERR_OK;
2246 }
2247
2248
2249 /*********************************************************************
2250  *
2251  * Function    :  process_encrypted_request
2252  *
2253  * Description :  Receives and parses an encrypted request.
2254  *
2255  * Parameters  :
2256  *          1  :  csp = Current client state (buffers, headers, etc...)
2257  *
2258  * Returns     :  JB_ERR_OK on success,
2259  *                JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2260  *
2261  *********************************************************************/
2262 static jb_err process_encrypted_request(struct client_state *csp)
2263 {
2264    char *p;
2265    char *request_line;
2266    jb_err err;
2267    /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2268    struct list header_list;
2269    struct list *headers = &header_list;
2270
2271    err = receive_encrypted_request(csp);
2272    if (err != JB_ERR_OK)
2273    {
2274       /* XXX: Also used for JB_ERR_MEMORY */
2275       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2276          jb_err_to_string(err));
2277       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2278          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2279       return err;
2280    }
2281
2282    /* We don't need get_request_line() because the whole HTTP head is buffered. */
2283    request_line = get_header(csp->client_iob);
2284    if (request_line == NULL)
2285    {
2286       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2287       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2288          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2289       return JB_ERR_PARSE;
2290    }
2291    assert(*request_line != '\0');
2292
2293    if (client_protocol_is_unsupported(csp, request_line))
2294    {
2295       /*
2296        * If the protocol is unsupported we're done here.
2297        * client_protocol_is_unsupported() took care of sending
2298        * the error response and logging the error message.
2299        */
2300       return JB_ERR_PARSE;
2301    }
2302
2303 #ifdef FEATURE_FORCE_LOAD
2304    if (force_required(csp, request_line))
2305    {
2306       csp->flags |= CSP_FLAG_FORCED;
2307    }
2308 #endif /* def FEATURE_FORCE_LOAD */
2309
2310    free_http_request(csp->http);
2311
2312    err = parse_http_request(request_line, csp->http);
2313    /* XXX: Restore ssl setting. This is ugly */
2314    csp->http->client_ssl = 1;
2315    csp->http->server_ssl = 1;
2316
2317    freez(request_line);
2318    if (JB_ERR_OK != err)
2319    {
2320       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2321          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2322       /* XXX: Use correct size */
2323       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2324       log_error(LOG_LEVEL_ERROR,
2325          "Couldn't parse request line received from %s: %s",
2326          csp->ip_addr_str, jb_err_to_string(err));
2327
2328       free_http_request(csp->http);
2329       return JB_ERR_PARSE;
2330    }
2331
2332    /* Parse the rest of the client's headers. */
2333    init_list(headers);
2334    for (;;)
2335    {
2336       p = get_header(csp->client_iob);
2337
2338       if (p == NULL)
2339       {
2340          /* There are no additional headers to read. */
2341          break;
2342       }
2343       enlist(headers, p);
2344       freez(p);
2345    }
2346
2347    if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2348    {
2349       /*
2350        * Our attempts to get the request destination
2351        * elsewhere failed.
2352        */
2353       log_error(LOG_LEVEL_ERROR,
2354          "Failed to get the encrypted request destination");
2355       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2356          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2357       return JB_ERR_PARSE;
2358    }
2359
2360 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2361    /* Split the domain we just got for pattern matching */
2362    init_domain_components(csp->http);
2363 #endif
2364
2365 #ifdef FEATURE_TOGGLE
2366    if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2367 #endif
2368    {
2369       /* Determine the actions for this URL */
2370       get_url_actions(csp, csp->http);
2371    }
2372
2373    enlist(csp->https_headers, csp->http->cmd);
2374
2375    /* Append the previously read headers */
2376    err = list_append_list_unique(csp->https_headers, headers);
2377    destroy_list(headers);
2378    if (JB_ERR_OK != err)
2379    {
2380       /* XXX: Send error message */
2381       return err;
2382    }
2383
2384    /* XXX: Work around crash */
2385    csp->error_message = NULL;
2386
2387    /* XXX: Why do this here? */
2388    csp->http->ssl = 1;
2389
2390    err = sed_https(csp);
2391    if (JB_ERR_OK != err)
2392    {
2393       ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2394          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2395       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2396          csp->ip_addr_str);
2397       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2398          csp->ip_addr_str, csp->http->cmd);
2399       return JB_ERR_PARSE;
2400    }
2401
2402    log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2403    log_applied_actions(csp->action);
2404    log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2405       csp->http->path);
2406
2407    return err;
2408
2409 }
2410
2411 /*********************************************************************
2412  *
2413  * Function    :  cgi_page_requested
2414  *
2415  * Description :  Checks if a request is for an internal CGI page.
2416  *
2417  * Parameters  :
2418  *          1  :  host = The host requested by the client.
2419  *
2420  * Returns     :  1 if a CGI page has been requested, 0 otherwise
2421  *
2422  *********************************************************************/
2423 static int cgi_page_requested(const char *host)
2424 {
2425    if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2426     || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2427     || (0 == strcmpic(host, CGI_SITE_2_HOST))
2428     || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2429    {
2430       return 1;
2431    }
2432
2433    return 0;
2434
2435 }
2436
2437 #endif
2438
2439
2440 /*********************************************************************
2441  *
2442  * Function    :  handle_established_connection
2443  *
2444  * Description :  Shuffle data between client and server once the
2445  *                connection has been established.
2446  *
2447  * Parameters  :
2448  *          1  :  csp = Current client state (buffers, headers, etc...)
2449  *
2450  * Returns     :  Nothing.
2451  *
2452  *********************************************************************/
2453 static void handle_established_connection(struct client_state *csp)
2454 {
2455    char *hdr;
2456    char *p;
2457    int n;
2458 #ifdef HAVE_POLL
2459    struct pollfd poll_fds[2];
2460 #else
2461    fd_set rfds;
2462    jb_socket maxfd;
2463    struct timeval timeout;
2464 #endif
2465    int server_body;
2466    int ms_iis5_hack = 0;
2467    unsigned long long byte_count = 0;
2468    struct http_request *http;
2469    long len = 0; /* for buffer sizes (and negative error codes) */
2470    int buffer_and_filter_content = 0;
2471    unsigned int write_delay;
2472 #ifdef FEATURE_HTTPS_INSPECTION
2473    int ret = 0;
2474    int use_ssl_tunnel = 0;
2475    csp->dont_verify_certificate = 0;
2476
2477    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2478    {
2479       /* Pass encrypted content without filtering. */
2480       use_ssl_tunnel = 1;
2481    }
2482 #endif
2483
2484    /* Skeleton for HTTP response, if we should intercept the request */
2485    struct http_response *rsp;
2486 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2487    int watch_client_socket;
2488 #endif
2489
2490    csp->receive_buffer_size = csp->config->receive_buffer_size;
2491    csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2492    if (csp->receive_buffer == NULL)
2493    {
2494       log_error(LOG_LEVEL_ERROR,
2495          "Out of memory. Failed to allocate the receive buffer.");
2496       rsp = cgi_error_memory();
2497       send_crunch_response(csp, rsp);
2498       return;
2499    }
2500
2501    http = csp->http;
2502
2503 #ifndef HAVE_POLL
2504    maxfd = (csp->cfd > csp->server_connection.sfd) ?
2505       csp->cfd : csp->server_connection.sfd;
2506 #endif
2507
2508    /* pass data between the client and server
2509     * until one or the other shuts down the connection.
2510     */
2511
2512    server_body = 0;
2513
2514 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2515    watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2516 #endif
2517    write_delay = get_write_delay(csp);
2518
2519    for (;;)
2520    {
2521 #ifndef HAVE_POLL
2522 #ifdef __OS2__
2523       /*
2524        * FD_ZERO here seems to point to an errant macro which crashes.
2525        * So do this by hand for now...
2526        */
2527       memset(&rfds,0x00,sizeof(fd_set));
2528 #else
2529       FD_ZERO(&rfds);
2530 #endif
2531 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2532       if (!watch_client_socket)
2533       {
2534          maxfd = csp->server_connection.sfd;
2535       }
2536       else
2537 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2538       {
2539          FD_SET(csp->cfd, &rfds);
2540       }
2541
2542       FD_SET(csp->server_connection.sfd, &rfds);
2543 #endif /* ndef HAVE_POLL */
2544
2545 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2546       if ((csp->flags & CSP_FLAG_CHUNKED)
2547          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2548          && ((csp->iob->eod - csp->iob->cur) >= 5)
2549          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2550       {
2551          /*
2552           * XXX: This check should be obsolete now,
2553           *      but let's wait a while to be sure.
2554           */
2555          log_error(LOG_LEVEL_CONNECT,
2556             "Looks like we got the last chunk together with "
2557             "the server headers but didn't detect it earlier. "
2558             "We better stop reading.");
2559          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2560          csp->expected_content_length = byte_count;
2561          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2562       }
2563       if (server_body && server_response_is_complete(csp, byte_count))
2564       {
2565          if (csp->expected_content_length == byte_count)
2566          {
2567             log_error(LOG_LEVEL_CONNECT,
2568                "Done reading from server. Content length: %llu as expected. "
2569                "Bytes most recently read: %d.",
2570                byte_count, len);
2571          }
2572          else
2573          {
2574             log_error(LOG_LEVEL_CONNECT,
2575                "Done reading from server. Expected content length: %llu. "
2576                "Actual content length: %llu. Bytes most recently read: %d.",
2577                csp->expected_content_length, byte_count, len);
2578          }
2579          len = 0;
2580          /*
2581           * XXX: Should not jump around, handle_established_connection()
2582           * is complicated enough already.
2583           */
2584          goto reading_done;
2585       }
2586 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2587
2588 #ifdef HAVE_POLL
2589       poll_fds[0].fd = csp->cfd;
2590 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2591       if (!watch_client_socket)
2592       {
2593          /*
2594           * Ignore incoming data, but still watch out
2595           * for disconnects etc. These flags are always
2596           * implied anyway but explicitly setting them
2597           * doesn't hurt.
2598           */
2599          poll_fds[0].events = POLLERR|POLLHUP;
2600       }
2601       else
2602 #endif
2603       {
2604          poll_fds[0].events = POLLIN;
2605       }
2606       poll_fds[1].fd = csp->server_connection.sfd;
2607       poll_fds[1].events = POLLIN;
2608       n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2609 #else
2610       timeout.tv_sec = csp->config->socket_timeout;
2611       timeout.tv_usec = 0;
2612       n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2613 #endif /* def HAVE_POLL */
2614
2615       /*server or client not responding in timeout */
2616       if (n == 0)
2617       {
2618          log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2619             csp->config->socket_timeout, http->url);
2620          if ((byte_count == 0) && (http->ssl == 0))
2621          {
2622             send_crunch_response(csp, error_response(csp, "connection-timeout"));
2623          }
2624          mark_server_socket_tainted(csp);
2625 #ifdef FEATURE_HTTPS_INSPECTION
2626          close_client_and_server_ssl_connections(csp);
2627 #endif
2628          return;
2629       }
2630       else if (n < 0)
2631       {
2632 #ifdef HAVE_POLL
2633          log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2634 #else
2635          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2636 #endif
2637          mark_server_socket_tainted(csp);
2638 #ifdef FEATURE_HTTPS_INSPECTION
2639          close_client_and_server_ssl_connections(csp);
2640 #endif
2641          return;
2642       }
2643
2644       /*
2645        * This is the body of the browser's request,
2646        * just read and write it.
2647        *
2648        * Receives data from browser and sends it to server
2649        *
2650        * XXX: Make sure the client doesn't use pipelining
2651        * behind Privoxy's back.
2652        */
2653 #ifdef HAVE_POLL
2654       if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2655       {
2656          log_error(LOG_LEVEL_CONNECT,
2657             "The client socket %d has become unusable while "
2658             "the server socket %d is still open.",
2659             csp->cfd, csp->server_connection.sfd);
2660          mark_server_socket_tainted(csp);
2661          break;
2662       }
2663
2664       if (poll_fds[0].revents != 0)
2665 #else
2666       if (FD_ISSET(csp->cfd, &rfds))
2667 #endif /* def HAVE_POLL*/
2668       {
2669          int max_bytes_to_read = (int)csp->receive_buffer_size;
2670
2671 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2672          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2673          {
2674             if (data_is_available(csp->cfd, 0))
2675             {
2676                /*
2677                 * If the next request is already waiting, we have
2678                 * to stop select()ing the client socket. Otherwise
2679                 * we would always return right away and get nothing
2680                 * else done.
2681                 */
2682                watch_client_socket = 0;
2683                log_error(LOG_LEVEL_CONNECT,
2684                   "Stop watching client socket %d. "
2685                   "There's already another request waiting.",
2686                   csp->cfd);
2687                continue;
2688             }
2689             /*
2690              * If the client socket is set, but there's no data
2691              * available on the socket, the client went fishing
2692              * and continuing talking to the server makes no sense.
2693              */
2694             log_error(LOG_LEVEL_CONNECT,
2695                "The client closed socket %d while "
2696                "the server socket %d is still open.",
2697                csp->cfd, csp->server_connection.sfd);
2698             mark_server_socket_tainted(csp);
2699             break;
2700          }
2701          if (csp->expected_client_content_length != 0)
2702          {
2703             if (csp->expected_client_content_length < csp->receive_buffer_size)
2704             {
2705                max_bytes_to_read = (int)csp->expected_client_content_length;
2706             }
2707             log_error(LOG_LEVEL_CONNECT,
2708                "Waiting for up to %d bytes from the client.",
2709                max_bytes_to_read);
2710          }
2711          assert(max_bytes_to_read <= csp->receive_buffer_size);
2712 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2713
2714 #ifdef FEATURE_HTTPS_INSPECTION
2715          if (client_use_ssl(csp))
2716          {
2717             log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2718             break;
2719          }
2720          else
2721 #endif /* def FEATURE_HTTPS_INSPECTION */
2722          {
2723             len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2724
2725             if (len <= 0)
2726             {
2727                /* XXX: not sure if this is necessary. */
2728                mark_server_socket_tainted(csp);
2729                break; /* "game over, man" */
2730             }
2731
2732 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2733             if (csp->expected_client_content_length != 0)
2734             {
2735                assert(len <= max_bytes_to_read);
2736                csp->expected_client_content_length -= (unsigned)len;
2737                log_error(LOG_LEVEL_CONNECT,
2738                   "Expected client content length set to %llu "
2739                   "after reading %d bytes.",
2740                   csp->expected_client_content_length, len);
2741                if (csp->expected_client_content_length == 0)
2742                {
2743                   log_error(LOG_LEVEL_CONNECT,
2744                      "Done reading from the client.");
2745                   csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2746                }
2747             }
2748 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2749
2750             if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2751             {
2752                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2753                mark_server_socket_tainted(csp);
2754                return;
2755             }
2756          }
2757          continue;
2758       }
2759
2760       /*
2761        * The server wants to talk. It could be the header or the body.
2762        * If `hdr' is null, then it's the header otherwise it's the body.
2763        * FIXME: Does `hdr' really mean `host'? No.
2764        */
2765 #ifdef HAVE_POLL
2766       if (poll_fds[1].revents != 0)
2767 #else
2768       if (FD_ISSET(csp->server_connection.sfd, &rfds))
2769 #endif /* HAVE_POLL */
2770       {
2771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2772          /*
2773           * If we are buffering content, we don't want to eat up to
2774           * buffer-limit bytes if the client no longer cares about them.
2775           * If we aren't buffering, however, a dead client socket will be
2776           * noticed pretty much right away anyway, so we can reduce the
2777           * overhead by skipping the check.
2778           */
2779          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2780          {
2781 #ifdef _WIN32
2782             log_error(LOG_LEVEL_CONNECT,
2783                "The server still wants to talk, but the client may already have hung up on us.");
2784 #else
2785             log_error(LOG_LEVEL_CONNECT,
2786                "The server still wants to talk, but the client hung up on us.");
2787             mark_server_socket_tainted(csp);
2788 #ifdef FEATURE_HTTPS_INSPECTION
2789             close_client_and_server_ssl_connections(csp);
2790 #endif
2791             return;
2792 #endif /* def _WIN32 */
2793          }
2794 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2795
2796 #ifdef FEATURE_HTTPS_INSPECTION
2797          /*
2798           * Reading data from standard or secured connection (HTTP/HTTPS)
2799           */
2800          if (server_use_ssl(csp))
2801          {
2802             len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2803                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2804          }
2805          else
2806 #endif
2807          {
2808             len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2809                (int)csp->receive_buffer_size);
2810          }
2811
2812          if (len < 0)
2813          {
2814             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2815
2816             if ((http->ssl && (csp->fwd == NULL))
2817 #ifdef FEATURE_HTTPS_INSPECTION
2818                && use_ssl_tunnel
2819 #endif
2820                 )
2821             {
2822                /*
2823                 * Just hang up. We already confirmed the client's CONNECT
2824                 * request with status code 200 and unencrypted content is
2825                 * no longer welcome.
2826                 */
2827                log_error(LOG_LEVEL_ERROR,
2828                   "CONNECT already confirmed. Unable to tell the client about the problem.");
2829                return;
2830             }
2831             else if (byte_count)
2832             {
2833                /*
2834                 * Just hang up. We already transmitted the original headers
2835                 * and parts of the original content and therefore missed the
2836                 * chance to send an error message (without risking data corruption).
2837                 *
2838                 * XXX: we could retry with a fancy range request here.
2839                 */
2840                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2841                   "Unable to tell the client about the problem.");
2842                mark_server_socket_tainted(csp);
2843 #ifdef FEATURE_HTTPS_INSPECTION
2844                close_client_and_server_ssl_connections(csp);
2845 #endif
2846                return;
2847             }
2848             /*
2849              * XXX: Consider handling the cases above the same.
2850              */
2851             mark_server_socket_tainted(csp);
2852             len = 0;
2853          }
2854
2855 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2856          if (csp->flags & CSP_FLAG_CHUNKED)
2857          {
2858             if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2859             {
2860                /* XXX: this is a temporary hack */
2861                log_error(LOG_LEVEL_CONNECT,
2862                   "Looks like we reached the end of the last chunk. "
2863                   "We better stop reading.");
2864                csp->expected_content_length = byte_count + (unsigned long long)len;
2865                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2866             }
2867          }
2868          reading_done:
2869 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2870
2871          /*
2872           * This is guaranteed by allocating with zalloc_or_die()
2873           * and never (intentionally) writing to the last byte.
2874           *
2875           * csp->receive_buffer_size is the size of the part of the
2876           * buffer we intentionally write to, but we actually
2877           * allocated csp->receive_buffer_size+1 bytes so the assertion
2878           * stays within the allocated range.
2879           */
2880          assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2881
2882          /*
2883           * Add a trailing zero to let be able to use string operations.
2884           * XXX: do we still need this with filter_popups gone?
2885           */
2886          assert(len <= csp->receive_buffer_size);
2887          csp->receive_buffer[len] = '\0';
2888
2889          /*
2890           * Normally, this would indicate that we've read
2891           * as much as the server has sent us and we can
2892           * close the client connection.  However, Microsoft
2893           * in its wisdom has released IIS/5 with a bug that
2894           * prevents it from sending the trailing \r\n in
2895           * a 302 redirect header (and possibly other headers).
2896           * To work around this if we've haven't parsed
2897           * a full header we'll append a trailing \r\n
2898           * and see if this now generates a valid one.
2899           *
2900           * This hack shouldn't have any impacts.  If we've
2901           * already transmitted the header or if this is a
2902           * SSL connection, then we won't bother with this
2903           * hack.  So we only work on partially received
2904           * headers.  If we append a \r\n and this still
2905           * doesn't generate a valid header, then we won't
2906           * transmit anything to the client.
2907           */
2908          if (len == 0)
2909          {
2910
2911             if (server_body || (http->ssl
2912 #ifdef FEATURE_HTTPS_INSPECTION
2913                   && use_ssl_tunnel
2914 #endif
2915                ))
2916             {
2917                /*
2918                 * If we have been buffering up the document,
2919                 * now is the time to apply content modification
2920                 * and send the result to the client.
2921                 */
2922                if (buffer_and_filter_content)
2923                {
2924                   p = execute_content_filters(csp);
2925                   /*
2926                    * If content filtering fails, use the original
2927                    * buffer and length.
2928                    * (see p != NULL ? p : csp->iob->cur below)
2929                    */
2930                   if (NULL == p)
2931                   {
2932                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2933                   }
2934 #ifdef FEATURE_COMPRESSION
2935                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2936                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2937                   {
2938                      char *compressed_content = compress_buffer(p,
2939                         (size_t *)&csp->content_length, csp->config->compression_level);
2940                      if (compressed_content != NULL)
2941                      {
2942                         freez(p);
2943                         p = compressed_content;
2944                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2945                      }
2946                   }
2947 #endif
2948
2949                   if (JB_ERR_OK != update_server_headers(csp))
2950                   {
2951                      log_error(LOG_LEVEL_FATAL,
2952                         "Failed to update server headers. after filtering.");
2953                   }
2954
2955                   hdr = list_to_text(csp->headers);
2956                   if (hdr == NULL)
2957                   {
2958                      /* FIXME Should handle error properly */
2959                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2960                   }
2961
2962 #ifdef FEATURE_HTTPS_INSPECTION
2963                   /*
2964                    * Sending data with standard or secured connection (HTTP/HTTPS)
2965                    */
2966                   if (client_use_ssl(csp))
2967                   {
2968                      if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2969                               (const unsigned char *)hdr, strlen(hdr),
2970                               get_write_delay(csp)) < 0)
2971                         || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
2972                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2973                               csp->content_length, get_write_delay(csp)) < 0))
2974                      {
2975                         log_error(LOG_LEVEL_ERROR, "write modified content to "
2976                            "client over TLS/SSL failed");
2977                         freez(hdr);
2978                         freez(p);
2979                         mark_server_socket_tainted(csp);
2980                         close_client_and_server_ssl_connections(csp);
2981                         return;
2982                      }
2983                   }
2984                   else
2985 #endif /* def FEATURE_HTTPS_INSPECTION */
2986                   {
2987                      if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2988                       || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2989                          (size_t)csp->content_length, write_delay))
2990                      {
2991                         log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2992                         freez(hdr);
2993                         freez(p);
2994                         mark_server_socket_tainted(csp);
2995                         return;
2996                      }
2997                   }
2998
2999                   freez(hdr);
3000                   freez(p);
3001                }
3002
3003                break; /* "game over, man" */
3004             }
3005
3006             /*
3007              * This is NOT the body, so
3008              * Let's pretend the server just sent us a blank line.
3009              */
3010             snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3011             len = (int)strlen(csp->receive_buffer);
3012
3013             /*
3014              * Now, let the normal header parsing algorithm below do its
3015              * job.  If it fails, we'll exit instead of continuing.
3016              */
3017
3018             ms_iis5_hack = 1;
3019          }
3020
3021          /*
3022           * If we're in the body of the server document, just write it to
3023           * the client, unless we need to buffer the body for later
3024           * content-filtering.
3025           */
3026          if (server_body || (http->ssl
3027 #ifdef FEATURE_HTTPS_INSPECTION
3028                && use_ssl_tunnel
3029 #endif
3030             ))
3031          {
3032             if (buffer_and_filter_content)
3033             {
3034                /*
3035                 * If there is no memory left for buffering the content, or the buffer limit
3036                 * has been reached, switch to non-filtering mode, i.e. make & write the
3037                 * header, flush the iob and buf, and get out of the way.
3038                 */
3039                if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3040                {
3041                   size_t hdrlen;
3042                   long flushed;
3043
3044                   log_error(LOG_LEVEL_INFO,
3045                      "Flushing header and buffers. Stepping back from filtering.");
3046
3047                   hdr = list_to_text(csp->headers);
3048                   if (hdr == NULL)
3049                   {
3050                      /*
3051                       * Memory is too tight to even generate the header.
3052                       * Send our static "Out-of-memory" page.
3053                       */
3054                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3055                      rsp = cgi_error_memory();
3056                      send_crunch_response(csp, rsp);
3057                      mark_server_socket_tainted(csp);
3058 #ifdef FEATURE_HTTPS_INSPECTION
3059                      close_client_and_server_ssl_connections(csp);
3060 #endif
3061                      return;
3062                   }
3063                   hdrlen = strlen(hdr);
3064
3065 #ifdef FEATURE_HTTPS_INSPECTION
3066                   /*
3067                    * Sending data with standard or secured connection (HTTP/HTTPS)
3068                    */
3069                   if (client_use_ssl(csp))
3070                   {
3071                      if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3072                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3073                         || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3074                                 csp->iob)) < 0)
3075                         || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3076                               (const unsigned char *)csp->receive_buffer, (size_t)len,
3077                               get_write_delay(csp)) < 0))
3078                      {
3079                         log_error(LOG_LEVEL_CONNECT,
3080                            "Flush header and buffers to client failed");
3081                         freez(hdr);
3082                         mark_server_socket_tainted(csp);
3083                         close_client_and_server_ssl_connections(csp);
3084                         return;
3085                      }
3086                   }
3087                   else
3088 #endif /* def FEATURE_HTTPS_INSPECTION */
3089                   {
3090                      if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3091                       || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3092                       || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3093                             write_delay))
3094                      {
3095                         log_error(LOG_LEVEL_CONNECT,
3096                            "Flush header and buffers to client failed: %E");
3097                         freez(hdr);
3098                         mark_server_socket_tainted(csp);
3099                         return;
3100                      }
3101                   }
3102
3103                   /*
3104                    * Reset the byte_count to the amount of bytes
3105                    * we just flushed. len will be added a few lines below,
3106                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
3107                    */
3108                   byte_count = (unsigned long long)flushed;
3109                   freez(hdr);
3110                   buffer_and_filter_content = 0;
3111                   server_body = 1;
3112                }
3113             }
3114             else
3115             {
3116 #ifdef FEATURE_HTTPS_INSPECTION
3117                /*
3118                 * Sending data with standard or secured connection (HTTP/HTTPS)
3119                 */
3120                if (client_use_ssl(csp))
3121                {
3122                   ret = ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3123                      (const unsigned char *)csp->receive_buffer, (size_t)len,
3124                      get_write_delay(csp));
3125                   if (ret < 0)
3126                   {
3127                      log_error(LOG_LEVEL_ERROR,
3128                         "Sending data to client failed");
3129                      mark_server_socket_tainted(csp);
3130                      close_client_and_server_ssl_connections(csp);
3131                      return;
3132                   }
3133                }
3134                else
3135 #endif /* def FEATURE_HTTPS_INSPECTION */
3136                {
3137                   if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3138                         (size_t)len, write_delay))
3139                   {
3140                      log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3141                      mark_server_socket_tainted(csp);
3142                      return;
3143                   }
3144                }
3145             }
3146             byte_count += (unsigned long long)len;
3147             continue;
3148          }
3149          else
3150          {
3151             /*
3152              * We're still looking for the end of the server's header.
3153              * Buffer up the data we just read.  If that fails, there's
3154              * little we can do but send our static out-of-memory page.
3155              */
3156             if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3157             {
3158                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3159                rsp = cgi_error_memory();
3160                send_crunch_response(csp, rsp);
3161                mark_server_socket_tainted(csp);
3162 #ifdef FEATURE_HTTPS_INSPECTION
3163                close_client_and_server_ssl_connections(csp);
3164 #endif
3165                return;
3166             }
3167
3168             /* Convert iob into something sed() can digest */
3169             if (JB_ERR_PARSE == get_server_headers(csp))
3170             {
3171                if (ms_iis5_hack)
3172                {
3173                   /*
3174                    * Well, we tried our MS IIS/5 hack and it didn't work.
3175                    * The header is incomplete and there isn't anything
3176                    * we can do about it.
3177                    */
3178                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3179                      "Applying the MS IIS5 hack didn't help.");
3180                   log_error(LOG_LEVEL_CLF,
3181                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3182 #ifdef FEATURE_HTTPS_INSPECTION
3183                   /*
3184                    * Sending data with standard or secured connection (HTTP/HTTPS)
3185                    */
3186                   if (client_use_ssl(csp))
3187                   {
3188                      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3189                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3190                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3191                   }
3192                   else
3193 #endif /* def FEATURE_HTTPS_INSPECTION */
3194                   {
3195                      write_socket_delayed(csp->cfd,
3196                         INVALID_SERVER_HEADERS_RESPONSE,
3197                         strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3198                   }
3199                   mark_server_socket_tainted(csp);
3200 #ifdef FEATURE_HTTPS_INSPECTION
3201                   close_client_and_server_ssl_connections(csp);
3202 #endif
3203                   return;
3204                }
3205                else
3206                {
3207                   /*
3208                    * Since we have to wait for more from the server before
3209                    * we can parse the headers we just continue here.
3210                    */
3211                   log_error(LOG_LEVEL_CONNECT,
3212                      "Continuing buffering server headers from socket %d. "
3213                      "Bytes most recently read: %d.", csp->cfd, len);
3214                   continue;
3215                }
3216             }
3217             else
3218             {
3219                /*
3220                 * Account for the content bytes we
3221                 * might have gotten with the headers.
3222                 */
3223                assert(csp->iob->eod >= csp->iob->cur);
3224                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3225             }
3226
3227             /* Did we actually get anything? */
3228             if (NULL == csp->headers->first)
3229             {
3230                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3231                {
3232                   log_error(LOG_LEVEL_ERROR,
3233                      "No server or forwarder response received on socket %d. "
3234                      "Closing client socket %d without sending data.",
3235                      csp->server_connection.sfd, csp->cfd);
3236                   log_error(LOG_LEVEL_CLF,
3237                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3238                }
3239                else
3240                {
3241                   log_error(LOG_LEVEL_ERROR,
3242                      "No server or forwarder response received on socket %d.",
3243                      csp->server_connection.sfd);
3244                   send_crunch_response(csp, error_response(csp, "no-server-data"));
3245                }
3246                free_http_request(http);
3247                mark_server_socket_tainted(csp);
3248 #ifdef FEATURE_HTTPS_INSPECTION
3249                close_client_and_server_ssl_connections(csp);
3250 #endif
3251                return;
3252             }
3253
3254             if (!csp->headers->first->str)
3255             {
3256                log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3257             }
3258             assert(csp->headers->first->str);
3259
3260             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3261                 strncmpic(csp->headers->first->str, "ICY", 3))
3262             {
3263                /*
3264                 * It doesn't look like a HTTP (or Shoutcast) response:
3265                 * tell the client and log the problem.
3266                 */
3267                if (strlen(csp->headers->first->str) > 30)
3268                {
3269                   csp->headers->first->str[30] = '\0';
3270                }
3271                log_error(LOG_LEVEL_ERROR,
3272                   "Invalid server or forwarder response. Starts with: %s",
3273                   csp->headers->first->str);
3274                log_error(LOG_LEVEL_CLF,
3275                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3276 #ifdef FEATURE_HTTPS_INSPECTION
3277                /*
3278                 * Sending data with standard or secured connection (HTTP/HTTPS)
3279                 */
3280                if (client_use_ssl(csp))
3281                {
3282                   ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3283                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3284                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3285                      get_write_delay(csp));
3286                }
3287                else
3288 #endif /* def FEATURE_HTTPS_INSPECTION */
3289                {
3290                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3291                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3292                }
3293                free_http_request(http);
3294                mark_server_socket_tainted(csp);
3295 #ifdef FEATURE_HTTPS_INSPECTION
3296                close_client_and_server_ssl_connections(csp);
3297 #endif
3298                return;
3299             }
3300
3301             /*
3302              * We have now received the entire server header,
3303              * filter it and send the result to the client
3304              */
3305             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3306             {
3307                log_error(LOG_LEVEL_CLF,
3308                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3309 #ifdef FEATURE_HTTPS_INSPECTION
3310                /*
3311                 * Sending data with standard or secured connection (HTTP/HTTPS)
3312                 */
3313                if (client_use_ssl(csp))
3314                {
3315                   ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3316                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3317                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3318                      get_write_delay(csp));
3319                }
3320                else
3321 #endif
3322                {
3323                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3324                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3325                }
3326                free_http_request(http);
3327                mark_server_socket_tainted(csp);
3328 #ifdef FEATURE_HTTPS_INSPECTION
3329                close_client_and_server_ssl_connections(csp);
3330 #endif
3331                return;
3332             }
3333             hdr = list_to_text(csp->headers);
3334             if (hdr == NULL)
3335             {
3336                /* FIXME Should handle error properly */
3337                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3338             }
3339
3340             if ((csp->flags & CSP_FLAG_CHUNKED)
3341                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3342                && ((csp->iob->eod - csp->iob->cur) >= 5)
3343                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3344             {
3345                log_error(LOG_LEVEL_CONNECT,
3346                   "Looks like we got the last chunk together with "
3347                   "the server headers. We better stop reading.");
3348                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3349                csp->expected_content_length = byte_count;
3350                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3351             }
3352
3353             csp->server_connection.response_received = time(NULL);
3354
3355             if (crunch_response_triggered(csp, crunchers_light))
3356             {
3357                /*
3358                 * One of the tags created by a server-header
3359                 * tagger triggered a crunch. We already
3360                 * delivered the crunch response to the client
3361                 * and are done here after cleaning up.
3362                 */
3363                freez(hdr);
3364                mark_server_socket_tainted(csp);
3365 #ifdef FEATURE_HTTPS_INSPECTION
3366                close_client_and_server_ssl_connections(csp);
3367 #endif
3368                return;
3369             }
3370
3371             /* Buffer and pcrs filter this if appropriate. */
3372             buffer_and_filter_content = content_requires_filtering(csp);
3373
3374             if (!buffer_and_filter_content)
3375             {
3376                /*
3377                 * Write the server's (modified) header to
3378                 * the client (along with anything else that
3379                 * may be in the buffer). Use standard or secured
3380                 * connection.
3381                 */
3382 #ifdef FEATURE_HTTPS_INSPECTION
3383                if (client_use_ssl(csp))
3384                {
3385                   if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3386                           (const unsigned char *)hdr, strlen(hdr),
3387                           get_write_delay(csp)) < 0)
3388                      || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3389                             csp->iob) < 0))
3390                   {
3391                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3392
3393                      /*
3394                       * The write failed, so don't bother mentioning it
3395                       * to the client... it probably can't hear us anyway.
3396                       */
3397                      freez(hdr);
3398                      mark_server_socket_tainted(csp);
3399 #ifdef FEATURE_HTTPS_INSPECTION
3400                      close_client_and_server_ssl_connections(csp);
3401 #endif
3402                      return;
3403                   }
3404                }
3405                else
3406 #endif /* def FEATURE_HTTPS_INSPECTION */
3407                {
3408                   if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3409                      || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3410                   {
3411                      log_error(LOG_LEVEL_ERROR,
3412                         "write header to client failed");
3413                      /*
3414                       * The write failed, so don't bother mentioning it
3415                       * to the client... it probably can't hear us anyway.
3416                       */
3417                      freez(hdr);
3418                      mark_server_socket_tainted(csp);
3419                      return;
3420                   }
3421                }
3422                                 }
3423
3424             /* we're finished with the server's header */
3425
3426             freez(hdr);
3427             server_body = 1;
3428
3429             /*
3430              * If this was a MS IIS/5 hack then it means the server
3431              * has already closed the connection. Nothing more to read.
3432              * Time to bail.
3433              */
3434             if (ms_iis5_hack)
3435             {
3436                log_error(LOG_LEVEL_ERROR,
3437                   "Closed server connection detected. "
3438                   "Applying the MS IIS5 hack didn't help.");
3439                log_error(LOG_LEVEL_CLF,
3440                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3441 #ifdef FEATURE_HTTPS_INSPECTION
3442                /*
3443                 * Sending data with standard or secured connection (HTTP/HTTPS)
3444                 */
3445                if (client_use_ssl(csp))
3446                {
3447                   ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
3448                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3449                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
3450                      get_write_delay(csp));
3451                }
3452                else
3453 #endif /* def FEATURE_HTTPS_INSPECTION */
3454                {
3455                   write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3456                      strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3457                }
3458                mark_server_socket_tainted(csp);
3459 #ifdef FEATURE_HTTPS_INSPECTION
3460                close_client_and_server_ssl_connections(csp);
3461 #endif
3462                return;
3463             }
3464          }
3465          continue;
3466       }
3467       mark_server_socket_tainted(csp);
3468 #ifdef FEATURE_HTTPS_INSPECTION
3469       close_client_and_server_ssl_connections(csp);
3470 #endif
3471       return; /* huh? we should never get here */
3472    }
3473 #ifdef FEATURE_HTTPS_INSPECTION
3474    close_client_and_server_ssl_connections(csp);
3475 #endif
3476    if (csp->content_length == 0)
3477    {
3478       /*
3479        * If Privoxy didn't recalculate the Content-Length,
3480        * byte_count is still correct.
3481        */
3482       csp->content_length = byte_count;
3483    }
3484
3485 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3486    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3487       && (csp->expected_content_length != byte_count))
3488    {
3489       log_error(LOG_LEVEL_CONNECT,
3490          "Received %llu bytes while expecting %llu.",
3491          byte_count, csp->expected_content_length);
3492       mark_server_socket_tainted(csp);
3493    }
3494 #endif
3495
3496 #ifdef FEATURE_HTTPS_INSPECTION
3497    if (client_use_ssl(csp))
3498    {
3499       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3500          csp->ip_addr_str, http->gpc, http->hostport, http->path,
3501          http->version, csp->content_length);
3502    }
3503    else
3504 #endif
3505    {
3506       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3507          csp->ip_addr_str, http->ocmd, csp->content_length);
3508    }
3509    csp->server_connection.timestamp = time(NULL);
3510 }
3511
3512
3513 /*********************************************************************
3514  *
3515  * Function    :  chat
3516  *
3517  * Description :  Once a connection from the client has been accepted,
3518  *                this function is called (via serve()) to handle the
3519  *                main business of the communication.  This function
3520  *                returns after dealing with a single request. It can
3521  *                be called multiple times with the same client socket
3522  *                if the client is keeping the connection alive.
3523  *
3524  *                The decision whether or not a client connection will
3525  *                be kept alive is up to the caller which also must
3526  *                close the client socket when done.
3527  *
3528  *                FIXME: chat is nearly thousand lines long.
3529  *                Ridiculous.
3530  *
3531  * Parameters  :
3532  *          1  :  csp = Current client state (buffers, headers, etc...)
3533  *
3534  * Returns     :  Nothing.
3535  *
3536  *********************************************************************/
3537 static void chat(struct client_state *csp)
3538 {
3539    const struct forward_spec *fwd;
3540    struct http_request *http;
3541    /* Skeleton for HTTP response, if we should intercept the request */
3542    struct http_response *rsp;
3543 #ifdef FEATURE_HTTPS_INSPECTION
3544    int use_ssl_tunnel = 0;
3545 #endif
3546
3547    http = csp->http;
3548
3549    if (receive_client_request(csp) != JB_ERR_OK)
3550    {
3551       return;
3552    }
3553    if (parse_client_request(csp) != JB_ERR_OK)
3554    {
3555       return;
3556    }
3557
3558    /* decide how to route the HTTP request */
3559    fwd = forward_url(csp, http);
3560    if (NULL == fwd)
3561    {
3562       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
3563       /* Never get here - LOG_LEVEL_FATAL causes program exit */
3564       return;
3565    }
3566
3567 #ifdef FEATURE_HTTPS_INSPECTION
3568    /*
3569     * Setting flags to use old solution with SSL tunnel and to disable
3570     * certificate verification.
3571     */
3572    if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3573       && !cgi_page_requested(csp->http->host))
3574    {
3575       use_ssl_tunnel = 1;
3576    }
3577
3578    if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3579    {
3580       csp->dont_verify_certificate = 1;
3581    }
3582 #endif
3583
3584    /*
3585     * build the http request to send to the server
3586     * we have to do one of the following:
3587     *
3588     * create =    use the original HTTP request to create a new
3589     *             HTTP request that has either the path component
3590     *             without the http://domainspec (w/path) or the
3591     *             full orininal URL (w/url)
3592     *             Note that the path and/or the HTTP version may
3593     *             have been altered by now.
3594     *
3595     * SSL proxy = Open a socket to the host:port of the server
3596     *             and create TLS/SSL connection with server and
3597     *             with client. Then behave like mediator between
3598     *             client and server over TLS/SSL.
3599     *
3600     * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3601     *    with     request to a parent proxy. Note that we'll be sending
3602     * forwarding  the CFAIL message ourselves if connecting to the parent
3603     *             fails, but we won't send a CSUCCEED message if it works,
3604     *             since that would result in a double message (ours and the
3605     *             parent's). After sending the request to the parent, we
3606     *             must parse answer and send it to client. If connection
3607     *             with server is established, we do TLS/SSL proxy. Otherwise
3608     *             we send parent response to client and close connections.
3609     *
3610     * here's the matrix:
3611     *                        SSL
3612     *                    0        1
3613     *                +--------+--------+
3614     *                |        |        |
3615     *             0  | create |   SSL  |
3616     *                | w/path |  proxy |
3617     *  Forwarding    +--------+--------+
3618     *                |        |   SSL  |
3619     *             1  | create |  proxy |
3620     *                | w/url  |+forward|
3621     *                +--------+--------+
3622     *
3623     */
3624
3625 #ifdef FEATURE_HTTPS_INSPECTION
3626    /*
3627     * Presetting SSL client and server flags
3628     */
3629    if (http->ssl && !use_ssl_tunnel)
3630    {
3631       http->client_ssl = 1;
3632       http->server_ssl = 1;
3633    }
3634    else
3635    {
3636       http->client_ssl = 0;
3637       http->server_ssl = 0;
3638    }
3639 #endif
3640
3641 #ifdef FEATURE_HTTPS_INSPECTION
3642    /*
3643     * Log the request unless we're https inspecting
3644     * in which case we don't have the path yet and
3645     * will log the request later.
3646     */
3647    if (!client_use_ssl(csp))
3648 #endif
3649    {
3650       log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3651    }
3652
3653    if (http->ssl && connect_port_is_forbidden(csp))
3654    {
3655       const char *acceptable_connect_ports =
3656          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3657       assert(NULL != acceptable_connect_ports);
3658       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3659          "limit-connect{%s} doesn't allow CONNECT requests to %s",
3660          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3661       csp->action->flags |= ACTION_BLOCK;
3662       http->ssl = 0;
3663 #ifdef FEATURE_HTTPS_INSPECTION
3664       http->client_ssl = 0;
3665       http->server_ssl = 0;
3666 #endif
3667    }
3668
3669
3670    freez(csp->headers->first->str);
3671    build_request_line(csp, fwd, &csp->headers->first->str);
3672
3673    /*
3674     * We have a request. Check if one of the crunchers wants it
3675     * unless the client wants to use TLS/SSL in which case we
3676     * haven't setup the TLS context yet and will send the crunch
3677     * response later.
3678     */
3679    if (
3680 #ifdef FEATURE_HTTPS_INSPECTION
3681        !client_use_ssl(csp) &&
3682 #endif
3683        crunch_response_triggered(csp, crunchers_all))
3684    {
3685       /*
3686        * Yes. The client got the crunch response and we're done here.
3687        */
3688       return;
3689    }
3690
3691    log_applied_actions(csp->action);
3692    if (fwd->forward_host)
3693    {
3694       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3695          fwd->forward_host, fwd->forward_port, http->hostport);
3696    }
3697    else
3698    {
3699       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3700    }
3701
3702    /* here we connect to the server, gateway, or the forwarder */
3703
3704 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3705    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3706       && socket_is_still_alive(csp->server_connection.sfd)
3707       && connection_destination_matches(&csp->server_connection, http, fwd))
3708    {
3709       log_error(LOG_LEVEL_CONNECT,
3710          "Reusing server socket %d connected to %s. Total requests: %u.",
3711          csp->server_connection.sfd, csp->server_connection.host,
3712          csp->server_connection.requests_sent_total);
3713    }
3714    else
3715    {
3716       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3717       {
3718 #ifdef FEATURE_CONNECTION_SHARING
3719          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3720          {
3721             remember_connection(&csp->server_connection);
3722          }
3723          else
3724 #endif /* def FEATURE_CONNECTION_SHARING */
3725          {
3726             log_error(LOG_LEVEL_CONNECT,
3727                "Closing server socket %d connected to %s. Total requests: %u.",
3728                csp->server_connection.sfd, csp->server_connection.host,
3729                csp->server_connection.requests_sent_total);
3730             close_socket(csp->server_connection.sfd);
3731          }
3732          mark_connection_closed(&csp->server_connection);
3733       }
3734 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3735 #ifdef FEATURE_HTTPS_INSPECTION
3736       if (http->ssl && !use_ssl_tunnel)
3737       {
3738          int ret;
3739          /*
3740           * Creating a SSL proxy.
3741           *
3742           * By sending the CSUCCEED message we're lying to the client as
3743           * the connection hasn't actually been established yet. We don't
3744           * establish the connection until we have seen and parsed the
3745           * encrypted client headers.
3746           */
3747          if (write_socket_delayed(csp->cfd, CSUCCEED,
3748                strlen(CSUCCEED), get_write_delay(csp)) != 0)
3749          {
3750             log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3751             return;
3752          }
3753
3754          ret = create_client_ssl_connection(csp);
3755          if (ret != 0)
3756          {
3757             log_error(LOG_LEVEL_ERROR,
3758                "Failed to open a secure connection with the client");
3759             return;
3760          }
3761          if (JB_ERR_OK != process_encrypted_request(csp))
3762          {
3763             log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3764             close_client_ssl_connection(csp);
3765             return;
3766          }
3767          /*
3768           * We have an encrypted request. Check if one of the crunchers now
3769           * wants it (for example because the previously invisible path was
3770           * required to match).
3771           */
3772          if (crunch_response_triggered(csp, crunchers_all))
3773          {
3774             /*
3775      &nbs