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