From 2d6eefd8c608730bc6443fe992ca9ce9f86bc2c4 Mon Sep 17 00:00:00 2001 From: Vangelis Banos Date: Mon, 10 Jun 2019 06:53:12 +0000 Subject: [PATCH] Check if connection is still open when trying to close When an exception is raised during network communication with the remote close, we handle it and we close the socket. Some times, the socket is already closed due to the exception and we get an extra `OSError [Errno 107] Transport endpoint is not connected` when trying to shutdown the socket. We add a check to avoid that. --- warcprox/mitmproxy.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/warcprox/mitmproxy.py b/warcprox/mitmproxy.py index d6a0593..5ef53c1 100644 --- a/warcprox/mitmproxy.py +++ b/warcprox/mitmproxy.py @@ -581,8 +581,12 @@ class MitmProxyHandler(http_server.BaseHTTPRequestHandler): self.logger.info('bad_hostnames_ports cache size: %d', len(self.server.bad_hostnames_ports)) - self._remote_server_conn.sock.shutdown(socket.SHUT_RDWR) - self._remote_server_conn.sock.close() + # Close the connection only if its still open. If its already + # closed, an `OSError` "([Errno 107] Transport endpoint is not + # connected)" would be raised. + if not is_connection_dropped(self._remote_server_conn): + self._remote_server_conn.sock.shutdown(socket.SHUT_RDWR) + self._remote_server_conn.sock.close() raise finally: if prox_rec_res: