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