Class: OverSIP::WebSocket::WsFraming

Inherits:
Object
  • Object
show all
Includes:
Logger
Defined in:
lib/oversip/websocket/ws_framing.rb

Constant Summary collapse

OPCODE =
{
  0  => :continuation,
  1  => :text,
  2  => :binary,
  8  => :close,
  9  => :ping,
  10 => :pong
}
KEEPALIVE_PING_FRAME =
keepalive_ping_frame
LOG_ID =
"WsFraming"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logger

close, fg_system_msg2str, init_logger_mq, load_methods, syslog_system_msg2str, syslog_user_msg2str

Constructor Details

#initialize(connection, buffer) ⇒ WsFraming

Returns a new instance of WsFraming.



37
38
39
40
41
42
# File 'lib/oversip/websocket/ws_framing.rb', line 37

def initialize connection, buffer
  @connection = connection
  @buffer = buffer
  @utf8_validator = ::OverSIP::WebSocket::FramingUtils::Utf8Validator.allocate
  @state = :init
end

Instance Attribute Details

#ws_app=(value) ⇒ Object (writeonly)

Sets the attribute ws_app

Parameters:

  • value

    the value to set the attribute ws_app to.



28
29
30
# File 'lib/oversip/websocket/ws_framing.rb', line 28

def ws_app=(value)
  @ws_app = value
end

Class Method Details

.class_initObject



23
24
25
# File 'lib/oversip/websocket/ws_framing.rb', line 23

def self.class_init
  @@max_frame_size = ::OverSIP.configuration[:websocket][:max_ws_frame_size]
end

Instance Method Details

#continuation_frame?Boolean

Returns:

  • (Boolean)


364
365
366
# File 'lib/oversip/websocket/ws_framing.rb', line 364

def continuation_frame?
  @opcode == 0
end

#control_frame?Boolean

Returns:

  • (Boolean)


354
355
356
# File 'lib/oversip/websocket/ws_framing.rb', line 354

def control_frame?
  @opcode > 2
end

#do_keep_alive(interval) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/oversip/websocket/ws_framing.rb', line 45

def do_keep_alive interval
  @keep_alive_timer = ::EM::PeriodicTimer.new(interval) do
    unless @connection.error?  # Ensure it.
      log_system_debug "sending keep-alive ping frame"  if $oversip_debug
      @connection.send_data KEEPALIVE_PING_FRAME
    else
      @keep_alive_timer.cancel
    end
  end
end

#log_idObject



32
33
34
# File 'lib/oversip/websocket/ws_framing.rb', line 32

def log_id
  LOG_ID
end

#receive_dataObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/oversip/websocket/ws_framing.rb', line 57

