danni / uwebsockets

Micropython websockets implementation
MIT License
182 stars 40 forks source link

Partial recv can cause failure #16

Open osresearch opened 3 years ago

osresearch commented 3 years ago

sock.recv(length) is not guaranteed to return all the bytes in a single call, so it is necessary to wrap it in recv_frame(). Otherwise a slow network can cause unrecoverable protocol errors.

diff --git a/uwebsockets/protocol.py b/uwebsockets/protocol.py
index 64f4d06..8ed34b8 100644
--- a/uwebsockets/protocol.py
+++ b/uwebsockets/protocol.py
@@ -113,7 +115,9 @@ class Websocket:
             mask_bits = self.sock.read(4)

         try:
-            data = self.sock.read(length)
+            data = b''
+            while len(data) < length:
+                data += self.sock.read(length - len(data))
         except MemoryError:
             # We can't receive this many bytes, close the socket
             if __debug__: LOGGER.debug("Frame of length %s too big. Closing",
danni commented 3 years ago

Hi, yes! Can you please submit a pull request? Thanks.