@@ -832,7 +832,7 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
832832 )
833833 self = cls .__new__ (cls , ** kwargs )
834834 super (SSLSocket , self ).__init__ (** kwargs )
835- self . settimeout ( sock .gettimeout () )
835+ sock_timeout = sock .gettimeout ()
836836 sock .detach ()
837837
838838 self ._context = context
@@ -851,9 +851,38 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
851851 if e .errno != errno .ENOTCONN :
852852 raise
853853 connected = False
854+ blocking = self .getblocking ()
855+ self .setblocking (False )
856+ try :
857+ # We are not connected so this is not supposed to block, but
858+ # testing revealed otherwise on macOS and Windows so we do
859+ # the non-blocking dance regardless. Our raise when any data
860+ # is found means consuming the data is harmless.
861+ notconn_pre_handshake_data = self .recv (1 )
862+ except OSError as e :
863+ # EINVAL occurs for recv(1) on non-connected on unix sockets.
864+ if e .errno not in (errno .ENOTCONN , errno .EINVAL ):
865+ raise
866+ notconn_pre_handshake_data = b''
867+ self .setblocking (blocking )
868+ if notconn_pre_handshake_data :
869+ # This prevents pending data sent to the socket before it was
870+ # closed from escaping to the caller who could otherwise
871+ # presume it came through a successful TLS connection.
872+ reason = "Closed before TLS handshake with data in recv buffer."
873+ notconn_pre_handshake_data_error = SSLError (e .errno , reason )
874+ # Add the SSLError attributes that _ssl.c always adds.
875+ notconn_pre_handshake_data_error .reason = reason
876+ notconn_pre_handshake_data_error .library = None
877+ try :
878+ self .close ()
879+ except OSError :
880+ pass
881+ raise notconn_pre_handshake_data_error
854882 else :
855883 connected = True
856884
885+ self .settimeout (sock_timeout ) # Must come after setblocking() calls.
857886 self ._connected = connected
858887 if connected :
859888 # create the SSL object
0 commit comments