def receive_data
  while (case @state
    when :init
      return false  if @buffer.size < 2

      byte1 = @buffer.read(1).getbyte(0)
      byte2 = @buffer.read(1).getbyte(0)

      # FIN is the bit 0.
      @fin = (byte1 & 0b10000000) == 0b10000000

      # RSV1-3 are bits 1-3.
      @rsv1 = (byte1 & 0b01000000) == 0b01000000
      @rsv2 = (byte1 & 0b00100000) == 0b00100000
      @rsv3 = (byte1 & 0b00010000) == 0b00010000

      if @rsv1 or @rsv2 or @rsv3
        log_system_notice "frame has RSV bits set, clossing the connection"
        @connection.close 1002, "RSV bit set not supported"
        return false
      end

      # opcode are bits 4-7.
      @opcode = byte1 & 0b00001111
      unless (@sym_opcode = OPCODE[@opcode])
        @connection.close 1002, "unknown opcode=#{@opcode}"
        return false
      end

      # MASK is bit 8.
      @mask = (byte2 & 0b10000000) == 0b10000000
      unless @mask
        @connection.close 1002, "MASK bit not set"
        return false
      end

      # payload_len are bits 9-15.
      length = byte2 & 0b01111111

      case length
      # Length defined by 8 bytes.
      when 127
        @state = :payload_length_8_bytes
      # Length defined by 2 bytes.
      when 126
        @state = :payload_length_2_bytes
      # Length defined by already received 7 bits.
      else
        @payload_length = length
        @state = :masking_key
      end

      @payload = nil
      true

    when :payload_length_2_bytes
      return false  if @buffer.size < 2

      # Get the payload length and remove first two bytes fro
      # the buffer at the same time.
      @payload_length = @buffer.read(2).unpack('n').first

      @state = :masking_key
      true

    when :payload_length_8_bytes
      return false  if @buffer.size < 8

      # Get the payload length.
      # NOTE: Just take the last 4 bytes (4 GB frame is enough!!!),
      # Check that first 4 bytes are 0000. If not then the frame is bigger
      # than 4 GB and must be rejected!

      if @buffer.read(4).unpack('N').first != 0
        log_system_notice "frame size bigger than 4 GB, rejected"
        @connection.close 1008
        return false
      end

      @payload_length = @buffer.read(4).unpack('N').first

      @state = :masking_key
      true

    when :masking_key
      return false  if @buffer.size < 4

      # Get the masking key (4 bytes) and remove first 4 bytes
      # from the buffer.
      @masking_key = @buffer.read(4)

      @state = :check_frame
      true

    when :check_frame
      # All control frames MUST have a payload length of 125 bytes or
      # less and MUST NOT be fragmented.
      if control_frame? and @payload_length > 125
        log_system_notice "received invalid control frame (payload_length > 125), sending close frame"
        @connection.close 1002
        return false
      end

      if control_frame? and not @fin
        log_system_notice "received invalid control frame (FIN=0), sending close frame"
        @connection.close 1002, "forbidden FIN=0 in control frame"
        return false
      end

      # A continuation frame can only arrive if previously a text/binary frame
      # arrived with FIN=0.
      if continuation_frame? and not @msg_sym_opcode
        log_system_notice "invalid continuation frame received (no previous unfinished message), sending close frame"
        @connection.close 1002, "invalid continuation frame received"
        return false
      end

      # If a previous frame had FIN=0 and opcode=text/binary, then it cannot arrive
      # a new frame with opcode=text/binary.
      if @msg_sym_opcode and text_or_binary_frame?
        log_system_notice "invalid text/binary frame received (expecting a continuation frame), sending close frame"
        @connection.close 1002, "expected a continuation frame"
        return false
      end

      # Check max frame size.
      if @payload_length > @@max_frame_size
        @connection.close 1009, "frame too big"
        return false
      end

      @state = :payload_data
      true

    when :payload_data
      return false  if @buffer.size < @payload_length

      unless @payload_length.zero?
        # NOTE: @payload will always be Encoding::BINARY
        @payload = ::OverSIP::WebSocket::FramingUtils.unmask @buffer.read(@payload_length), @masking_key
      end
      # NOTE: @payload could be nil.

      @state = :process_frame
      true

    when :process_frame
      # Set it here as it could be changed later in this block.
      @state = :init

      case @sym_opcode

      when :text
        log_system_debug "received text frame: FIN=#{@fin}, RSV1-3=#{@rsv1}/#{@rsv2}/#{@rsv3}, payload_length=#{@payload_length}"  if $oversip_debug

        # Store the opcode of the first frame (if there is more frames for same message
        # they will have opcode=continuation).
        @msg_sym_opcode = @sym_opcode

        # Reset the UTF8 validator.
        @utf8_validator.reset

        if @payload
          if (valid_utf8 = @utf8_validator.validate(@payload)) == false
            log_system_notice "received single text frame contains invalid UTF-8, closing the connection"
            @connection.close 1007, "single text frame contains invalid UTF-8"
            return false
          end

          if @fin and not valid_utf8
            log_system_notice "received single text frame contains incomplete UTF-8, closing the connection"
            @connection.close 1007, "single text frame contains incomplete UTF-8"
            return false
          end

          # If @ws_app.receive_payload_data returns false it means that total
          # message size is too big.
          unless @ws_app.receive_payload_data @payload
            @connection.close 1009, "message too big"
            return false
          end
        end

        # If message is finished tell it to the WS application.
        if @fin
          @ws_app.message_done @msg_sym_opcode
          @msg_sym_opcode = nil
        end

      when :binary
        log_system_debug "received binary frame: FIN=#{@fin}, RSV1-3=#{@rsv1}/#{@rsv2}/#{@rsv3}, payload_length=#{@payload_length}"  if $oversip_debug

        # Store the opcode of the first frame (if there is more frames for same message
        # they will have opcode=continuation).
        @msg_sym_opcode = @sym_opcode

        if @payload
          # If @ws_app.receive_payload_data returns false it means that total
          # message size is too big.
          unless @ws_app.receive_payload_data @payload
            @connection.close 1009, "message too big"
            return false
          end
        end

        # If message is finished tell it to the WS application.
        if @fin
          @ws_app.message_done @msg_sym_opcode
          @msg_sym_opcode = nil
        end

      when :continuation
        log_system_debug "received continuation frame: FIN=#{@fin}, RSV1-3=#{@rsv1}/#{@rsv2}/#{@rsv3}, payload_length=#{@payload_length}"  if $oversip_debug

        if @payload
          if @msg_sym_opcode == :text
            if (valid_utf8 = @utf8_validator.validate(@payload)) == false
              log_system_notice "received continuation text frame contains invalid UTF-8, closing the connection"
              @connection.close 1007, "continuation text frame contains invalid UTF-8"
              return false
            end

            if @fin and not valid_utf8
              log_system_notice "received continuation final text frame contains incomplete UTF-8, closing the connection"
              @connection.close 1007, "continuation final text frame contains incomplete UTF-8"
              return false
            end
          end

          return false  unless @ws_app.receive_payload_data @payload
        end

        # If message is finished tell it to the WS application.
        if @fin
          @ws_app.message_done @msg_sym_opcode
          @msg_sym_opcode = nil
        end

      when :close
        if @payload_length >= 2
          status = ""
          status << @payload.getbyte(0) << @payload.getbyte(1)
          status =  status.unpack('n').first
          if (reason = @payload[2..-1])
            # Reset the UTF8 validator.
            @utf8_validator.reset

            # The UTF-8 validator returns:
            # - true: Valid UTF-8 string.
            # - nil: Valid but not terminated UTF-8 string.
            # - false: Invalid UTF-8 string.
            # So it must be true for the close frame reason.
            unless @utf8_validator.validate(reason)
              log_system_notice "received close frame with invalid UTF-8 data in the reason: status=#{status.inspect}"
              @connection.close 1007, "close frame reason contains incomplete UTF-8"
              return false
            end
          end
        else
          status = nil
        end

        case status
        when 1002
          log_system_notice "received close frame due to WS protocol error: status=1002, reason=#{reason.inspect}"
        when 1003
          log_system_notice "received close frame due to sent data type: status=1003, reason=#{reason.inspect}"
        when 1007
          log_system_notice "received close frame due to non valid UTF-8 data sent: status=1007, reason=#{reason.inspect}"
        when 1009
          log_system_notice "received close frame due to too big message sent: status=1009, reason=#{reason.inspect}"
        when 1010
          log_system_notice "received close frame due to extensions negotiation failure: status=1010, reason=#{reason.inspect}"
        else
          log_system_debug "received close frame: status=#{status.inspect}, reason=#{reason.inspect}"  if $oversip_debug
        end

        @connection.client_closed = true
        @connection.close nil, nil
        return false

      when :ping
        log_system_debug "received ping frame: payload_length=#{@payload_length}"  if $oversip_debug
        send_pong_frame @payload

      when :pong
        log_system_debug "received pong frame: payload_length=#{@payload_length}"  if $oversip_debug

      end

      true
    end)
  end # while

