@@ -1083,6 +1083,7 @@ async def create_connection(
10831083 connection in the background. When successful, the coroutine
10841084 returns a (transport, protocol) pair.
10851085 """
1086+ sock_was_provided = sock is not None
10861087 if server_hostname is not None and not ssl :
10871088 raise ValueError ('server_hostname is only meaningful with ssl' )
10881089
@@ -1204,7 +1205,8 @@ async def create_connection(
12041205 transport , protocol = await self ._create_connection_transport (
12051206 sock , protocol_factory , ssl , server_hostname ,
12061207 ssl_handshake_timeout = ssl_handshake_timeout ,
1207- ssl_shutdown_timeout = ssl_shutdown_timeout )
1208+ ssl_shutdown_timeout = ssl_shutdown_timeout ,
1209+ sock_was_provided = sock_was_provided )
12081210 if self ._debug :
12091211 # Get the socket from the transport because SSL transport closes
12101212 # the old socket and creates a new SSL socket
@@ -1217,7 +1219,8 @@ async def _create_connection_transport(
12171219 self , sock , protocol_factory , ssl ,
12181220 server_hostname , server_side = False ,
12191221 ssl_handshake_timeout = None ,
1220- ssl_shutdown_timeout = None , context = None ):
1222+ ssl_shutdown_timeout = None , context = None ,
1223+ sock_was_provided = False ):
12211224
12221225 try :
12231226 sock .setblocking (False )
@@ -1236,8 +1239,10 @@ async def _create_connection_transport(
12361239 else :
12371240 transport = self ._make_socket_transport (sock , protocol , waiter , context = context )
12381241 except :
1239- # gh-153133: close the socket if the transport is never created.
1240- sock .close ()
1242+ # gh-153133: close internally created sockets if the transport is
1243+ # never created.
1244+ if not sock_was_provided :
1245+ sock .close ()
12411246 raise
12421247
12431248 try :
@@ -1705,7 +1710,8 @@ async def connect_accepted_socket(
17051710 transport , protocol = await self ._create_connection_transport (
17061711 sock , protocol_factory , ssl , '' , server_side = True ,
17071712 ssl_handshake_timeout = ssl_handshake_timeout ,
1708- ssl_shutdown_timeout = ssl_shutdown_timeout )
1713+ ssl_shutdown_timeout = ssl_shutdown_timeout ,
1714+ sock_was_provided = True )
17091715 if self ._debug :
17101716 # Get the socket from the transport because SSL transport closes
17111717 # the old socket and creates a new SSL socket
0 commit comments