Respect a remote close during the ping protocol

This commit is contained in:
Alex Stokes 2019-10-24 19:44:52 +09:00
parent e157c3f654
commit 1cf239cce6
No known key found for this signature in database
GPG Key ID: 51CE1721B245C086

View File

@ -12,15 +12,21 @@ RESP_TIMEOUT = 60
logger = logging.getLogger("libp2p.host.ping") logger = logging.getLogger("libp2p.host.ping")
async def _handle_ping(stream: INetStream, peer_id: PeerID) -> None: async def _handle_ping(stream: INetStream, peer_id: PeerID) -> bool:
"""
Return a boolean indicating if we expect more pings from the peer at ``peer_id``.
"""
try: try:
payload = await asyncio.wait_for(stream.read(PING_LENGTH), RESP_TIMEOUT) payload = await asyncio.wait_for(stream.read(PING_LENGTH), RESP_TIMEOUT)
except asyncio.TimeoutError as error: except asyncio.TimeoutError as error:
logger.debug("Timed out waiting for ping from %s: %s", peer_id, error) logger.debug("Timed out waiting for ping from %s: %s", peer_id, error)
raise raise
except (StreamEOF, StreamReset) as error: except StreamEOF:
logger.debug("Other side closed while waiting for ping from %s", peer_id)
return False
except StreamReset as error:
logger.debug( logger.debug(
"Other side closed while waiting for ping from %s: %s", peer_id, error "Other side reset while waiting for ping from %s: %s", peer_id, error
) )
raise raise
except Exception as error: except Exception as error:
@ -30,6 +36,7 @@ async def _handle_ping(stream: INetStream, peer_id: PeerID) -> None:
logger.debug("Received ping from %s with data: 0x%s", peer_id, payload.hex()) logger.debug("Received ping from %s with data: 0x%s", peer_id, payload.hex())
await stream.write(payload) await stream.write(payload)
return True
async def handle_ping(stream: INetStream) -> None: async def handle_ping(stream: INetStream) -> None:
@ -41,7 +48,9 @@ async def handle_ping(stream: INetStream) -> None:
while True: while True:
try: try:
await _handle_ping(stream, peer_id) should_continue = await _handle_ping(stream, peer_id)
if not should_continue:
return
except Exception: except Exception:
await stream.reset() await stream.reset()
return return