end

#send_binary_frame(message) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/oversip/websocket/ws_framing.rb', line 404

def send_binary_frame message
  log_system_debug "sending binary frame: payload_length=#{message.bytesize}"  if $oversip_debug

  frame = "".encode ::Encoding::BINARY

  # byte1 = OPCODE_TO_INT[:binary] | 0b10000000 => 130
  #
  # - FIN bit set.
  # - RSV1-3 bits not set.
  # - opcode = 2
  frame << 130

  length = message.bytesize
  if length <= 125
    frame << length # since rsv4 is 0
  elsif length < 65536 # write 2 byte length
    frame << 126
    frame << [length].pack('n')
  else # write 8 byte length
    frame << 127
    frame << [length >> 32, length & 0xFFFFFFFF].pack("NN")
  end

  if message.encoding == ::Encoding::BINARY
    frame << message
  else
    frame << message.force_encoding(::Encoding::BINARY)
  end

  @connection.send_data frame
  true
end

#send_close_frame(status = nil, reason = nil, in_reply_to_close = nil) ⇒ Object



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/oversip/websocket/ws_framing.rb', line 502

def send_close_frame status=nil, reason=nil, in_reply_to_close=nil
  @keep_alive_timer.cancel  if @keep_alive_timer

  unless in_reply_to_close
    log_system_debug "sending close frame: status=#{status.inspect}, reason=#{reason.inspect}"  if $oversip_debug
  else
    log_system_debug "sending reply close frame: status=#{status.inspect}, reason=#{reason.inspect}"  if $oversip_debug
  end

  @buffer.clear

  frame = "".encode ::Encoding::BINARY

  # byte1 = OPCODE_TO_INT[:close] | 0b10000000 => 136
  #
  # - FIN bit set.
  # - RSV1-3 bits not set.
  # - opcode = 8
  frame << 136
  if status
    length = ( reason ? 2 + reason.bytesize : 2 )
  else
    length = 0
  end

  frame << length # since rsv4 is 0
  if status
    frame << [status].pack('n')
    if reason
      if reason.encoding == ::Encoding::BINARY
        frame << reason
      else
        frame << reason.force_encoding(::Encoding::BINARY)
      end
    end
  end

  @connection.send_data frame
  true
