Skip to content

Commit

Permalink
Don't answer pings on closing connection.
Browse files Browse the repository at this point in the history
Technically, this is the wrong behavior, but I'll live with this in the
legacy layer. The new Sans I/O layer has the right behavior.

Fix #669.
  • Loading branch information
aaugustin committed Jun 17, 2021
1 parent f148d82 commit b2a95c4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
13 changes: 7 additions & 6 deletions src/websockets/legacy/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,12 +975,13 @@ async def read_data_frame(self, max_size: Optional[int]) -> Optional[Frame]:
return None

elif frame.opcode == OP_PING:
# Answer pings.
try:
await self.pong(frame.data)
except ConnectionClosed:
# Connection closed before we could respond to the ping.
pass
# Answer pings, unless connection is CLOSING.
if self.state is State.OPEN:
try:
await self.pong(frame.data)
except ConnectionClosed:
# Connection closed while draining write buffer.
pass

elif frame.opcode == OP_PONG:
if frame.data in self.pings:
Expand Down
12 changes: 11 additions & 1 deletion tests/legacy/test_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,10 +909,20 @@ def test_answer_ping(self):
self.run_loop_once()
self.assertOneFrameSent(True, OP_PONG, b"test")

def test_answer_ping_does_not_crash_if_connection_closing(self):
close_task = self.half_close_connection_local()

self.receive_frame(Frame(True, OP_PING, b"test"))

with self.assertNoLogs():
self.loop.run_until_complete(self.protocol.close())

self.loop.run_until_complete(close_task) # cleanup

def test_answer_ping_does_not_crash_if_connection_closed(self):
self.make_drain_slow()
# Drop the connection right after receiving a ping frame,
# which prevents responding wwith a pong frame properly.
# which prevents responding with a pong frame properly.
self.receive_frame(Frame(True, OP_PING, b"test"))
self.receive_eof()

Expand Down

0 comments on commit b2a95c4

Please sign in to comment.