File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -12,6 +12,7 @@ module WebSocket
1212 class CloseFrame < Frame
1313 OPCODE = 0x8
1414 FORMAT = "na*"
15+ MAXIMUM_REASON_LENGTH = 123
1516
1617 # Unpack the frame data into a close code and reason.
1718 # @returns [Tuple(Integer, String)] The close code and reason.
@@ -45,6 +46,7 @@ def unpack
4546
4647 # Pack a close code and reason into the frame data.
4748 # If code is missing, reason is ignored.
49+ # The reason is truncated to 123 bytes.
4850 # @parameter code [Integer | Nil] The close code.
4951 # @parameter reason [String | Nil] The close reason.
5052 def pack ( code = nil , reason = nil )
@@ -53,6 +55,10 @@ def pack(code = nil, reason = nil)
5355 reason = reason . encode ( Encoding ::UTF_8 )
5456 end
5557
58+ if reason and reason . bytesize > MAXIMUM_REASON_LENGTH
59+ reason = reason . byteslice ( 0 , MAXIMUM_REASON_LENGTH ) . scrub ( "" )
60+ end
61+
5662 super ( [ code , reason ] . pack ( FORMAT ) )
5763 else
5864 super ( )
Original file line number Diff line number Diff line change 3030
3131 expect ( frame . payload ) . to be == "\x03 \xE8 Hello World" . b
3232 end
33+
34+ it "truncates the reason to fit in a control frame" do
35+ frame . pack ( 1000 , "x" * 200 )
36+
37+ expect ( frame . payload . bytesize ) . to be == 125
38+
39+ code , reason = frame . unpack
40+ expect ( code ) . to be == 1000
41+ expect ( reason ) . to be == "x" * 123
42+ end
43+
44+ it "doesn't split a multibyte character when truncating the reason" do
45+ frame . pack ( 1000 , ( "x" * 122 ) + "é" )
46+
47+ expect ( frame . payload . bytesize ) . to be == 124
48+
49+ code , reason = frame . unpack
50+ expect ( reason ) . to be == "x" * 122
51+ end
3352 end
3453
3554 with "#unpack" do
Original file line number Diff line number Diff line change 6969 expect ( connection ) . to be ( :closed? )
7070 end
7171
72+ it "truncates a long error message to fit in the close frame" do
73+ connection . close_write ( RuntimeError . new ( "x" * 200 ) )
74+
75+ frame = client . read_frame
76+ expect ( frame ) . to be_a ( Protocol ::WebSocket ::CloseFrame )
77+
78+ code , reason = frame . unpack
79+ expect ( code ) . to be == Protocol ::WebSocket ::Error ::INTERNAL_ERROR
80+ expect ( reason ) . to be == "x" * 123
81+ end
82+
7283 it "is not closed when close_write succeeds" do
7384 connection . close_write
7485
You can’t perform that action at this time.
0 commit comments