end

#send_ping_frame(data = nil) ⇒ Object



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/oversip/websocket/ws_framing.rb', line 438

def send_ping_frame data=nil
  if data
    log_system_debug "sending ping frame: payload_length=#{data.bytesize}"  if $oversip_debug
  else
    log_system_debug "sending ping frame: payload_length=0"  if $oversip_debug
  end

  frame = "".encode ::Encoding::BINARY

  # byte1 = OPCODE_TO_INT[:ping] | 0b10000000 => 137
  #
  # - FIN bit set.
  # - RSV1-3 bits not set.
  # - opcode = 9
  frame << 137

  length = ( data ? data.bytesize : 0 )
  frame << length

  if data
    if data.encoding == ::Encoding::BINARY
      frame << data
    else
      frame << data.force_encoding(::Encoding::BINARY)
    end
  end

  @connection.send_data frame
  true
end

#send_pong_frame(data = nil) ⇒ Object



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/oversip/websocket/ws_framing.rb', line 470

def send_pong_frame data=nil
  if data
    log_system_debug "sending pong frame: payload_length=#{data.bytesize}"  if $oversip_debug
  else
    log_system_debug "sending pong frame: payload_length=0"  if $oversip_debug
  end

  frame = "".encode ::Encoding::BINARY

  # byte1 = OPCODE_TO_INT[:pong] | 0b10000000 => 138
  #
  # - FIN bit set.
  # - RSV1-3 bits not set.
  # - opcode = 10
  frame << 138

  length = ( data ? data.bytesize : 0 )
  frame << length

  if data
    if data.encoding == ::Encoding::BINARY
      frame << data
    else
      frame << data.force_encoding(::Encoding::BINARY)
    end
  end

  @connection.send_data frame
  true
end

#send_text_frame(message) ⇒ Object

NOTE: A WS message is always set in a single WS frame.



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/oversip/websocket/ws_framing.rb', line 370

def send_text_frame message
  log_system_debug "sending text frame: payload_length=#{message.bytesize}"  if $oversip_debug

  frame = "".encode ::Encoding::BINARY

  # byte1 = OPCODE_TO_INT[:text] | 0b10000000 => 129
  #
  # - FIN bit set.
  # - RSV1-3 bits not set.
  # - opcode = 1
  frame << 129

  length = message.bytesize
  if length <= 125
    frame << length # since rsv4 is 0
  elsif length < 65536 # write 2 byte length
    frame << 126
    frame << [length].pack('n')
  else # write 8 byte length
    frame << 127
    frame << [length >> 32, length & 0xFFFFFFFF].pack("NN")
  end

  if message.encoding == ::Encoding::BINARY
    frame << message
  else
    frame << message.force_encoding(::Encoding::BINARY)
  end

  @connection.send_data frame
  true
end

#text_or_binary_frame?Boolean

Returns:

  • (Boolean)


359
360
361
# File 'lib/oversip/websocket/ws_framing.rb', line 359

def text_or_binary_frame?
  @opcode == 1 or @opcode == 2
end