Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 31 additions & 11 deletions test/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
ConnectionRequested,
TextReceived,
BytesReceived,
)
PingReceived,
PongReceived)
from wsproto.frame_protocol import CloseReason, FrameProtocol


Expand Down Expand Up @@ -125,22 +126,19 @@ def test_ping_pong(self, as_client):

payload = b'x' * 23

# Send a PING message
me.ping(payload)
wire_data = me.bytes_to_send()
assert wire_data[0] == 0x89
masked = bool(wire_data[1] & 0x80)
assert wire_data[1] & ~0x80 == len(payload)
if masked:
maskbytes = itertools.cycle(bytearray(wire_data[2:6]))
data = bytearray(b ^ next(maskbytes)
for b in bytearray(wire_data[6:]))
else:
data = wire_data[2:]
assert data == payload

# Verify that the peer emits the PingReceive event with the correct payload
them.receive_bytes(wire_data)
event = next(them.events())
assert isinstance(event, PingReceived)
assert event.payload == payload
with pytest.raises(StopIteration):
print(repr(next(them.events())))

# Let the peer send the automatic PONG message
wire_data = them.bytes_to_send()
assert wire_data[0] == 0x8a
masked = bool(wire_data[1] & 0x80)
Expand All @@ -153,6 +151,28 @@ def test_ping_pong(self, as_client):
data = wire_data[2:]
assert data == payload

# Verify that connection emits the PongReceive event with the correct payload
me.receive_bytes(wire_data)
event = next(me.events())
assert isinstance(event, PongReceived)
assert event.payload == payload
with pytest.raises(StopIteration):
print(repr(next(me.events())))

@pytest.mark.parametrize('args, expected_payload', [
((), b''),
((b'abcdef',), b'abcdef')
], ids=['nopayload', 'payload'])
def test_unsolicited_pong(self, args, expected_payload):
client, server = self.create_connection()
client.pong(*args)
wire_data = client.bytes_to_send()
server.receive_bytes(wire_data)
events = list(server.events())
assert len(events) == 1
assert isinstance(events[0], PongReceived)
assert events[0].payload == expected_payload

@pytest.mark.parametrize('text,payload,full_message,full_frame', [
(True, u'ƒñö®∂😎', True, True),
(True, u'ƒñö®∂😎', False, True),
Expand Down
27 changes: 26 additions & 1 deletion wsproto/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from .events import (
ConnectionRequested, ConnectionEstablished, ConnectionClosed,
ConnectionFailed, TextReceived, BytesReceived
ConnectionFailed, TextReceived, BytesReceived, PingReceived, PongReceived
)
from .frame_protocol import FrameProtocol, ParseFailed, CloseReason, Opcode

Expand Down Expand Up @@ -275,6 +275,11 @@ def events(self):
if frame.opcode is Opcode.PING:
assert frame.frame_finished and frame.message_finished
self._outgoing += self._proto.pong(frame.payload)
yield PingReceived(frame.payload)

elif frame.opcode is Opcode.PONG:
assert frame.frame_finished and frame.message_finished
yield PongReceived(frame.payload)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we verify that the pong-payload is the same as what we sent earlier with ping(payload)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would require storing the payload of every PING message. Can we even rely on the ordering of the PONGs vs PINGs?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From RFC6455:

It SHOULD respond with Pong frame as soon as is practical.

But it is also allowed to send PONGs, without receiving a PING first.

A Pong frame sent in response to a Ping frame must have identical "Application data" as found in the message body of the Ping frame being replied to.

Yes, I think we should store the ping payload, and verify it against the first pong we receive, and the reset it to None (or similar?).

If we want to overcomplicate this, we should introduce a stack that holds all ping-payloads, and we pop them off one-by-one for every pong received...

For now, I would just clearly document that every ping(payload) overwrites the "global" expected pong response payload. So, don't send a PING before you got the PONG of the last one back.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we definitely can't verify the payload. RFC 6455 says:

A Pong frame MAY be sent unsolicited. This serves as a unidirectional heartbeat.

So if we get a Pong frame with an unexpected payload, we have no way to know whether that's because the peer screwed up the payload, or because they just happened to spontaneously send us a weird Pong and the one we're expecting will be along any moment. So even if we stored the payload, we couldn't do anything with that information.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the protocol lets either side send PONGs arbitrarily, how do we know that a particular PONG was a response to a PING that we sent?

@Kriechi Kriechi Jul 25, 2017 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, arguably this is difficult. I couldn't find any errata in the RFC (yet).

IMO this sentence in the RFC is pretty clear:

A Pong frame sent in response to a Ping frame must have identical
"Application data" as found in the message body of the Ping frame
being replied to.

Strangely it doesn't make use of the usual "MUST HAVE" in capital letters to indicate an absolute requirement / condition...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RFC 6455 is generally pretty clear about what invariants it wants implementors to enforce on their peers. There are lots of cases where it says "if your peer does this, you MUST immediately close the connection". This isn't one of them, and my guess is that this is intentional (even if the lack of all-caps might be accidental), because, well, AFAICT it's literally impossible to enforce even if we want to :-).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think my quick stack idea might work.
But I agree that this is too complicated.

I propose to ignore the payload verification in wsproto, and clearly document that it is the users responsibility to compare the payloads (if it is important to their use case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you propose that even the users would accomplish that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have to give a solution... 😄
Sounds terrible, but it is what it is.


elif frame.opcode is Opcode.CLOSE:
code, reason = frame.payload
Expand Down Expand Up @@ -435,5 +440,25 @@ def accept(self, event, subprotocol=None):
self._state = ConnectionState.OPEN

def ping(self, payload=None):
"""
Send a PING message to the peer.

:param payload: an optional payload to send with the message
"""

payload = bytes(payload or b'')
self._outgoing += self._proto.ping(payload)

def pong(self, payload=None):
"""
Send a PONG message to the peer.

This method can be used to send an unsolicted PONG to the peer.
It is not needed otherwise since every received PING causes a
corresponding PONG to be sent automatically.

:param payload: an optional payload to send with the message
"""

payload = bytes(payload or b'')
self._outgoing += self._proto.pong(payload)
10 changes: 10 additions & 0 deletions wsproto/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,13 @@ class TextReceived(DataReceived):

class BytesReceived(DataReceived):
pass


class PingReceived(object):
def __init__(self, payload):
self.payload = payload


class PongReceived(object):
def __init__(self, payload):
self.payload = payload