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