@@ -453,6 +453,7 @@ def connect(address, ssl_context=None, **config):
453
453
s .connect (address )
454
454
s .setsockopt (SOL_SOCKET , SO_KEEPALIVE , 1 if config .get ("keep_alive" , True ) else 0 )
455
455
except SocketError as error :
456
+ s .close ()
456
457
if error .errno in (61 , 111 , 10061 ):
457
458
raise ServiceUnavailable ("Failed to establish connection to {!r}" .format (address ))
458
459
else :
@@ -465,6 +466,7 @@ def connect(address, ssl_context=None, **config):
465
466
try :
466
467
s = ssl_context .wrap_socket (s , server_hostname = host if HAS_SNI else None )
467
468
except SSLError as cause :
469
+ s .close ()
468
470
error = SecurityError ("Failed to establish secure connection to {!r}" .format (cause .args [1 ]))
469
471
error .__cause__ = cause
470
472
raise error
@@ -473,13 +475,15 @@ def connect(address, ssl_context=None, **config):
473
475
# Check that the server provides a certificate
474
476
der_encoded_server_certificate = s .getpeercert (binary_form = True )
475
477
if der_encoded_server_certificate is None :
478
+ s .close ()
476
479
raise ProtocolError ("When using a secure socket, the server should always "
477
480
"provide a certificate" )
478
481
trust = config .get ("trust" , TRUST_DEFAULT )
479
482
if trust == TRUST_ON_FIRST_USE :
480
483
from neo4j .bolt .cert import PersonalCertificateStore
481
484
store = PersonalCertificateStore ()
482
485
if not store .match_or_trust (host , der_encoded_server_certificate ):
486
+ s .close ()
483
487
raise ProtocolError ("Server certificate does not match known certificate "
484
488
"for %r; check details in file %r" % (host , KNOWN_HOSTS ))
485
489
else :
@@ -502,10 +506,12 @@ def connect(address, ssl_context=None, **config):
502
506
# If no data is returned after a successful select
503
507
# response, the server has closed the connection
504
508
log_error ("S: [CLOSE]" )
509
+ s .close ()
505
510
raise ProtocolError ("Connection to %r closed without handshake response" % (address ,))
506
511
if data_size != 4 :
507
512
# Some garbled data has been received
508
513
log_error ("S: @*#!" )
514
+ s .close ()
509
515
raise ProtocolError ("Expected four byte handshake response, received %r instead" % data )
510
516
agreed_version , = struct_unpack (">I" , data )
511
517
log_info ("S: [HANDSHAKE] %d" , agreed_version )
@@ -517,8 +523,10 @@ def connect(address, ssl_context=None, **config):
517
523
return Connection (s , der_encoded_server_certificate = der_encoded_server_certificate , ** config )
518
524
elif agreed_version == 0x48545450 :
519
525
log_error ("S: [CLOSE]" )
526
+ s .close ()
520
527
raise ServiceUnavailable ("Cannot to connect to Bolt service on {!r} "
521
528
"(looks like HTTP)" .format (address ))
522
529
else :
523
530
log_error ("S: [CLOSE]" )
531
+ s .close ()
524
532
raise ProtocolError ("Unknown Bolt protocol version: {}" .format (agreed_version ))
0 commit comments