1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2021 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
105 #ifdef FEATURE_HTTPS_INSPECTION
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
124 struct client_states clients[1];
125 struct file_list files[1];
127 #ifdef FEATURE_STATISTICS
128 int urls_read = 0; /* total nr of urls read inc rejected */
129 int urls_rejected = 0; /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
132 #ifdef FEATURE_GRACEFUL_TERMINATION
137 static void sig_handler(int the_signal);
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
167 #define sleep(N) Sleep(((N) * 1000))
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225 "HTTP/1.1 200 Connection established\r\n\r\n";
227 static const char CHEADER[] =
228 "HTTP/1.1 400 Invalid header received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid header received from client.\n";
233 static const char FTP_RESPONSE[] =
234 "HTTP/1.1 400 Invalid request received from client\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Invalid request. Privoxy doesn't support FTP.\n";
239 static const char GOPHER_RESPONSE[] =
240 "HTTP/1.1 400 Invalid request received from client\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Invalid request. Privoxy doesn't support gopher.\n";
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247 "HTTP/1.1 400 Bad request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Bad request. Privoxy was unable to extract the destination.\n";
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Bad response. The server or forwarder response doesn't look like HTTP.\n";
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261 "HTTP/1.1 400 Malformed request after rewriting\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad request. Messed up with header filters.\n";
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267 "HTTP/1.1 503 Too many open connections\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Maximum number of open connections reached.\n";
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273 "HTTP/1.1 504 Connection timeout\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "The connection timed out because the client request didn't arrive in time.\n";
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279 "HTTP/1.1 400 Failed reading client body\r\n"
280 "Content-Type: text/plain\r\n"
281 "Connection: close\r\n\r\n"
282 "Failed parsing or buffering the chunk-encoded client body.\n";
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285 "HTTP/1.1 417 Expecting too much\r\n"
286 "Content-Type: text/plain\r\n"
287 "Connection: close\r\n\r\n"
288 "Privoxy detected an unsupported Expect header value.\n";
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
293 /* Crunch function flags */
294 #define CF_NO_FLAGS 0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE 1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
300 /* A crunch function and its flags */
303 const crunch_func_ptr cruncher;
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312 { block_url, CF_COUNT_AS_REJECT },
314 { trust_url, CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316 { redirect_url, CF_NO_FLAGS },
317 { dispatch_cgi, CF_IGNORE_FORCE},
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323 { block_url, CF_COUNT_AS_REJECT },
324 { redirect_url, CF_NO_FLAGS },
330 * XXX: Don't we really mean
337 /*********************************************************************
339 * Function : sig_handler
341 * Description : Signal handler for different signals.
342 * Exit gracefully on TERM and INT
343 * or set a flag that will cause the errlog
344 * to be reopened by the main thread on HUP.
347 * 1 : the_signal = the signal cause this function to call
351 *********************************************************************/
352 static void sig_handler(int the_signal)
358 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
370 received_hup_signal = 1;
376 * We shouldn't be here, unless we catch signals
377 * in main() that we can't handle here!
379 log_error(LOG_LEVEL_FATAL,
380 "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : get_write_delay
392 * Description : Parse the delay-response parameter.
395 * 1 : csp = Current client state (buffers, headers, etc...)
397 * Returns : Number of milliseconds to delay writes.
399 *********************************************************************/
400 static unsigned int get_write_delay(const struct client_state *csp)
406 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
410 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
412 delay = (unsigned)strtol(newval, &endptr, 0);
415 log_error(LOG_LEVEL_FATAL,
416 "Invalid delay-response{} parameter: '%s'", newval);
424 /*********************************************************************
426 * Function : client_protocol_is_unsupported
428 * Description : Checks if the client used a known unsupported
429 * protocol and deals with it by sending an error
433 * 1 : csp = Current client state (buffers, headers, etc...)
434 * 2 : req = the first request line send by the client
436 * Returns : TRUE if an error response has been generated, or
437 * FALSE if the request doesn't look invalid.
439 *********************************************************************/
440 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
443 * If it's a FTP or gopher request, we don't support it.
445 * These checks are better than nothing, but they might
446 * not work in all configurations and some clients might
447 * have problems digesting the answer.
449 * They should, however, never cause more problems than
450 * Privoxy's old behaviour (returning the misleading HTML
453 * "Could not resolve http://(ftp|gopher)://example.org").
455 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
457 const char *response = NULL;
458 const char *protocol = NULL;
460 if (!strncmpic(req, "GET ftp://", 10))
462 response = FTP_RESPONSE;
467 response = GOPHER_RESPONSE;
470 log_error(LOG_LEVEL_ERROR,
471 "%s tried to use Privoxy as %s proxy: %s",
472 csp->ip_addr_str, protocol, req);
473 log_error(LOG_LEVEL_CLF,
474 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
477 #ifdef FEATURE_HTTPS_INSPECTION
478 if (client_use_ssl(csp))
480 ssl_send_data_delayed(&(csp->ssl_client_attr),
481 (const unsigned char *)response, strlen(response),
482 get_write_delay(csp));
487 write_socket_delayed(csp->cfd, response, strlen(response),
488 get_write_delay(csp));
498 /*********************************************************************
500 * Function : client_has_unsupported_expectations
502 * Description : Checks if the client used an unsupported expectation
503 * in which case an error message is delivered.
506 * 1 : csp = Current client state (buffers, headers, etc...)
508 * Returns : TRUE if an error response has been generated, or
509 * FALSE if the request doesn't look invalid.
511 *********************************************************************/
512 static int client_has_unsupported_expectations(const struct client_state *csp)
514 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
516 log_error(LOG_LEVEL_ERROR,
517 "Rejecting request from client %s with unsupported Expect header value",
519 log_error(LOG_LEVEL_CLF,
520 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
521 write_socket_delayed(csp->cfd,
522 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
523 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
524 get_write_delay(csp));
534 /*********************************************************************
536 * Function : get_request_destination_elsewhere
538 * Description : If the client's request was redirected into
539 * Privoxy without the client's knowledge,
540 * the request line lacks the destination host.
542 * This function tries to get it elsewhere,
543 * provided accept-intercepted-requests is enabled.
545 * "Elsewhere" currently only means "Host: header",
546 * but in the future we may ask the redirecting
547 * packet filter to look the destination up.
549 * If the destination stays unknown, an error
550 * response is send to the client and headers
551 * are freed so that chat() can return directly.
554 * 1 : csp = Current client state (buffers, headers, etc...)
555 * 2 : headers = a header list
557 * Returns : JB_ERR_OK if the destination is now known, or
558 * JB_ERR_PARSE if it isn't.
560 *********************************************************************/
561 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
563 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
565 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
566 " Privoxy isn't configured to accept intercepted requests.",
567 csp->ip_addr_str, csp->http->cmd);
568 /* XXX: Use correct size */
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
570 csp->ip_addr_str, csp->http->cmd);
572 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
573 get_write_delay(csp));
574 destroy_list(headers);
578 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
580 /* Split the domain we just got for pattern matching */
581 init_domain_components(csp->http);
587 /* We can't work without destination. Go spread the news.*/
589 /* XXX: Use correct size */
590 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
591 csp->ip_addr_str, csp->http->cmd);
592 log_error(LOG_LEVEL_ERROR,
593 "Privoxy was unable to get the destination for %s's request: %s",
594 csp->ip_addr_str, csp->http->cmd);
596 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
597 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
598 destroy_list(headers);
603 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
604 * to get the destination IP address, use it as host directly
605 * or do a reverse DNS lookup first.
610 /*********************************************************************
612 * Function : get_server_headers
614 * Description : Parses server headers in iob and fills them
615 * into csp->headers so that they can later be
619 * 1 : csp = Current client state (buffers, headers, etc...)
621 * Returns : JB_ERR_OK if everything went fine, or
622 * JB_ERR_PARSE if the headers were incomplete.
624 *********************************************************************/
625 static jb_err get_server_headers(struct client_state *csp)
627 int continue_hack_in_da_house = 0;
630 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
635 * continue hack in da house. Ignore the ending of
636 * this head and continue enlisting header lines.
637 * The reason is described below.
639 enlist(csp->headers, "");
640 continue_hack_in_da_house = 0;
643 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
646 * It's a bodyless continue response, don't
647 * stop header parsing after reaching its end.
649 * As a result Privoxy will concatenate the
650 * next response's head and parse and deliver
651 * the headers as if they belonged to one request.
653 * The client will separate them because of the
654 * empty line between them.
656 * XXX: What we're doing here is clearly against
657 * the intended purpose of the continue header,
658 * and under some conditions (HTTP/1.0 client request)
659 * it's a standard violation.
661 * Anyway, "sort of against the spec" is preferable
662 * to "always getting confused by Continue responses"
663 * (Privoxy's behaviour before this hack was added)
665 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
666 continue_hack_in_da_house = 1;
668 else if (*header == '\0')
671 * If the header is empty, but the Continue hack
672 * isn't active, we can assume that we reached the
673 * end of the buffer before we hit the end of the
676 * Inform the caller an let it decide how to handle it.
681 if (JB_ERR_MEMORY == enlist(csp->headers, header))
684 * XXX: Should we quit the request and return a
685 * out of memory error page instead?
687 log_error(LOG_LEVEL_ERROR,
688 "Out of memory while enlisting server headers. %s lost.",
698 /*********************************************************************
700 * Function : crunch_reason
702 * Description : Translates the crunch reason code into a string.
705 * 1 : rsp = a http_response
707 * Returns : A string with the crunch reason or an error description.
709 *********************************************************************/
710 static const char *crunch_reason(const struct http_response *rsp)
712 char * reason = NULL;
717 return "Internal error while searching for crunch reason";
720 switch (rsp->crunch_reason)
723 reason = "Unsupported HTTP feature";
729 reason = "Untrusted";
732 reason = "Redirected";
738 reason = "DNS failure";
740 case FORWARDING_FAILED:
741 reason = "Forwarding failed";
744 reason = "Connection failure";
747 reason = "Out of memory (may mask other reasons)";
749 case CONNECTION_TIMEOUT:
750 reason = "Connection timeout";
753 reason = "No server data received";
756 reason = "No reason recorded";
764 /*********************************************************************
766 * Function : log_applied_actions
768 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
772 * 1 : actions = Current action spec to log
776 *********************************************************************/
777 static void log_applied_actions(const struct current_action_spec *actions)
780 * The conversion to text requires lots of memory allocations so
781 * we only do the conversion if the user is actually interested.
783 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
785 char *actions_as_text = actions_to_line_of_text(actions);
786 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
787 freez(actions_as_text);
792 /*********************************************************************
794 * Function : send_crunch_response
796 * Description : Delivers already prepared response for
797 * intercepted requests, logs the interception
798 * and frees the response.
801 * 1 : csp = Current client state (buffers, headers, etc...)
802 * 2 : rsp = Fully prepared response. Will be freed on exit.
806 *********************************************************************/
807 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
809 const struct http_request *http = csp->http;
813 assert(rsp->head != NULL);
817 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
821 * Extract the status code from the actual head
822 * that will be send to the client. It is the only
823 * way to get it right for all requests, including
824 * the fixed ones for out-of-memory problems.
826 * A head starts like this: 'HTTP/1.1 200...'
830 status_code[0] = rsp->head[9];
831 status_code[1] = rsp->head[10];
832 status_code[2] = rsp->head[11];
833 status_code[3] = '\0';
835 /* Log that the request was crunched and why. */
836 log_applied_actions(csp->action);
837 #ifdef FEATURE_HTTPS_INSPECTION
838 if (client_use_ssl(csp))
840 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
841 http->hostport, http->path);
842 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
843 csp->ip_addr_str, http->gpc, http->hostport, http->path,
844 http->version, status_code, rsp->content_length);
849 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
850 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
851 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
853 /* Write the answer to the client */
854 #ifdef FEATURE_HTTPS_INSPECTION
855 if (client_use_ssl(csp))
857 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
858 (const unsigned char *)rsp->head, rsp->head_length,
859 get_write_delay(csp)) < 0)
860 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
861 (const unsigned char *)rsp->body, rsp->content_length,
862 get_write_delay(csp)) < 0))
864 /* There is nothing we can do about it. */
865 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
866 "for https://%s%s through client socket %d using TLS/SSL",
867 http->hostport, http->url, csp->cfd);
873 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
874 get_write_delay(csp))
875 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
876 get_write_delay(csp)))
878 /* There is nothing we can do about it. */
879 log_error(LOG_LEVEL_CONNECT,
880 "Couldn't deliver the error message for %s through client socket %d: %E",
881 http->url, csp->cfd);
885 /* Clean up and return */
886 if (cgi_error_memory() != rsp)
888 free_http_response(rsp);
894 /*********************************************************************
896 * Function : crunch_response_triggered
898 * Description : Checks if the request has to be crunched,
899 * and delivers the crunch response if necessary.
902 * 1 : csp = Current client state (buffers, headers, etc...)
903 * 2 : crunchers = list of cruncher functions to run
905 * Returns : TRUE if the request was answered with a crunch response
908 *********************************************************************/
909 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
911 struct http_response *rsp = NULL;
912 const struct cruncher *c;
915 * If CGI request crunching is disabled,
916 * check the CGI dispatcher out of order to
917 * prevent unintentional blocks or redirects.
919 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
920 && (NULL != (rsp = dispatch_cgi(csp))))
922 /* Deliver, log and free the interception response. */
923 send_crunch_response(csp, rsp);
924 csp->flags |= CSP_FLAG_CRUNCHED;
928 for (c = crunchers; c->cruncher != NULL; c++)
931 * Check the cruncher if either Privoxy is toggled
932 * on and the request isn't forced, or if the cruncher
933 * applies to forced requests as well.
935 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
936 !(csp->flags & CSP_FLAG_FORCED)) ||
937 (c->flags & CF_IGNORE_FORCE))
939 rsp = c->cruncher(csp);
942 /* Deliver, log and free the interception response. */
943 send_crunch_response(csp, rsp);
944 csp->flags |= CSP_FLAG_CRUNCHED;
945 #ifdef FEATURE_STATISTICS
946 if (c->flags & CF_COUNT_AS_REJECT)
948 csp->flags |= CSP_FLAG_REJECTED;
950 #endif /* def FEATURE_STATISTICS */
961 /*********************************************************************
963 * Function : build_request_line
965 * Description : Builds the HTTP request line.
967 * If a HTTP forwarder is used it expects the whole URL,
968 * web servers only get the path.
971 * 1 : csp = Current client state (buffers, headers, etc...)
972 * 2 : fwd = The forwarding spec used for the request.
974 * 3 : request_line = The old request line which will be replaced.
976 * Returns : Nothing. Terminates in case of memory problems.
978 *********************************************************************/
979 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
981 struct http_request *http = csp->http;
984 * Downgrade http version from 1.1 to 1.0
985 * if +downgrade action applies.
987 if ((csp->action->flags & ACTION_DOWNGRADE)
988 && (!strcmpic(http->version, "HTTP/1.1")))
990 freez(http->version);
991 http->version = strdup_or_die("HTTP/1.0");
995 * Rebuild the request line.
997 freez(*request_line);
998 #ifdef FEATURE_HTTPS_INSPECTION
999 if (fwd != NULL && fwd->forward_host &&
1000 fwd->type != FORWARD_WEBSERVER && client_use_ssl(csp))
1002 *request_line = strdup("CONNECT ");
1007 *request_line = strdup(http->gpc);
1008 string_append(request_line, " ");
1011 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1013 #ifdef FEATURE_HTTPS_INSPECTION
1014 if (client_use_ssl(csp))
1016 char port_string[10];
1018 string_append(request_line, http->host);
1019 snprintf(port_string, sizeof(port_string), ":%d", http->port);
1020 string_append(request_line, port_string);
1025 string_append(request_line, http->url);
1030 string_append(request_line, http->path);
1032 string_append(request_line, " ");
1033 string_append(request_line, http->version);
1035 if (*request_line == NULL)
1037 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1039 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1043 /*********************************************************************
1045 * Function : change_request_destination
1047 * Description : Parse a (rewritten) request line and regenerate
1048 * the http request data.
1051 * 1 : csp = Current client state (buffers, headers, etc...)
1053 * Returns : Forwards the parse_http_request() return code.
1054 * Terminates in case of memory problems.
1056 *********************************************************************/
1057 static jb_err change_request_destination(struct client_state *csp)
1059 struct http_request *http = csp->http;
1062 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1063 csp->headers->first->str);
1064 free_http_request(http);
1065 err = parse_http_request(csp->headers->first->str, http);
1066 if (JB_ERR_OK != err)
1068 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1069 jb_err_to_string(err));
1071 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1074 * A client header filter changed the request URL from
1075 * http:// to https:// which we currently don't support.
1077 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1078 "to https behind the client's back currently isn't supported.");
1079 return JB_ERR_PARSE;
1086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1087 /*********************************************************************
1089 * Function : server_response_is_complete
1091 * Description : Determines whether we should stop reading
1092 * from the server socket.
1095 * 1 : csp = Current client state (buffers, headers, etc...)
1096 * 2 : content_length = Length of content received so far.
1098 * Returns : TRUE if the response is complete,
1101 *********************************************************************/
1102 static int server_response_is_complete(struct client_state *csp,
1103 unsigned long long content_length)
1105 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1107 if (!strcmpic(csp->http->gpc, "HEAD"))
1110 * "HEAD" implies no body, we are thus expecting
1111 * no content. XXX: incomplete "list" of methods?
1113 csp->expected_content_length = 0;
1114 content_length_known = TRUE;
1115 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1118 if (csp->http->status == 204 || csp->http->status == 304)
1121 * Expect no body. XXX: incomplete "list" of status codes?
1123 csp->expected_content_length = 0;
1124 content_length_known = TRUE;
1125 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1128 return (content_length_known && ((0 == csp->expected_content_length)
1129 || (csp->expected_content_length <= content_length)));
1133 #ifdef FEATURE_CONNECTION_SHARING
1134 /*********************************************************************
1136 * Function : wait_for_alive_connections
1138 * Description : Waits for alive connections to timeout.
1144 *********************************************************************/
1145 static void wait_for_alive_connections(void)
1147 int connections_alive = close_unusable_connections();
1149 while (0 < connections_alive)
1151 log_error(LOG_LEVEL_CONNECT,
1152 "Waiting for %d connections to timeout.",
1155 connections_alive = close_unusable_connections();
1158 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1161 #endif /* def FEATURE_CONNECTION_SHARING */
1164 /*********************************************************************
1166 * Function : save_connection_destination
1168 * Description : Remembers a connection for reuse later on.
1171 * 1 : sfd = Open socket to remember.
1172 * 2 : http = The destination for the connection.
1173 * 3 : fwd = The forwarder settings used.
1174 * 4 : server_connection = storage.
1178 *********************************************************************/
1179 static void save_connection_destination(jb_socket sfd,
1180 const struct http_request *http,
1181 const struct forward_spec *fwd,
1182 struct reusable_connection *server_connection)
1184 assert(sfd != JB_INVALID_SOCKET);
1185 assert(NULL != http->host);
1187 server_connection->sfd = sfd;
1188 server_connection->host = strdup_or_die(http->host);
1189 server_connection->port = http->port;
1191 assert(NULL != fwd);
1192 assert(server_connection->gateway_host == NULL);
1193 assert(server_connection->gateway_port == 0);
1194 assert(server_connection->forwarder_type == 0);
1195 assert(server_connection->forward_host == NULL);
1196 assert(server_connection->forward_port == 0);
1198 server_connection->forwarder_type = fwd->type;
1199 if (NULL != fwd->gateway_host)
1201 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1205 server_connection->gateway_host = NULL;
1207 server_connection->gateway_port = fwd->gateway_port;
1208 if (NULL != fwd->auth_username)
1210 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1214 server_connection->auth_username = NULL;
1216 if (NULL != fwd->auth_password)
1218 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1222 server_connection->auth_password = NULL;
1225 if (NULL != fwd->forward_host)
1227 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1231 server_connection->forward_host = NULL;
1233 server_connection->forward_port = fwd->forward_port;
1235 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1238 /*********************************************************************
1240 * Function : verify_request_length
1242 * Description : Checks if we already got the whole client requests
1243 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1246 * Data that doesn't belong to the current request is
1247 * either thrown away to let the client retry on a clean
1248 * socket, or stashed to be dealt with after the current
1249 * request is served.
1252 * 1 : csp = Current client state (buffers, headers, etc...)
1256 *********************************************************************/
1257 static void verify_request_length(struct client_state *csp)
1259 unsigned long long buffered_request_bytes =
1260 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1262 if ((csp->expected_client_content_length != 0)
1263 && (buffered_request_bytes != 0))
1265 if (csp->expected_client_content_length >= buffered_request_bytes)
1267 csp->expected_client_content_length -= buffered_request_bytes;
1268 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1269 "to account for the %llu ones we already got.",
1270 csp->expected_client_content_length, buffered_request_bytes);
1274 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1275 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1276 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1277 "Marking the server socket tainted after throwing %llu bytes away.",
1278 buffered_request_bytes - csp->expected_client_content_length);
1279 csp->expected_client_content_length = 0;
1280 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1283 if (csp->expected_client_content_length == 0)
1285 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1289 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1290 && ((csp->client_iob->cur < csp->client_iob->eod)
1291 || (csp->expected_client_content_length != 0)))
1293 if (strcmpic(csp->http->gpc, "GET")
1294 && strcmpic(csp->http->gpc, "HEAD")
1295 && strcmpic(csp->http->gpc, "TRACE")
1296 && strcmpic(csp->http->gpc, "OPTIONS")
1297 && strcmpic(csp->http->gpc, "DELETE"))
1299 /* XXX: this is an incomplete hack */
1300 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1301 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1305 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1307 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1309 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1310 log_error(LOG_LEVEL_CONNECT,
1311 "Possible pipeline attempt detected. The connection will not "
1312 "be kept alive and we will only serve the first request.");
1313 /* Nuke the pipelined requests from orbit, just to be sure. */
1314 clear_iob(csp->client_iob);
1319 * Keep the pipelined data around for now, we'll deal with
1320 * it once we're done serving the current request.
1322 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1323 assert(csp->client_iob->eod >= csp->client_iob->cur);
1324 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1325 "%d bytes of pipelined data received.",
1326 (int)(csp->client_iob->eod - csp->client_iob->cur));
1332 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1333 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1338 /*********************************************************************
1340 * Function : mark_server_socket_tainted
1342 * Description : Makes sure we don't reuse a server socket
1343 * (if we didn't read everything the server sent
1344 * us reusing the socket would lead to garbage).
1347 * 1 : csp = Current client state (buffers, headers, etc...)
1351 *********************************************************************/
1352 static void mark_server_socket_tainted(struct client_state *csp)
1355 * For consistency we always mark the server socket
1356 * tainted, however, to reduce the log noise we only
1357 * emit a log message if the server socket could have
1358 * actually been reused.
1360 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1361 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1363 log_error(LOG_LEVEL_CONNECT,
1364 "Marking the server socket %d tainted.",
1365 csp->server_connection.sfd);
1367 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1370 /*********************************************************************
1372 * Function : get_request_line
1374 * Description : Read the client request line.
1377 * 1 : csp = Current client state (buffers, headers, etc...)
1379 * Returns : Pointer to request line or NULL in case of errors.
1381 *********************************************************************/
1382 static char *get_request_line(struct client_state *csp)
1384 char buf[BUFFER_SIZE];
1385 char *request_line = NULL;
1388 memset(buf, 0, sizeof(buf));
1390 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1393 * If there are multiple pipelined requests waiting,
1394 * the flag will be set again once the next request
1397 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1399 request_line = get_header(csp->client_iob);
1400 if ((NULL != request_line) && ('\0' != *request_line))
1402 return request_line;
1406 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1407 "received yet. Continuing reading from %d.", csp->cfd);
1415 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1417 !data_is_available(csp->cfd, csp->config->socket_timeout)
1420 if (socket_is_still_alive(csp->cfd))
1422 log_error(LOG_LEVEL_CONNECT,
1423 "No request line on socket %d received in time. Timeout: %d.",
1424 csp->cfd, csp->config->socket_timeout);
1425 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1426 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1427 get_write_delay(csp));
1431 log_error(LOG_LEVEL_CONNECT,
1432 "The client side of the connection on socket %d got "
1433 "closed without sending a complete request line.", csp->cfd);
1438 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1440 if (len <= 0) return NULL;
1443 * If there is no memory left for buffering the
1444 * request, there is nothing we can do but hang up
1446 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1451 request_line = get_header(csp->client_iob);
1453 } while ((NULL != request_line) && ('\0' == *request_line));
1455 return request_line;
1461 CHUNK_STATUS_MISSING_DATA,
1462 CHUNK_STATUS_BODY_COMPLETE,
1463 CHUNK_STATUS_PARSE_ERROR
1467 /*********************************************************************
1469 * Function : chunked_body_is_complete
1471 * Description : Figures out whether or not a chunked body is complete.
1473 * Currently it always starts at the beginning of the
1474 * buffer which is somewhat wasteful and prevents Privoxy
1475 * from starting to forward the correctly parsed chunks
1476 * as soon as theoretically possible.
1478 * Should be modified to work with a common buffer,
1479 * and allow the caller to skip already parsed chunks.
1481 * This would allow the function to be used for unbuffered
1482 * response bodies as well.
1485 * 1 : iob = Buffer with the body to check.
1486 * 2 : length = Length of complete body
1488 * Returns : Enum with the result of the check.
1490 *********************************************************************/
1491 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1493 unsigned int chunksize;
1499 * We need at least a single digit, followed by "\r\n",
1500 * followed by an unknown amount of data, followed by "\r\n".
1502 if (p + 5 > iob->eod)
1504 return CHUNK_STATUS_MISSING_DATA;
1506 if (sscanf(p, "%x", &chunksize) != 1)
1508 return CHUNK_STATUS_PARSE_ERROR;
1512 * We want at least a single digit, followed by "\r\n",
1513 * followed by the specified amount of data, followed by "\r\n".
1515 if (p + chunksize + 5 > iob->eod)
1517 return CHUNK_STATUS_MISSING_DATA;
1520 /* Skip chunk-size. */
1521 p = strstr(p, "\r\n");
1524 return CHUNK_STATUS_PARSE_ERROR;
1526 /* Move beyond the chunkdata. */
1529 /* Make sure we're still within the buffer and have two bytes left */
1530 if (p + 2 > iob->eod)
1532 return CHUNK_STATUS_MISSING_DATA;
1535 /* There should be another "\r\n" to skip */
1536 if (memcmp(p, "\r\n", 2))
1538 return CHUNK_STATUS_PARSE_ERROR;
1541 } while (chunksize > 0U);
1543 *length = (size_t)(p - iob->cur);
1544 assert(*length <= (size_t)(iob->eod - iob->cur));
1545 assert(p <= iob->eod);
1547 return CHUNK_STATUS_BODY_COMPLETE;
1552 /*********************************************************************
1554 * Function : receive_chunked_client_request_body
1556 * Description : Read the chunk-encoded client request body.
1557 * Failures are dealt with.
1560 * 1 : csp = Current client state (buffers, headers, etc...)
1562 * Returns : JB_ERR_OK or JB_ERR_PARSE
1564 *********************************************************************/
1565 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1568 enum chunk_status status;
1570 while (CHUNK_STATUS_MISSING_DATA ==
1571 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1573 char buf[BUFFER_SIZE];
1576 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1578 log_error(LOG_LEVEL_ERROR,
1579 "Timeout while waiting for the client body.");
1582 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1585 log_error(LOG_LEVEL_ERROR,
1586 "Reading the client body failed: %E");
1589 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1594 if (status != CHUNK_STATUS_BODY_COMPLETE)
1596 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1597 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1598 log_error(LOG_LEVEL_CLF,
1599 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1600 return JB_ERR_PARSE;
1602 log_error(LOG_LEVEL_CONNECT,
1603 "Chunked client body completely read. Length: %lu", body_length);
1604 csp->expected_client_content_length = body_length;
1612 /*********************************************************************
1614 * Function : fuzz_chunked_transfer_encoding
1616 * Description : Treat the fuzzed input as chunked transfer encoding
1617 * to check and dechunk.
1620 * 1 : csp = Used to store the data.
1621 * 2 : fuzz_input_file = File to read the input from.
1623 * Returns : Result of dechunking
1625 *********************************************************************/
1626 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1629 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1630 enum chunk_status status;
1632 status = chunked_body_is_complete(csp->iob, &length);
1633 if (CHUNK_STATUS_BODY_COMPLETE != status)
1635 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1638 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1643 /*********************************************************************
1645 * Function : fuzz_client_request
1647 * Description : Try to get a client request from the fuzzed input.
1650 * 1 : csp = Current client state (buffers, headers, etc...)
1651 * 2 : fuzz_input_file = File to read the input from.
1653 * Returns : Result of fuzzing.
1655 *********************************************************************/
1656 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1661 csp->ip_addr_str = "fuzzer";
1663 if (strcmp(fuzz_input_file, "-") != 0)
1665 log_error(LOG_LEVEL_FATAL,
1666 "Fuzzed client requests can currently only be read from stdin (-).");
1668 err = receive_client_request(csp);
1669 if (err != JB_ERR_OK)
1673 err = parse_client_request(csp);
1674 if (err != JB_ERR_OK)
1682 #endif /* def FUZZ */
1685 #ifdef FEATURE_FORCE_LOAD
1686 /*********************************************************************
1688 * Function : force_required
1690 * Description : Checks a request line to see if it contains
1691 * the FORCE_PREFIX. If it does, it is removed
1692 * unless enforcing requests has beend disabled.
1695 * 1 : request_line = HTTP request line
1697 * Returns : TRUE if force is required, FALSE otherwise.
1699 *********************************************************************/
1700 static int force_required(const struct client_state *csp, char *request_line)
1704 p = strstr(request_line, "http://");
1708 p += strlen("http://");
1712 /* Intercepted request usually don't specify the protocol. */
1716 /* Go to the beginning of the path */
1721 * If the path is missing the request line is invalid and we
1722 * are done here. The client-visible rejection happens later on.
1727 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1729 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1731 /* XXX: Should clean more carefully */
1732 strclean(request_line, FORCE_PREFIX);
1733 log_error(LOG_LEVEL_FORCE,
1734 "Enforcing request: \"%s\".", request_line);
1738 log_error(LOG_LEVEL_FORCE,
1739 "Ignored force prefix in request: \"%s\".", request_line);
1745 #endif /* def FEATURE_FORCE_LOAD */
1748 /*********************************************************************
1750 * Function : receive_client_request
1752 * Description : Read the client's request (more precisely the
1753 * client headers) and answer it if necessary.
1756 * 1 : csp = Current client state (buffers, headers, etc...)
1758 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1760 *********************************************************************/
1761 static jb_err receive_client_request(struct client_state *csp)
1763 char buf[BUFFER_SIZE];
1766 struct http_request *http;
1770 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1771 struct list header_list;
1772 struct list *headers = &header_list;
1774 /* We don't care if the arriving data is a valid HTTP request or not. */
1775 csp->requests_received_total++;
1779 memset(buf, 0, sizeof(buf));
1781 req = get_request_line(csp);
1784 mark_server_socket_tainted(csp);
1785 return JB_ERR_PARSE;
1787 assert(*req != '\0');
1789 if (client_protocol_is_unsupported(csp, req))
1791 return JB_ERR_PARSE;
1794 #ifdef FEATURE_FORCE_LOAD
1795 if (force_required(csp, req))
1797 csp->flags |= CSP_FLAG_FORCED;
1799 #endif /* def FEATURE_FORCE_LOAD */
1801 err = parse_http_request(req, http);
1803 if (JB_ERR_OK != err)
1805 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1806 get_write_delay(csp));
1807 /* XXX: Use correct size */
1808 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1809 log_error(LOG_LEVEL_ERROR,
1810 "Couldn't parse request line received from %s: %s",
1811 csp->ip_addr_str, jb_err_to_string(err));
1813 free_http_request(http);
1814 return JB_ERR_PARSE;
1817 /* grab the rest of the client's headers */
1821 p = get_header(csp->client_iob);
1825 /* There are no additional headers to read. */
1832 * We didn't receive a complete header
1833 * line yet, get the rest of it.
1835 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1837 log_error(LOG_LEVEL_ERROR,
1838 "Stopped grabbing the client headers.");
1839 destroy_list(headers);
1840 return JB_ERR_PARSE;
1843 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1846 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1847 destroy_list(headers);
1848 return JB_ERR_PARSE;
1851 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1854 * If there is no memory left for buffering the
1855 * request, there is nothing we can do but hang up
1857 destroy_list(headers);
1858 return JB_ERR_MEMORY;
1863 if (!strncmpic(p, "Transfer-Encoding:", 18))
1866 * XXX: should be called through sed()
1867 * but currently can't.
1869 client_transfer_encoding(csp, &p);
1872 * We were able to read a complete
1873 * header and can finally enlist it.
1880 if (http->host == NULL)
1883 * If we still don't know the request destination,
1884 * the request is invalid or the client uses
1885 * Privoxy without its knowledge.
1887 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1890 * Our attempts to get the request destination
1891 * elsewhere failed or Privoxy is configured
1892 * to only accept proxy requests.
1894 * An error response has already been sent
1895 * and we're done here.
1897 return JB_ERR_PARSE;
1901 #ifdef FEATURE_CLIENT_TAGS
1902 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1903 set_client_address(csp, headers);
1904 get_tag_list_for_client(csp->client_tags, csp->client_address);
1908 * Determine the actions for this URL
1910 #ifdef FEATURE_TOGGLE
1911 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1913 /* Most compatible set of actions (i.e. none) */
1914 init_current_action(csp->action);
1917 #endif /* ndef FEATURE_TOGGLE */
1919 get_url_actions(csp, http);
1922 enlist(csp->headers, http->cmd);
1924 /* Append the previously read headers */
1925 err = list_append_list_unique(csp->headers, headers);
1926 destroy_list(headers);
1933 /*********************************************************************
1935 * Function : parse_client_request
1937 * Description : Parses the client's request and decides what to do
1940 * Note that since we're not using select() we could get
1941 * blocked here if a client connected, then didn't say
1945 * 1 : csp = Current client state (buffers, headers, etc...)
1947 * Returns : JB_ERR_OK or JB_ERR_PARSE
1949 *********************************************************************/
1950 static jb_err parse_client_request(struct client_state *csp)
1952 struct http_request *http = csp->http;
1955 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1956 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1957 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1958 && (csp->http->ssl == 0))
1960 /* Assume persistence until further notice */
1961 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1963 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1965 if (csp->http->ssl == 0)
1968 * This whole block belongs to chat() but currently
1969 * has to be executed before sed().
1971 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1973 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1975 return JB_ERR_PARSE;
1980 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1982 verify_request_length(csp);
1984 #ifndef FEATURE_HTTPS_INSPECTION
1987 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1991 err = sed(csp, FILTER_CLIENT_HEADERS);
1992 if (JB_ERR_OK != err)
1994 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1996 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1997 csp->ip_addr_str, csp->http->cmd);
1998 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1999 return JB_ERR_PARSE;
2001 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2003 /* Check request line for rewrites. */
2004 if ((NULL == csp->headers->first->str)
2005 || (strcmp(http->cmd, csp->headers->first->str) &&
2006 (JB_ERR_OK != change_request_destination(csp))))
2009 * A header filter broke the request line - bail out.
2011 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2012 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2013 /* XXX: Use correct size */
2014 log_error(LOG_LEVEL_CLF,
2015 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2016 log_error(LOG_LEVEL_ERROR,
2017 "Invalid request line after applying header filters.");
2018 free_http_request(http);
2020 return JB_ERR_PARSE;
2023 if (client_has_unsupported_expectations(csp))
2025 return JB_ERR_PARSE;
2033 /*********************************************************************
2035 * Function : read_http_request_body
2037 * Description : Reads remaining request body from the client.
2040 * 1 : csp = Current client state (buffers, headers, etc...)
2042 * Returns : 0 on success, anything else is an error.
2044 *********************************************************************/
2045 static int read_http_request_body(struct client_state *csp)
2047 size_t to_read = csp->expected_client_content_length;
2050 assert(to_read != 0);
2052 /* check if all data has been already read */
2053 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2058 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2059 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2060 to_read -= (unsigned)len)
2062 char buf[BUFFER_SIZE];
2063 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2065 log_error(LOG_LEVEL_CONNECT,
2066 "Waiting for up to %lu bytes of request body from the client.",
2068 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2071 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2074 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2078 assert(to_read >= len);
2083 log_error(LOG_LEVEL_CONNECT,
2084 "Not enough request body has been read: expected %lu more bytes",
2088 log_error(LOG_LEVEL_CONNECT,
2089 "The last %d bytes of the request body have been read", len);
2094 /*********************************************************************
2096 * Function : update_client_headers
2098 * Description : Updates the HTTP headers from the client request.
2101 * 1 : csp = Current client state (buffers, headers, etc...)
2102 * 2 : new_content_length = new content length value to set
2104 * Returns : 0 on success, anything else is an error.
2106 *********************************************************************/
2107 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2109 static const char content_length[] = "Content-Length:";
2111 struct list_entry *p;
2113 #ifndef FEATURE_HTTPS_INSPECTION
2114 for (p = csp->headers->first;
2116 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2118 !updated && (p != NULL); p = p->next)
2120 /* Header crunch()ed in previous run? -> ignore */
2126 /* Does the current parser handle this header? */
2127 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2129 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2141 /*********************************************************************
2143 * Function : can_filter_request_body
2145 * Description : Checks if the current request body can be stored in
2146 * the client_iob without hitting buffer limit.
2149 * 1 : csp = Current client state (buffers, headers, etc...)
2151 * Returns : TRUE if the current request size do not exceed buffer limit
2154 *********************************************************************/
2155 static int can_filter_request_body(const struct client_state *csp)
2157 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2158 csp->expected_client_content_length))
2160 log_error(LOG_LEVEL_INFO,
2161 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2162 "(content length %llu)", csp->ip_addr_str, csp->config->buffer_limit,
2163 csp->expected_client_content_length);
2170 /*********************************************************************
2172 * Function : send_http_request
2174 * Description : Sends the HTTP headers from the client request
2175 * and all the body data that has already been received.
2178 * 1 : csp = Current client state (buffers, headers, etc...)
2180 * Returns : 0 on success, anything else is an error.
2182 *********************************************************************/
2183 static int send_http_request(struct client_state *csp)
2187 const char *to_send;
2189 int filter_client_body = csp->expected_client_content_length != 0 &&
2190 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2192 if (filter_client_body)
2194 if (read_http_request_body(csp))
2198 to_send_len = csp->expected_client_content_length;
2199 to_send = execute_client_body_filters(csp, &to_send_len);
2200 if (to_send == NULL)
2202 /* just flush client_iob */
2203 filter_client_body = FALSE;
2205 else if (to_send_len != csp->expected_client_content_length &&
2206 update_client_headers(csp, to_send_len))
2208 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2212 csp->expected_client_content_length = 0;
2215 hdr = list_to_text(csp->headers);
2218 /* FIXME Should handle error properly */
2219 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2221 list_remove_all(csp->headers);
2224 * Write the client's (modified) header to the server
2225 * (along with anything else that may be in the buffer)
2227 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2232 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2233 csp->http->hostport);
2234 if (filter_client_body)
2241 if (filter_client_body)
2243 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2247 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2248 csp->http->hostport);
2253 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2254 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2256 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2257 csp->http->hostport);
2264 #ifdef FEATURE_HTTPS_INSPECTION
2265 /*********************************************************************
2267 * Function : read_https_request_body
2269 * Description : Reads remaining request body from the client.
2272 * 1 : csp = Current client state (buffers, headers, etc...)
2274 * Returns : 0 on success, anything else is an error.
2276 *********************************************************************/
2277 static int read_https_request_body(struct client_state *csp)
2279 size_t to_read = csp->expected_client_content_length;
2282 assert(to_read != 0);
2284 /* check if all data has been already read */
2285 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2290 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2291 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2292 data_is_available(csp->cfd, csp->config->socket_timeout));
2293 to_read -= (unsigned)len)
2295 unsigned char buf[BUFFER_SIZE];
2296 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2298 log_error(LOG_LEVEL_CONNECT,
2299 "Waiting for up to %lu bytes of request body from the client.",
2301 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2302 (unsigned)max_bytes_to_read);
2305 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2308 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2312 assert(to_read >= len);
2317 log_error(LOG_LEVEL_CONNECT,
2318 "Not enough request body has been read: expected %lu more bytes",
2323 log_error(LOG_LEVEL_CONNECT,
2324 "The last %llu bytes of the request body have been read",
2325 csp->expected_client_content_length);
2330 /*********************************************************************
2332 * Function : receive_and_send_encrypted_post_data
2334 * Description : Reads remaining request body from the client and sends
2338 * 1 : csp = Current client state (buffers, headers, etc...)
2340 * Returns : 0 on success, anything else is an error.
2342 *********************************************************************/
2343 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2345 int content_length_known = csp->expected_client_content_length != 0;
2347 while (is_ssl_pending(&(csp->ssl_client_attr))
2348 || (content_length_known && csp->expected_client_content_length != 0))
2350 unsigned char buf[BUFFER_SIZE];
2352 int max_bytes_to_read = sizeof(buf);
2354 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2356 max_bytes_to_read = (int)csp->expected_client_content_length;
2358 log_error(LOG_LEVEL_CONNECT,
2359 "Waiting for up to %d bytes of request body from the client.",
2361 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2362 (unsigned)max_bytes_to_read);
2369 /* XXX: Does this actually happen? */
2372 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2374 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2379 if (csp->expected_client_content_length != 0)
2381 if (csp->expected_client_content_length >= len)
2383 csp->expected_client_content_length -= (unsigned)len;
2385 if (csp->expected_client_content_length == 0)
2387 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2393 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2400 /*********************************************************************
2402 * Function : send_https_request
2404 * Description : Sends the HTTP headers from the client request
2405 * and all the body data that has already been received.
2408 * 1 : csp = Current client state (buffers, headers, etc...)
2410 * Returns : 0 on success, anything else is an error.
2412 *********************************************************************/
2413 static int send_https_request(struct client_state *csp)
2418 const char *to_send;
2420 int filter_client_body = csp->expected_client_content_length != 0 &&
2421 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2423 if (filter_client_body)
2425 if (read_https_request_body(csp))
2429 to_send_len = csp->expected_client_content_length;
2430 to_send = execute_client_body_filters(csp, &to_send_len);
2431 if (to_send == NULL)
2433 /* just flush client_iob */
2434 filter_client_body = FALSE;
2436 else if (to_send_len != csp->expected_client_content_length &&
2437 update_client_headers(csp, to_send_len))
2439 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2442 csp->expected_client_content_length = 0;
2445 hdr = list_to_text(csp->https_headers);
2448 /* FIXME Should handle error properly */
2449 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2451 list_remove_all(csp->https_headers);
2454 * Write the client's (modified) header to the server
2455 * (along with anything else that may be in the buffer)
2457 ret = ssl_send_data(&(csp->ssl_server_attr),
2458 (const unsigned char *)hdr, strlen(hdr));
2463 log_error(LOG_LEVEL_CONNECT,
2464 "Failed sending encrypted request headers to: %s: %E",
2465 csp->http->hostport);
2466 mark_server_socket_tainted(csp);
2470 if (filter_client_body)
2472 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2476 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2477 csp->http->hostport);
2482 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2483 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2484 csp->client_iob)) < 0))
2486 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2487 csp->http->hostport);
2490 if (flushed != 0 || csp->expected_client_content_length != 0)
2492 if (csp->expected_client_content_length != 0)
2494 if (csp->expected_client_content_length < flushed)
2496 log_error(LOG_LEVEL_ERROR,
2497 "Flushed %ld bytes of request body while only expecting %llu",
2498 flushed, csp->expected_client_content_length);
2499 csp->expected_client_content_length = 0;
2503 log_error(LOG_LEVEL_CONNECT,
2504 "Flushed %ld bytes of request body while expecting %llu",
2505 flushed, csp->expected_client_content_length);
2506 csp->expected_client_content_length -= (unsigned)flushed;
2507 if (receive_and_send_encrypted_post_data(csp))
2515 log_error(LOG_LEVEL_CONNECT,
2516 "Flushed %ld bytes of request body", flushed);
2520 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2527 /*********************************************************************
2529 * Function : receive_encrypted_request_headers
2531 * Description : Receives the encrypted request headers when
2535 * 1 : csp = Current client state (buffers, headers, etc...)
2537 * Returns : JB_ERR_OK on success,
2538 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2540 *********************************************************************/
2541 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2543 char buf[BUFFER_SIZE];
2549 log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2550 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2551 !data_is_available(csp->cfd, csp->config->socket_timeout))
2553 log_error(LOG_LEVEL_CONNECT,
2554 "Socket %d timed out while waiting for client headers", csp->cfd);
2555 return JB_ERR_PARSE;
2557 len = ssl_recv_data(&(csp->ssl_client_attr),
2558 (unsigned char *)buf, sizeof(buf));
2561 log_error(LOG_LEVEL_CONNECT,
2562 "Socket %d closed while waiting for client headers", csp->cfd);
2563 return JB_ERR_PARSE;
2567 return JB_ERR_PARSE;
2569 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2571 return JB_ERR_MEMORY;
2573 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2574 } while (p == NULL);
2576 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2582 /*********************************************************************
2584 * Function : change_encrypted_request_destination
2586 * Description : Parse a (rewritten) request line from an encrypted
2587 * request and regenerate the http request data.
2590 * 1 : csp = Current client state (buffers, headers, etc...)
2592 * Returns : Forwards the parse_http_request() return code.
2593 * Terminates in case of memory problems.
2595 *********************************************************************/
2596 static jb_err change_encrypted_request_destination(struct client_state *csp)
2599 char *original_host = csp->http->host;
2600 int original_port = csp->http->port;
2602 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2603 csp->https_headers->first->str);
2604 csp->http->host = NULL;
2605 free_http_request(csp->http);
2606 err = parse_http_request(csp->https_headers->first->str, csp->http);
2607 if (JB_ERR_OK != err)
2609 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2610 jb_err_to_string(err));
2611 freez(original_host);
2615 if (csp->http->host == NULL)
2617 char port_string[10];
2619 * The rewritten request line did not specify a host
2620 * which means we can use the original host specified
2623 csp->http->host = original_host;
2624 csp->http->port = original_port;
2625 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2628 * If the rewritten request line didn't contain a host
2629 * it also didn't contain a port so we can reuse the host
2632 freez(csp->http->hostport);
2633 csp->http->hostport = strdup_or_die(csp->http->host);
2634 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2635 err = string_append(&csp->http->hostport, port_string);
2636 if (err != JB_ERR_OK)
2638 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2639 jb_err_to_string(err));
2644 * While the request line didn't mention it,
2645 * we're https-inspecting and want to speak TLS
2648 csp->http->server_ssl = 1;
2653 /* The rewrite filter added a host so we can ditch the original */
2654 freez(original_host);
2655 csp->http->server_ssl = csp->http->ssl;
2658 csp->http->client_ssl = 1;
2660 freez(csp->https_headers->first->str);
2661 build_request_line(csp, NULL, &csp->https_headers->first->str);
2663 if (!server_use_ssl(csp))
2665 log_error(LOG_LEVEL_REDIRECTS,
2666 "Rewritten request line results in downgrade to http");
2668 * Replace the unencryptd headers received with the
2669 * CONNECT request with the ones we received securely.
2671 destroy_list(csp->headers);
2672 csp->headers->first = csp->https_headers->first;
2673 csp->headers->last = csp->https_headers->last;
2674 csp->https_headers->first = NULL;
2675 csp->https_headers->last = NULL;
2683 /*********************************************************************
2685 * Function : process_encrypted_request_headers
2687 * Description : Receives and parses the encrypted headers send
2688 * by the client when https-inspecting.
2691 * 1 : csp = Current client state (buffers, headers, etc...)
2693 * Returns : JB_ERR_OK on success,
2694 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2696 *********************************************************************/
2697 static jb_err process_encrypted_request_headers(struct client_state *csp)
2702 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2703 struct list header_list;
2704 struct list *headers = &header_list;
2706 assert(csp->ssl_with_client_is_opened);
2708 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2709 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2711 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2714 err = receive_encrypted_request_headers(csp);
2715 if (err != JB_ERR_OK)
2717 if (csp->client_iob->cur == NULL ||
2718 csp->client_iob->cur == csp->client_iob->eod)
2721 * We did not receive any data, most likely because the
2722 * client is done. Don't log this as a parse failure.
2724 return JB_ERR_PARSE;
2726 /* XXX: Also used for JB_ERR_MEMORY */
2727 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2728 jb_err_to_string(err));
2729 ssl_send_data_delayed(&(csp->ssl_client_attr),
2730 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2734 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2735 request_line = get_header(csp->client_iob);
2736 if (request_line == NULL)
2738 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2739 ssl_send_data_delayed(&(csp->ssl_client_attr),
2740 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2741 return JB_ERR_PARSE;
2743 assert(*request_line != '\0');
2745 if (client_protocol_is_unsupported(csp, request_line))
2748 * If the protocol is unsupported we're done here.
2749 * client_protocol_is_unsupported() took care of sending
2750 * the error response and logging the error message.
2752 return JB_ERR_PARSE;
2755 #ifdef FEATURE_FORCE_LOAD
2756 if (force_required(csp, request_line))
2758 csp->flags |= CSP_FLAG_FORCED;
2760 #endif /* def FEATURE_FORCE_LOAD */
2762 free_http_request(csp->http);
2764 err = parse_http_request(request_line, csp->http);
2765 /* XXX: Restore ssl setting. This is ugly */
2766 csp->http->client_ssl = 1;
2767 csp->http->server_ssl = 1;
2769 freez(request_line);
2770 if (JB_ERR_OK != err)
2772 ssl_send_data_delayed(&(csp->ssl_client_attr),
2773 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2774 /* XXX: Use correct size */
2775 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2776 log_error(LOG_LEVEL_ERROR,
2777 "Couldn't parse request line received from %s: %s",
2778 csp->ip_addr_str, jb_err_to_string(err));
2780 free_http_request(csp->http);
2781 return JB_ERR_PARSE;
2784 /* Parse the rest of the client's headers. */
2788 p = get_header(csp->client_iob);
2792 /* There are no additional headers to read. */
2799 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2802 * Our attempts to get the request destination
2805 log_error(LOG_LEVEL_ERROR,
2806 "Failed to get the encrypted request destination");
2807 ssl_send_data_delayed(&(csp->ssl_client_attr),
2808 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2809 destroy_list(headers);
2811 return JB_ERR_PARSE;
2814 /* Split the domain we just got for pattern matching */
2815 init_domain_components(csp->http);
2817 #ifdef FEATURE_CLIENT_TAGS
2818 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2819 if (csp->client_address == NULL)
2821 set_client_address(csp, headers);
2822 get_tag_list_for_client(csp->client_tags, csp->client_address);
2826 #ifdef FEATURE_TOGGLE
2827 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2831 * Determine the actions for this request after
2832 * clearing the ones from the previous one.
2834 free_current_action(csp->action);
2835 get_url_actions(csp, csp->http);
2838 enlist(csp->https_headers, csp->http->cmd);
2840 /* Append the previously read headers */
2841 err = list_append_list_unique(csp->https_headers, headers);
2842 destroy_list(headers);
2843 if (JB_ERR_OK != err)
2845 /* XXX: Send error message */
2849 /* XXX: Work around crash */
2850 csp->error_message = NULL;
2852 /* XXX: Why do this here? */
2855 err = sed_https(csp);
2856 if (JB_ERR_OK != err)
2858 ssl_send_data_delayed(&(csp->ssl_client_attr),
2859 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2860 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2862 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2863 csp->ip_addr_str, csp->http->cmd);
2864 return JB_ERR_PARSE;
2867 if ((NULL == csp->https_headers->first->str)
2868 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2869 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2871 ssl_send_data_delayed(&(csp->ssl_client_attr),
2872 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2873 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2874 log_error(LOG_LEVEL_ERROR,
2875 "Invalid request line after applying header filters.");
2876 /* XXX: Use correct size */
2877 log_error(LOG_LEVEL_CLF,
2878 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2880 return JB_ERR_PARSE;
2883 log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2884 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2891 /*********************************************************************
2893 * Function : cgi_page_requested
2895 * Description : Checks if a request is for an internal CGI page.
2898 * 1 : host = The host requested by the client.
2900 * Returns : 1 if a CGI page has been requested, 0 otherwise
2902 *********************************************************************/
2903 static int cgi_page_requested(const char *host)
2905 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2906 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2907 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2908 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2918 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2919 /*********************************************************************
2921 * Function : continue_https_chat
2923 * Description : Behaves similar to chat() but only deals with
2924 * https-inspected requests that arrive on an already
2925 * established connection. The first request is always
2926 * served by chat() which is a lot more complex as it
2927 * has to deal with forwarding settings and connection
2930 * If a connection to the server has already been
2931 * opened it is reused unless the request is blocked
2932 * or the forwarder changed.
2934 * If a connection to the server has not yet been
2935 * opened (because the previous request was crunched),
2936 * or the forwarder changed, the connection is dropped
2937 * so that the client retries on a fresh one.
2940 * 1 : csp = Current client state (buffers, headers, etc...)
2942 * Returns : Nothing.
2944 *********************************************************************/
2945 static void continue_https_chat(struct client_state *csp)
2947 const struct forward_spec *fwd;
2949 if (JB_ERR_OK != process_encrypted_request_headers(csp))
2951 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2955 csp->requests_received_total++;
2958 * We have an encrypted request. Check if one of the crunchers wants it.
2960 if (crunch_response_triggered(csp, crunchers_all))
2963 * Yes. The client got the crunch response and we're done here.
2967 if (csp->ssl_with_server_is_opened == 0)
2969 log_error(LOG_LEVEL_CONNECT,
2970 "Dropping the client connection on socket %d. "
2971 "The server connection has not been established yet.",
2973 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2976 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2978 fwd = forward_url(csp, csp->http);
2979 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2981 log_error(LOG_LEVEL_CONNECT,
2982 "Dropping the client connection on socket %d with "
2983 "server socket %d connected to %s. The forwarder has changed.",
2984 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2985 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2989 log_applied_actions(csp->action);
2991 log_error(LOG_LEVEL_CONNECT,
2992 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2993 csp->server_connection.sfd, csp->server_connection.host,
2994 csp->server_connection.requests_sent_total);
2996 if (send_https_request(csp))
2999 * Most likely the server connection timed out. We can't easily
3000 * create a new one so simply drop the client connection without a
3001 * error response to let the client retry.
3003 log_error(LOG_LEVEL_CONNECT,
3004 "Dropping client connection on socket %d. "
3005 "Forwarding the encrypted client request failed.",
3009 csp->server_connection.request_sent = time(NULL);
3010 csp->server_connection.requests_sent_total++;
3011 handle_established_connection(csp);
3012 freez(csp->receive_buffer);
3014 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3018 /*********************************************************************
3020 * Function : handle_established_connection
3022 * Description : Shuffle data between client and server once the
3023 * connection has been established and the request
3027 * 1 : csp = Current client state (buffers, headers, etc...)
3029 * Returns : Nothing.
3031 *********************************************************************/
3032 static void handle_established_connection(struct client_state *csp)
3038 struct pollfd poll_fds[2];
3042 struct timeval timeout;
3045 int ms_iis5_hack = 0;
3046 unsigned long long byte_count = 0;
3047 struct http_request *http;
3048 long len = 0; /* for buffer sizes (and negative error codes) */
3049 int buffer_and_filter_content = 0;
3050 unsigned int write_delay;
3051 #ifdef FEATURE_HTTPS_INSPECTION
3053 int use_ssl_tunnel = 0;
3054 csp->dont_verify_certificate = 0;
3056 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3058 /* Pass encrypted content without filtering. */
3063 /* Skeleton for HTTP response, if we should intercept the request */
3064 struct http_response *rsp;
3065 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3066 int watch_client_socket;
3069 csp->receive_buffer_size = csp->config->receive_buffer_size;
3070 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3071 if (csp->receive_buffer == NULL)
3073 log_error(LOG_LEVEL_ERROR,
3074 "Out of memory. Failed to allocate the receive buffer.");
3075 rsp = cgi_error_memory();
3076 send_crunch_response(csp, rsp);
3083 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3084 csp->cfd : csp->server_connection.sfd;
3087 /* pass data between the client and server
3088 * until one or the other shuts down the connection.
3093 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3094 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3096 write_delay = get_write_delay(csp);
3100 #ifdef FEATURE_HTTPS_INSPECTION
3101 if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3104 * It's possible that the TLS library already consumed all the
3105 * data the server intends to send. If that happens poll() and
3106 * select() will no longer see the data as available so we have
3107 * to skip the calls.
3109 goto server_wants_to_talk;
3114 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3115 if (!watch_client_socket)
3117 maxfd = csp->server_connection.sfd;
3120 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3122 FD_SET(csp->cfd, &rfds);
3125 FD_SET(csp->server_connection.sfd, &rfds);
3126 #endif /* ndef HAVE_POLL */
3128 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3129 if ((csp->flags & CSP_FLAG_CHUNKED)
3130 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3131 && ((csp->iob->eod - csp->iob->cur) >= 5)
3132 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3135 * XXX: This check should be obsolete now,
3136 * but let's wait a while to be sure.
3138 log_error(LOG_LEVEL_CONNECT,
3139 "Looks like we got the last chunk together with "
3140 "the server headers but didn't detect it earlier. "
3141 "We better stop reading.");
3142 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3143 csp->expected_content_length = byte_count;
3144 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3146 if (server_body && server_response_is_complete(csp, byte_count))
3148 if (csp->expected_content_length == byte_count)
3150 log_error(LOG_LEVEL_CONNECT,
3151 "Done reading from server. Content length: %llu as expected. "
3152 "Bytes most recently read: %ld.",
3157 log_error(LOG_LEVEL_CONNECT,
3158 "Done reading from server. Expected content length: %llu. "
3159 "Actual content length: %llu. Bytes most recently read: %ld.",
3160 csp->expected_content_length, byte_count, len);
3164 * XXX: Should not jump around, handle_established_connection()
3165 * is complicated enough already.
3169 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3172 poll_fds[0].fd = csp->cfd;
3173 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3174 if (!watch_client_socket)
3177 * Ignore incoming data, but still watch out
3178 * for disconnects etc. These flags are always
3179 * implied anyway but explicitly setting them
3182 poll_fds[0].events = POLLERR|POLLHUP;
3187 poll_fds[0].events = POLLIN;
3189 poll_fds[1].fd = csp->server_connection.sfd;
3190 poll_fds[1].events = POLLIN;
3191 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3193 timeout.tv_sec = csp->config->socket_timeout;
3194 timeout.tv_usec = 0;
3195 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3196 #endif /* def HAVE_POLL */
3198 /* Server or client not responding in timeout */
3201 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3202 csp->config->socket_timeout, http->url);
3203 if ((byte_count == 0) && (http->ssl == 0))
3205 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3207 mark_server_socket_tainted(csp);
3208 #ifdef FEATURE_HTTPS_INSPECTION
3209 close_client_and_server_ssl_connections(csp);
3216 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3218 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3220 mark_server_socket_tainted(csp);
3221 #ifdef FEATURE_HTTPS_INSPECTION
3222 close_client_and_server_ssl_connections(csp);
3228 * This is the body of the browser's request,
3229 * just read and write it.
3231 * Receives data from browser and sends it to server
3233 * XXX: Make sure the client doesn't use pipelining
3234 * behind Privoxy's back.
3237 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3239 log_error(LOG_LEVEL_CONNECT,
3240 "The client socket %d has become unusable while "
3241 "the server socket %d is still open.",
3242 csp->cfd, csp->server_connection.sfd);
3243 mark_server_socket_tainted(csp);
3247 if (poll_fds[0].revents != 0)
3249 if (FD_ISSET(csp->cfd, &rfds))
3250 #endif /* def HAVE_POLL*/
3252 int max_bytes_to_read = (int)csp->receive_buffer_size;
3254 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3255 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3257 if (data_is_available(csp->cfd, 0))
3260 * If the next request is already waiting, we have
3261 * to stop select()ing the client socket. Otherwise
3262 * we would always return right away and get nothing
3265 watch_client_socket = 0;
3266 log_error(LOG_LEVEL_CONNECT,
3267 "Stop watching client socket %d. "
3268 "There's already another request waiting.",
3273 * If the client socket is set, but there's no data
3274 * available on the socket, the client went fishing
3275 * and continuing talking to the server makes no sense.
3277 log_error(LOG_LEVEL_CONNECT,
3278 "The client closed socket %d while "
3279 "the server socket %d is still open.",
3280 csp->cfd, csp->server_connection.sfd);
3281 mark_server_socket_tainted(csp);
3284 if (csp->expected_client_content_length != 0)
3286 if (csp->expected_client_content_length < csp->receive_buffer_size)
3288 max_bytes_to_read = (int)csp->expected_client_content_length;
3290 log_error(LOG_LEVEL_CONNECT,
3291 "Waiting for up to %d bytes from the client.",
3294 assert(max_bytes_to_read <= csp->receive_buffer_size);
3295 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3297 #ifdef FEATURE_HTTPS_INSPECTION
3298 if (client_use_ssl(csp))
3300 if (csp->http->status == 101)
3302 len = ssl_recv_data(&(csp->ssl_client_attr),
3303 (unsigned char *)csp->receive_buffer,
3304 (size_t)max_bytes_to_read);
3307 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3308 "on client socket %d for an upgraded connection",
3314 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3315 "on client socket %d for an upgraded connection",
3319 byte_count += (unsigned long long)len;
3320 len = ssl_send_data(&(csp->ssl_server_attr),
3321 (unsigned char *)csp->receive_buffer, (size_t)len);
3324 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3325 "on server socket %d for an upgraded connection",
3326 csp->server_connection.sfd);
3331 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3335 #endif /* def FEATURE_HTTPS_INSPECTION */
3337 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3341 /* XXX: not sure if this is necessary. */
3342 mark_server_socket_tainted(csp);
3343 break; /* "game over, man" */
3346 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3347 if (csp->expected_client_content_length != 0)
3349 assert(len <= max_bytes_to_read);
3350 csp->expected_client_content_length -= (unsigned)len;
3351 log_error(LOG_LEVEL_CONNECT,
3352 "Expected client content length set to %llu "
3353 "after reading %ld bytes.",
3354 csp->expected_client_content_length, len);
3355 if (csp->expected_client_content_length == 0)
3357 log_error(LOG_LEVEL_CONNECT,
3358 "Done reading from the client.");
3359 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3362 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3364 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3366 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3367 mark_server_socket_tainted(csp);
3375 * The server wants to talk. It could be the header or the body.
3376 * If `hdr' is null, then it's the header otherwise it's the body.
3377 * FIXME: Does `hdr' really mean `host'? No.
3380 if (poll_fds[1].revents != 0)
3382 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3383 #endif /* HAVE_POLL */
3385 #ifdef FEATURE_HTTPS_INSPECTION
3386 server_wants_to_talk:
3388 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3390 * If we are buffering content, we don't want to eat up to
3391 * buffer-limit bytes if the client no longer cares about them.
3392 * If we aren't buffering, however, a dead client socket will be
3393 * noticed pretty much right away anyway, so we can reduce the
3394 * overhead by skipping the check.
3396 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3399 log_error(LOG_LEVEL_CONNECT,
3400 "The server still wants to talk, but the client may already have hung up on us.");
3402 log_error(LOG_LEVEL_CONNECT,
3403 "The server still wants to talk, but the client hung up on us.");
3404 mark_server_socket_tainted(csp);
3405 #ifdef FEATURE_HTTPS_INSPECTION
3406 close_client_and_server_ssl_connections(csp);
3409 #endif /* def _WIN32 */
3411 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3413 #ifdef FEATURE_HTTPS_INSPECTION
3415 * Reading data from standard or secured connection (HTTP/HTTPS)
3417 if (server_use_ssl(csp))
3419 len = ssl_recv_data(&(csp->ssl_server_attr),
3420 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3425 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3426 (int)csp->receive_buffer_size);
3431 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3433 if ((http->ssl && (csp->fwd == NULL))
3434 #ifdef FEATURE_HTTPS_INSPECTION
3440 * Just hang up. We already confirmed the client's CONNECT
3441 * request with status code 200 and unencrypted content is
3442 * no longer welcome.
3444 log_error(LOG_LEVEL_ERROR,
3445 "CONNECT already confirmed. Unable to tell the client about the problem.");
3448 else if (byte_count)
3451 * Just hang up. We already transmitted the original headers
3452 * and parts of the original content and therefore missed the
3453 * chance to send an error message (without risking data corruption).
3455 * XXX: we could retry with a fancy range request here.
3457 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3458 "Unable to tell the client about the problem.");
3459 mark_server_socket_tainted(csp);
3460 #ifdef FEATURE_HTTPS_INSPECTION
3461 close_client_and_server_ssl_connections(csp);
3466 * XXX: Consider handling the cases above the same.
3468 mark_server_socket_tainted(csp);
3472 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3473 if (csp->flags & CSP_FLAG_CHUNKED)
3475 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3477 /* XXX: this is a temporary hack */
3478 log_error(LOG_LEVEL_CONNECT,
3479 "Looks like we reached the end of the last chunk. "
3480 "We better stop reading.");
3481 csp->expected_content_length = byte_count + (unsigned long long)len;
3482 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3486 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3489 * This is guaranteed by allocating with zalloc_or_die()
3490 * and never (intentionally) writing to the last byte.
3492 * csp->receive_buffer_size is the size of the part of the
3493 * buffer we intentionally write to, but we actually
3494 * allocated csp->receive_buffer_size+1 bytes so the assertion
3495 * stays within the allocated range.
3497 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3500 * Add a trailing zero to let be able to use string operations.
3501 * XXX: do we still need this with filter_popups gone?
3503 assert(len <= csp->receive_buffer_size);
3504 csp->receive_buffer[len] = '\0';
3507 * Normally, this would indicate that we've read
3508 * as much as the server has sent us and we can
3509 * close the client connection. However, Microsoft
3510 * in its wisdom has released IIS/5 with a bug that
3511 * prevents it from sending the trailing \r\n in
3512 * a 302 redirect header (and possibly other headers).
3513 * To work around this if we've haven't parsed
3514 * a full header we'll append a trailing \r\n
3515 * and see if this now generates a valid one.
3517 * This hack shouldn't have any impacts. If we've
3518 * already transmitted the header or if this is a
3519 * SSL connection, then we won't bother with this
3520 * hack. So we only work on partially received
3521 * headers. If we append a \r\n and this still
3522 * doesn't generate a valid header, then we won't
3523 * transmit anything to the client.
3528 if (server_body || (http->ssl
3529 #ifdef FEATURE_HTTPS_INSPECTION
3535 * If we have been buffering up the document,
3536 * now is the time to apply content modification
3537 * and send the result to the client.
3539 if (buffer_and_filter_content)
3541 p = execute_content_filters(csp);
3543 * If content filtering fails, use the original
3544 * buffer and length.
3545 * (see p != NULL ? p : csp->iob->cur below)
3549 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3551 #ifdef FEATURE_COMPRESSION
3552 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3553 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3555 char *compressed_content = compress_buffer(p,
3556 (size_t *)&csp->content_length, csp->config->compression_level);
3557 if (compressed_content != NULL)
3560 p = compressed_content;
3561 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3566 if (JB_ERR_OK != update_server_headers(csp))
3568 log_error(LOG_LEVEL_FATAL,
3569 "Failed to update server headers. after filtering.");
3572 hdr = list_to_text(csp->headers);
3575 /* FIXME Should handle error properly */
3576 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3579 #ifdef FEATURE_HTTPS_INSPECTION
3581 * Sending data with standard or secured connection (HTTP/HTTPS)
3583 if (client_use_ssl(csp))
3585 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3586 (const unsigned char *)hdr, strlen(hdr),
3587 get_write_delay(csp)) < 0)
3588 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3589 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3590 csp->content_length, get_write_delay(csp)) < 0))
3592 log_error(LOG_LEVEL_ERROR,
3593 "Failed to send the modified content to the client over TLS");
3596 mark_server_socket_tainted(csp);
3597 close_client_and_server_ssl_connections(csp);
3602 #endif /* def FEATURE_HTTPS_INSPECTION */
3604 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3605 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3606 (size_t)csp->content_length, write_delay))
3608 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3611 mark_server_socket_tainted(csp);
3620 break; /* "game over, man" */
3624 * This is not the body, so let's pretend the server just sent
3627 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3628 len = (int)strlen(csp->receive_buffer);
3631 * Now, let the normal header parsing algorithm below do its
3632 * job. If it fails, we'll exit instead of continuing.
3639 * If we're in the body of the server document, just write it to
3640 * the client, unless we need to buffer the body for later
3641 * content-filtering.
3643 if (server_body || (http->ssl
3644 #ifdef FEATURE_HTTPS_INSPECTION
3649 if (buffer_and_filter_content)
3652 * If there is no memory left for buffering the content, or the buffer limit
3653 * has been reached, switch to non-filtering mode, i.e. make & write the
3654 * header, flush the iob and buf, and get out of the way.
3656 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3661 log_error(LOG_LEVEL_INFO,
3662 "Flushing header and buffers. Stepping back from filtering.");
3664 hdr = list_to_text(csp->headers);
3668 * Memory is too tight to even generate the header.
3669 * Send our static "Out-of-memory" page.
3671 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3672 rsp = cgi_error_memory();
3673 send_crunch_response(csp, rsp);
3674 mark_server_socket_tainted(csp);
3675 #ifdef FEATURE_HTTPS_INSPECTION
3676 close_client_and_server_ssl_connections(csp);
3680 hdrlen = strlen(hdr);
3682 #ifdef FEATURE_HTTPS_INSPECTION
3684 * Sending data with standard or secured connection (HTTP/HTTPS)
3686 if (client_use_ssl(csp))
3688 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3689 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3690 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3692 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3693 (const unsigned char *)csp->receive_buffer, (size_t)len,
3694 get_write_delay(csp)) < 0))
3696 log_error(LOG_LEVEL_CONNECT,
3697 "Flush header and buffers to client failed");
3699 mark_server_socket_tainted(csp);
3700 close_client_and_server_ssl_connections(csp);
3705 #endif /* def FEATURE_HTTPS_INSPECTION */
3707 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3708 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3709 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3712 log_error(LOG_LEVEL_CONNECT,
3713 "Flush header and buffers to client failed: %E");
3715 mark_server_socket_tainted(csp);
3721 * Reset the byte_count to the amount of bytes
3722 * we just flushed. len will be added a few lines below,
3723 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3725 byte_count = (unsigned long long)flushed;
3727 buffer_and_filter_content = 0;
3733 #ifdef FEATURE_HTTPS_INSPECTION
3735 * Sending data with standard or secured connection (HTTP/HTTPS)
3737 if (client_use_ssl(csp))
3739 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3740 (const unsigned char *)csp->receive_buffer, (size_t)len,
3741 get_write_delay(csp));
3744 log_error(LOG_LEVEL_ERROR,
3745 "Sending data to client failed");
3746 mark_server_socket_tainted(csp);
3747 close_client_and_server_ssl_connections(csp);
3752 #endif /* def FEATURE_HTTPS_INSPECTION */
3754 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3755 (size_t)len, write_delay))
3757 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3758 mark_server_socket_tainted(csp);
3763 byte_count += (unsigned long long)len;
3769 * We're still looking for the end of the server's header.
3770 * Buffer up the data we just read. If that fails, there's
3771 * little we can do but send our static out-of-memory page.
3773 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3775 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3776 rsp = cgi_error_memory();
3777 send_crunch_response(csp, rsp);
3778 mark_server_socket_tainted(csp);
3779 #ifdef FEATURE_HTTPS_INSPECTION
3780 close_client_and_server_ssl_connections(csp);
3785 /* Convert iob into something sed() can digest */
3786 if (JB_ERR_PARSE == get_server_headers(csp))
3791 * Well, we tried our MS IIS/5 hack and it didn't work.
3792 * The header is incomplete and there isn't anything
3793 * we can do about it.
3795 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3796 "Applying the MS IIS5 hack didn't help.");
3797 log_error(LOG_LEVEL_CLF,
3798 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3799 #ifdef FEATURE_HTTPS_INSPECTION
3801 * Sending data with standard or secured connection (HTTP/HTTPS)
3803 if (client_use_ssl(csp))
3805 ssl_send_data_delayed(&(csp->ssl_client_attr),
3806 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3807 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3810 #endif /* def FEATURE_HTTPS_INSPECTION */
3812 write_socket_delayed(csp->cfd,
3813 INVALID_SERVER_HEADERS_RESPONSE,
3814 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3816 mark_server_socket_tainted(csp);
3817 #ifdef FEATURE_HTTPS_INSPECTION
3818 close_client_and_server_ssl_connections(csp);
3825 * Since we have to wait for more from the server before
3826 * we can parse the headers we just continue here.
3828 log_error(LOG_LEVEL_CONNECT,
3829 "Continuing buffering server headers from socket %d. "
3830 "Bytes most recently read: %ld.", csp->cfd, len);
3837 * Account for the content bytes we
3838 * might have gotten with the headers.
3840 assert(csp->iob->eod >= csp->iob->cur);
3841 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3844 /* Did we actually get anything? */
3845 if (NULL == csp->headers->first)
3847 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3849 log_error(LOG_LEVEL_ERROR,
3850 "No server or forwarder response received on socket %d. "
3851 "Closing client socket %d without sending data.",
3852 csp->server_connection.sfd, csp->cfd);
3853 log_error(LOG_LEVEL_CLF,
3854 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3858 log_error(LOG_LEVEL_ERROR,
3859 "No server or forwarder response received on socket %d.",
3860 csp->server_connection.sfd);
3861 send_crunch_response(csp, error_response(csp, "no-server-data"));
3863 free_http_request(http);
3864 mark_server_socket_tainted(csp);
3865 #ifdef FEATURE_HTTPS_INSPECTION
3866 close_client_and_server_ssl_connections(csp);
3871 if (!csp->headers->first->str)
3873 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3875 assert(csp->headers->first->str);
3877 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3878 strncmpic(csp->headers->first->str, "ICY", 3))
3881 * It doesn't look like a HTTP (or Shoutcast) response:
3882 * tell the client and log the problem.
3884 if (strlen(csp->headers->first->str) > 30)
3886 csp->headers->first->str[30] = '\0';
3888 log_error(LOG_LEVEL_ERROR,
3889 "Invalid server or forwarder response. Starts with: %s",
3890 csp->headers->first->str);
3891 log_error(LOG_LEVEL_CLF,
3892 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3893 #ifdef FEATURE_HTTPS_INSPECTION
3895 * Sending data with standard or secured connection (HTTP/HTTPS)
3897 if (client_use_ssl(csp))
3899 ssl_send_data_delayed(&(csp->ssl_client_attr),
3900 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3901 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3902 get_write_delay(csp));
3905 #endif /* def FEATURE_HTTPS_INSPECTION */
3907 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3908 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3910 free_http_request(http);
3911 mark_server_socket_tainted(csp);
3912 #ifdef FEATURE_HTTPS_INSPECTION
3913 close_client_and_server_ssl_connections(csp);
3919 * Disable redirect checkers, so that they will be only run
3920 * again if the user also enables them through tags.
3922 * From a performance point of view it doesn't matter,
3923 * but it prevents duplicated log messages.
3925 #ifdef FEATURE_FAST_REDIRECTS
3926 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3928 csp->action->flags &= ~ACTION_REDIRECT;
3931 * We have now received the entire server header,
3932 * filter it and send the result to the client
3934 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3936 log_error(LOG_LEVEL_CLF,
3937 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3938 #ifdef FEATURE_HTTPS_INSPECTION
3940 * Sending data with standard or secured connection (HTTP/HTTPS)
3942 if (client_use_ssl(csp))
3944 ssl_send_data_delayed(&(csp->ssl_client_attr),
3945 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3946 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3947 get_write_delay(csp));
3952 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3953 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3955 free_http_request(http);
3956 mark_server_socket_tainted(csp);
3957 #ifdef FEATURE_HTTPS_INSPECTION
3958 close_client_and_server_ssl_connections(csp);
3962 hdr = list_to_text(csp->headers);
3965 /* FIXME Should handle error properly */
3966 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3969 if ((csp->flags & CSP_FLAG_CHUNKED)
3970 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3971 && ((csp->iob->eod - csp->iob->cur) >= 5)
3972 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3974 log_error(LOG_LEVEL_CONNECT,
3975 "Looks like we got the last chunk together with "
3976 "the server headers. We better stop reading.");
3977 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3978 csp->expected_content_length = byte_count;
3979 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3982 csp->server_connection.response_received = time(NULL);
3984 if (crunch_response_triggered(csp, crunchers_light))
3987 * One of the tags created by a server-header
3988 * tagger triggered a crunch. We already
3989 * delivered the crunch response to the client
3990 * and are done here after cleaning up.
3993 mark_server_socket_tainted(csp);
3994 #ifdef FEATURE_HTTPS_INSPECTION
3995 close_client_and_server_ssl_connections(csp);
4000 /* Buffer and pcrs filter this if appropriate. */
4001 buffer_and_filter_content = content_requires_filtering(csp);
4003 if (!buffer_and_filter_content)
4006 * Write the server's (modified) header to
4007 * the client (along with anything else that
4008 * may be in the buffer). Use standard or secured
4011 #ifdef FEATURE_HTTPS_INSPECTION
4012 if (client_use_ssl(csp))
4014 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
4015 (const unsigned char *)hdr, strlen(hdr),
4016 get_write_delay(csp)) < 0)
4017 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4020 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
4023 * The write failed, so don't bother mentioning it
4024 * to the client... it probably can't hear us anyway.
4027 mark_server_socket_tainted(csp);
4028 #ifdef FEATURE_HTTPS_INSPECTION
4029 close_client_and_server_ssl_connections(csp);
4035 #endif /* def FEATURE_HTTPS_INSPECTION */
4037 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4038 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4040 log_error(LOG_LEVEL_ERROR,
4041 "write header to client failed");
4043 * The write failed, so don't bother mentioning it
4044 * to the client... it probably can't hear us anyway.
4047 mark_server_socket_tainted(csp);
4053 /* we're finished with the server's header */
4059 * If this was a MS IIS/5 hack then it means the server
4060 * has already closed the connection. Nothing more to read.
4065 log_error(LOG_LEVEL_ERROR,
4066 "Closed server connection detected. "
4067 "Applying the MS IIS5 hack didn't help.");
4068 log_error(LOG_LEVEL_CLF,
4069 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4070 #ifdef FEATURE_HTTPS_INSPECTION
4072 * Sending data with standard or secured connection (HTTP/HTTPS)
4074 if (client_use_ssl(csp))
4076 ssl_send_data_delayed(&(csp->ssl_client_attr),
4077 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4078 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4079 get_write_delay(csp));
4082 #endif /* def FEATURE_HTTPS_INSPECTION */
4084 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4085 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4087 mark_server_socket_tainted(csp);
4088 #ifdef FEATURE_HTTPS_INSPECTION
4089 close_client_and_server_ssl_connections(csp);
4096 mark_server_socket_tainted(csp);
4097 #ifdef FEATURE_HTTPS_INSPECTION
4098 close_client_and_server_ssl_connections(csp);
4100 return; /* huh? we should never get here */
4103 if (csp->content_length == 0)
4106 * If Privoxy didn't recalculate the Content-Length,
4107 * byte_count is still correct.
4109 csp->content_length = byte_count;
4112 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4113 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4114 && (csp->expected_content_length != byte_count))
4116 log_error(LOG_LEVEL_CONNECT,
4117 "Received %llu bytes while expecting %llu.",
4118 byte_count, csp->expected_content_length);
4119 mark_server_socket_tainted(csp);
4123 #ifdef FEATURE_HTTPS_INSPECTION
4124 if (client_use_ssl(csp))
4126 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4127 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4128 http->version, csp->content_length);
4133 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4134 csp->ip_addr_str, http->ocmd, csp->content_length);
4136 csp->server_connection.timestamp = time(NULL);
4140 /*********************************************************************
4144 * Description : Once a connection from the client has been accepted,
4145 * this function is called (via serve()) to handle the
4146 * main business of the communication. This function
4147 * returns after dealing with a single request. It can
4148 * be called multiple times with the same client socket
4149 * if the client is keeping the connection alive.
4151 * The decision whether or not a client connection will
4152 * be kept alive is up to the caller which also must
4153 * close the client socket when done.
4155 * FIXME: chat is nearly thousand lines long.
4159 * 1 : csp = Current client state (buffers, headers, etc...)
4161 * Returns : Nothing.
4163 *********************************************************************/
4164 static void chat(struct client_state *csp)
4166 const struct forward_spec *fwd;
4167 struct http_request *http;
4168 /* Skeleton for HTTP response, if we should intercept the request */
4169 struct http_response *rsp;
4170 #ifdef FEATURE_HTTPS_INSPECTION
4171 int use_ssl_tunnel = 0;
4176 if (receive_client_request(csp) != JB_ERR_OK)
4180 if (parse_client_request(csp) != JB_ERR_OK)
4185 #ifdef FEATURE_HTTPS_INSPECTION
4187 * Setting flags to use old solution with SSL tunnel and to disable
4188 * certificate verification.
4190 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4191 && !cgi_page_requested(csp->http->host))
4196 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4198 csp->dont_verify_certificate = 1;
4203 * build the http request to send to the server
4204 * we have to do one of the following:
4206 * create = use the original HTTP request to create a new
4207 * HTTP request that has either the path component
4208 * without the http://domainspec (w/path) or the
4209 * full orininal URL (w/url)
4210 * Note that the path and/or the HTTP version may
4211 * have been altered by now.
4213 * SSL proxy = Open a socket to the host:port of the server
4214 * and create TLS/SSL connection with server and
4215 * with client. Then behave like mediator between
4216 * client and server over TLS/SSL.
4218 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4219 * with request to a parent proxy. Note that we'll be sending
4220 * forwarding the CFAIL message ourselves if connecting to the parent
4221 * fails, but we won't send a CSUCCEED message if it works,
4222 * since that would result in a double message (ours and the
4223 * parent's). After sending the request to the parent, we
4224 * must parse answer and send it to client. If connection
4225 * with server is established, we do TLS/SSL proxy. Otherwise
4226 * we send parent response to client and close connections.
4228 * here's the matrix:
4231 * +--------+--------+
4233 * 0 | create | SSL |
4234 * | w/path | proxy |
4235 * Forwarding +--------+--------+
4237 * 1 | create | proxy |
4238 * | w/url |+forward|
4239 * +--------+--------+
4243 #ifdef FEATURE_HTTPS_INSPECTION
4245 * Presetting SSL client and server flags
4247 if (http->ssl && !use_ssl_tunnel)
4249 http->client_ssl = 1;
4250 http->server_ssl = 1;
4254 http->client_ssl = 0;
4255 http->server_ssl = 0;
4259 #ifdef FEATURE_HTTPS_INSPECTION
4261 * Log the request unless we're https inspecting
4262 * in which case we don't have the path yet and
4263 * will log the request later.
4265 if (!client_use_ssl(csp))
4268 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4271 if (http->ssl && connect_port_is_forbidden(csp))
4273 const char *acceptable_connect_ports =
4274 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4275 assert(NULL != acceptable_connect_ports);
4276 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4277 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4278 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4279 csp->action->flags |= ACTION_BLOCK;
4281 #ifdef FEATURE_HTTPS_INSPECTION
4282 http->client_ssl = 0;
4283 http->server_ssl = 0;
4288 * We have a request. Check if one of the crunchers wants it
4289 * unless the client wants to use TLS/SSL in which case we
4290 * haven't setup the TLS context yet and will send the crunch
4294 #ifdef FEATURE_HTTPS_INSPECTION
4295 !client_use_ssl(csp) &&
4297 crunch_response_triggered(csp, crunchers_all))
4300 * Yes. The client got the crunch response and we're done here.
4305 #ifdef FEATURE_HTTPS_INSPECTION
4306 if (client_use_ssl(csp) && !use_ssl_tunnel)
4310 * Creating a SSL proxy.
4312 * By sending the CSUCCEED message we're lying to the client as
4313 * the connection hasn't actually been established yet. We don't
4314 * establish the connection until we have seen and parsed the
4315 * encrypted client headers.
4317 if (write_socket_delayed(csp->cfd, CSUCCEED,
4318 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4320 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4324 ret = create_client_ssl_connection(csp);
4327 log_error(LOG_LEVEL_ERROR,
4328 "Failed to open a secure connection with the client");
4331 if (JB_ERR_OK != process_encrypted_request_headers(csp))
4333 close_client_ssl_connection(csp);
4337 * We have an encrypted request. Check if one of the crunchers now
4338 * wants it (for example because the previously invisible path was
4339 * required to match).
4341 if (crunch_response_triggered(csp, crunchers_all))
4344 * Yes. The client got the crunch response and we're done here.
4351 log_applied_actions(csp->action);
4353 /* decide how to route the HTTP request */
4354 fwd = forward_url(csp, http);
4356 freez(csp->headers->first->str);
4357 build_request_line(csp, fwd, &csp->headers->first->str);
4359 if (fwd->forward_host)
4361 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4362 fwd->forward_host, fwd->forward_port, http->hostport);
4366 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4369 /* here we connect to the server, gateway, or the forwarder */
4371 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4372 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4373 && socket_is_still_alive(csp->server_connection.sfd)
4374 && connection_destination_matches(&csp->server_connection, http, fwd))
4376 log_error(LOG_LEVEL_CONNECT,
4377 "Reusing server socket %d connected to %s. Total requests: %u.",
4378 csp->server_connection.sfd, csp->server_connection.host,
4379 csp->server_connection.requests_sent_total);
4383 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4385 #ifdef FEATURE_CONNECTION_SHARING
4386 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4387 #ifdef FEATURE_HTTPS_INSPECTION
4388 && !server_use_ssl(csp)
4392 remember_connection(&csp->server_connection);
4395 #endif /* def FEATURE_CONNECTION_SHARING */
4397 log_error(LOG_LEVEL_CONNECT,
4398 "Closing server socket %d connected to %s. Total requests: %u.",
4399 csp->server_connection.sfd, csp->server_connection.host,
4400 csp->server_connection.requests_sent_total);
4401 close_socket(csp->server_connection.sfd);
4403 mark_connection_closed(&csp->server_connection);
4405 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4408 * Connecting to destination server
4410 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4412 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4414 if (fwd->type != SOCKS_NONE)
4417 rsp = error_response(csp, "forwarding-failed");
4419 else if (errno == EINVAL)
4421 rsp = error_response(csp, "no-such-domain");
4425 rsp = error_response(csp, "connect-failed");
4428 /* Write the answer to the client */
4431 send_crunch_response(csp, rsp);
4435 * Temporary workaround to prevent already-read client
4436 * bodies from being parsed as new requests. For now we
4437 * err on the safe side and throw all the following
4438 * requests under the bus, even if no client body has been
4439 * buffered. A compliant client will repeat the dropped
4440 * requests on an untainted connection.
4442 * The proper fix is to discard the no longer needed
4443 * client body in the buffer (if there is one) and to
4444 * continue parsing the bytes that follow.
4446 #ifdef FEATURE_HTTPS_INSPECTION
4447 close_client_ssl_connection(csp);
4449 drain_and_close_socket(csp->cfd);
4450 csp->cfd = JB_INVALID_SOCKET;
4455 #ifdef FEATURE_HTTPS_INSPECTION
4457 * Creating TLS/SSL connections with destination server or parent
4458 * proxy. If forwarding is enabled, we must send client request to
4459 * parent proxy and receive, parse and resend parent proxy answer.
4461 if (http->ssl && !use_ssl_tunnel)
4463 if (fwd->forward_host != NULL)
4465 char server_response[BUFFER_SIZE];
4468 char *hdr = list_to_text(csp->headers);
4469 memset(server_response, 0, sizeof(server_response));
4473 log_error(LOG_LEVEL_FATAL,
4474 "Out of memory parsing client header");
4476 list_remove_all(csp->headers);
4479 * Sending client's CONNECT request to the parent proxy
4481 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4487 log_error(LOG_LEVEL_CONNECT,
4488 "Sending request headers to: %s failed", http->hostport);
4489 mark_server_socket_tainted(csp);
4490 close_client_ssl_connection(csp);
4494 /* Waiting for parent proxy server response */
4495 len = read_socket(csp->server_connection.sfd, server_response,
4496 sizeof(server_response)-1);
4500 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4501 "server on socket %d.", csp->server_connection.sfd);