diff --git a/src/WebSocketClient.cpp b/src/WebSocketClient.cpp index ab41b0a..e97d4a9 100644 --- a/src/WebSocketClient.cpp +++ b/src/WebSocketClient.cpp @@ -206,25 +206,54 @@ int WebSocketClient::parseMessage() iRxMasked = (length & 0x80); length &= 0x7f; - // read the RX size - if (length < 126) + // work out how many extended length and mask bytes follow the + // initial opcode + length bytes + int extendedLength = 0; + if (length == 126) { - iRxSize = length; + extendedLength = 2; } - else if (length == 126) + else if (length == 127) { - iRxSize = (HttpClient::read() << 8) | HttpClient::read(); + extendedLength = 8; } - else + int maskLength = iRxMasked ? (int)sizeof(iRxMaskKey) : 0; + + // make sure the remaining header bytes are available before reading + // them, otherwise the frame header is incomplete + if (HttpClient::available() < (extendedLength + maskLength)) + { + return 0; + } + + // read the RX size + iRxSize = length; + if (length == 126) + { + // read each byte in a well-defined order (the evaluation order of + // multiple read() calls in a single expression is unspecified) + uint8_t b1 = HttpClient::read(); + uint8_t b0 = HttpClient::read(); + iRxSize = ((uint64_t)b1 << 8) | b0; + } + else if (length == 127) { - iRxSize = ((uint64_t)HttpClient::read() << 56) | - ((uint64_t)HttpClient::read() << 48) | - ((uint64_t)HttpClient::read() << 40) | - ((uint64_t)HttpClient::read() << 32) | - ((uint64_t)HttpClient::read() << 24) | - ((uint64_t)HttpClient::read() << 16) | - ((uint64_t)HttpClient::read() << 8) | - (uint64_t)HttpClient::read(); + uint8_t b7 = HttpClient::read(); + uint8_t b6 = HttpClient::read(); + uint8_t b5 = HttpClient::read(); + uint8_t b4 = HttpClient::read(); + uint8_t b3 = HttpClient::read(); + uint8_t b2 = HttpClient::read(); + uint8_t b1 = HttpClient::read(); + uint8_t b0 = HttpClient::read(); + iRxSize = ((uint64_t)b7 << 56) | + ((uint64_t)b6 << 48) | + ((uint64_t)b5 << 40) | + ((uint64_t)b4 << 32) | + ((uint64_t)b3 << 24) | + ((uint64_t)b2 << 16) | + ((uint64_t)b1 << 8) | + (uint64_t)b0; } // read in the mask, if present