From bc7d29cb52cd23a8fd006dc50c63b7a6803cfe47 Mon Sep 17 00:00:00 2001 From: James Coglan Date: Fri, 17 Jul 2015 22:02:51 +0100 Subject: [PATCH] Emit a protocol error when a closing frame has a 1-byte payload. --- lib/websocket/driver/hybi.rb | 6 +++--- spec/websocket/driver/hybi_spec.rb | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/websocket/driver/hybi.rb b/lib/websocket/driver/hybi.rb index aaaaba8..ce1421f 100644 --- a/lib/websocket/driver/hybi.rb +++ b/lib/websocket/driver/hybi.rb @@ -355,8 +355,8 @@ module WebSocket @message << frame when OPCODES[:close] then - code = (bytesize >= 2) ? 256 * bytes[0] + bytes[1] : DEFAULT_ERROR_CODE - reason = (bytesize > 2) ? Driver.encode(bytes[2..-1] || [], :utf8) : '' + code = (bytesize >= 2) ? payload.unpack(PACK_FORMATS[2]).first : nil + reason = (bytesize > 2) ? Driver.encode(bytes[2..-1] || [], :utf8) : nil unless (bytesize == 0) or (code && code >= MIN_RESERVED_ERROR && code <= MAX_RESERVED_ERROR) or @@ -368,7 +368,7 @@ module WebSocket code = ERRORS[:protocol_error] end - shutdown(code, reason) + shutdown(code || DEFAULT_ERROR_CODE, reason || '') when OPCODES[:ping] then frame(payload, :pong) diff --git a/spec/websocket/driver/hybi_spec.rb b/spec/websocket/driver/hybi_spec.rb index 99a7323..e7ba348 100644 --- a/spec/websocket/driver/hybi_spec.rb +++ b/spec/websocket/driver/hybi_spec.rb @@ -563,6 +563,20 @@ describe WebSocket::Driver::Hybi do end end + describe "receiving a close frame with a too-short payload" do + before do + driver.parse [0x88, 0x01, 0x03].pack("C*") + end + + it "triggers the onclose event with a protocol error" do + expect(@close).to eq [1002, ""] + end + + it "changes the state to :closed" do + expect(driver.state).to eq :closed + end + end + describe "receiving a close frame with no code" do before do driver.parse [0x88, 0x00].pack("C*")