Skip to content

Commit

Permalink
Ensure network connection is closed when handshake with peer fails (#…
Browse files Browse the repository at this point in the history
…1476)

* Ensure network connection is closed when handshake with peer fails

* clean up remaining unclosed transport warnings

* Add comment
  • Loading branch information
pipermerriam committed Nov 19, 2018
1 parent adf66da commit 6fca8f7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
16 changes: 14 additions & 2 deletions p2p/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,20 @@ async def handshake(
use_eip8 = False
initiator = HandshakeInitiator(remote, privkey, use_eip8, token)
reader, writer = await initiator.connect()
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
initiator, reader, writer, token)
try:
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
initiator, reader, writer, token)
except Exception:
# Note: This is one of two places where we manually handle closing the
# reader/writer connection pair in the event of an error during the
# peer connection and handshake process.
# See `p2p.peer.handshake` for the other.
if not reader.at_eof():
reader.feed_eof()
writer.close()
await asyncio.sleep(0)
raise

return aes_secret, mac_secret, egress_mac, ingress_mac, reader, writer


Expand Down
22 changes: 17 additions & 5 deletions p2p/peer.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,21 @@ async def handshake(remote: Node, factory: 'BasePeerFactory') -> 'BasePeer':
connection=connection,
inbound=False,
)
await peer.do_p2p_handshake()
await peer.do_sub_proto_handshake()

try:
await peer.do_p2p_handshake()
await peer.do_sub_proto_handshake()
except Exception:
# Note: This is one of two places where we manually handle closing the
# reader/writer connection pair in the event of an error during the
# peer connection and handshake process.
# See `p2p.auth.handshake` for the other.
if not reader.at_eof():
reader.feed_eof()
writer.close()
await asyncio.sleep(0)
raise

return peer


Expand Down Expand Up @@ -342,9 +355,8 @@ def close(self) -> None:
If the streams have already been closed, do nothing.
"""
if self.reader.at_eof():
return
self.reader.feed_eof()
if not self.reader.at_eof():
self.reader.feed_eof()
self.writer.close()

@property
Expand Down

0 comments on commit 6fca8f7

Please sign in to comment.