Source

ginsfsm / ginsfsm / protocols / sockjs / server / c_websocket.py

The default branch has multiple heads

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
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
402
403
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
436
437
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
468
469
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
500
501
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# -*- encoding: utf-8 -*-
""" GWebSocket GObj

Server-side implementation of the WebSocket protocol.

`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server.

.. warning::

   The WebSocket protocol was recently finalized as `RFC 6455
   <http://tools.ietf.org/html/rfc6455>`_ and is not yet supported in
   all browsers.  Refer to http://caniuse.com/websockets for details
   on compatibility.

   This module only supports the latest version 13 of the RFC 6455 protocol.

.. autoclass:: GWebSocket
    :members: start_up

"""
import base64
from hashlib import sha1
import struct
import logging

import ginsfsm.escape
from ginsfsm.c_timer import GTimer
from ginsfsm.compat import binary_type
from ginsfsm.gobj import GObj
from ginsfsm.gmsg import (
    GMsg,
    gmsg_remove,
)
from ginsfsm.utils import (
    string_to_pack,
)

STRUCT_2BYTES = struct.Struct("!H")
STRUCT_4BYTES = struct.Struct("!Q")
STRUCT_BB = struct.Struct("BB")
STRUCT_BBH = struct.Struct("!BBH")
STRUCT_BBQ = struct.Struct("!BBQ")

OPCODE_CONTINUATION_FRAME = 0x0
OPCODE_TEXT_FRAME = 0x01
OPCODE_BINARY_FRAME = 0x02

OPCODE_CONTROL_CLOSE = 0x08
OPCODE_CONTROL_PING = 0x09
OPCODE_CONTROL_PONG = 0x0A


class FRAME_HEADER_S(object):
    """ Websocket frame header

    This class controls the first two bytes of header:

      0                   1
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
     +-+-+-+-+-------+-+-------------+
     |F|R|R|R| opcode|M| Payload len |
     |I|S|S|S|  (4)  |A|     (7)     |
     |N|V|V|V|       |S|             |
     | |1|2|3|       |K|             |
     +-+-+-+-+-------+-+-------------+

    Full header:

      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     +-+-+-+-+-------+-+-------------+-------------------------------+
     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
     | |1|2|3|       |K|             |                               |
     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
     |     Extended payload length continued, if payload len == 127  |
     + - - - - - - - - - - - - - - - +-------------------------------+
     |                               |Masking-key, if MASK set to 1  |
     +-------------------------------+-------------------------------+
     | Masking-key (continued)       |          Payload Data         |
     +-------------------------------- - - - - - - - - - - - - - - - +
     :                     Payload Data continued ...                :
     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
     |                     Payload Data continued ...                |
     +---------------------------------------------------------------+
    """

    packer = struct.Struct('BB')

    def __init__(self):
        # Information of the first two bytes header
        self.fin = 0  # final fragment in a message
        self.reserved_bits = 0
        self.opcode = 0
        self.mask = 0  # Set to 1 a  masking key is present in masking-key
        self.payload_len = 0

        # variables to help encode/decode frame
        self.complete = False
        self.error = False
        self.must_close = False
        self.must_read_extended_payload_length = False
        self.must_read_masking_key = False
        self.must_read_payload_data = False
        self.masking_key = 0
        self.payload_data_length = 0

    def network_to_host(self, data):
        if len(data) != 2:
            raise RuntimeError('ERROR ntoh needs two bytes.')
        byte1, byte2 = self.packer.unpack(bytes(data))

        # decod byte1
        self.fin = byte1 & 0x80
        self.reserved_bits = byte1 & 0x70
        self.opcode = byte1 & 0x0f

        # decod byte2
        self.mask = byte2 & 0x80
        self.payload_len = byte2 & 0x7f

    def host_to_network(self, fin, opcode, mask, payload_len):
        self.fin = fin
        self.reserved_bits = 0  # by the moment it's ignored.
        self.opcode = opcode
        self.mask = mask
        self.payload_len = payload_len

        if self.fin:
            byte1 = (self.opcode & 0x0f) | 0x80
        else:
            byte1 = self.opcode

        byte2 = self.
        if self.mask:
            byte2 = byte2 & 0x80

        trama = self.packer.pack(byte1, byte2)
        return bytearray(trama)

    def yyy(self):
        ln = self.frame_len
        if ln < 126:
            # next: write 4 bytes of masking key IF client
            byte2 = self.frame_len
        elif ln <= 0xFFFF:
            # next: write 4 bytes of masking key IF client
            # next: write 2 bytes of extended payload length
            byte2 = 126
        else:
            # next: write 4 bytes of masking key IF client
            # next: write 8 bytes of extended payload length
            byte2 = 127
        if self.mask:
            byte2 = byte2 & 0x80

        trama = self.packer.pack(byte1, byte2)
        return bytearray(trama)

    def xxx(self, ln):
        if ln < 126:
            # next: read 4 bytes of masking key
            self.frame_len = self.payload_len
        elif ln == 126:
            # next: read 2 bytes of extended payload length
            # next: read 4 bytes of masking key
            self.frame_len = 0
        elif ln == 127:
            # next: read 8 bytes of extended payload length
            # next: read 4 bytes of masking key
            self.frame_len = 0


    @property
    def size(self):
        return self.packer.size


def analize_header(gmsg, iam_server):
    """ Get and check the header from gmsg.
    """
    hd = FRAME_HEADER_S()
    data = gmsg.getdata(hd.size)
    if data is None:
        # there is no enough data
        return hd
    hd.network_to_host(data)
    hd.complete = True
    if hd.reserved_bits:
        # client is using as-yet-undefined extensions; abort
        hd.error = True
        logging.error(
            "ERROR websocket header: using as-yet-undefined reserved_bits")
        return hd

    if hd.opcode_is_control:
        #
        #   Control opcode
        #
        control = hd.opcode
        if control == OPCODE_CONTROL_CLOSE:
            hd.close = True
            pass
        elif control == OPCODE_CONTROL_PING:
            pass
        elif control == OPCODE_CONTROL_PONG:
            pass
        if hd.payload_len >= 126:
            # control frames must have payload < 126; abort
            hd.error = True
            logging.error("ERROR websocket header: too big control frame payloda")
    else:
        #
        #   Data opcode
        #
        if iam_server and not hd.mask:
            # Unmasked frame; abort
            hd.error = True
            logging.error("ERROR websocket header: iam_server but unmasked frame")

    return hd


#----------------------------------------------------#
#               Machine Actions
#----------------------------------------------------#
def ac_timeout_waiting_frame_header(self, event):
    """ Timeout frame start.
        Too much time waiting the frame header.
    """
    self.remove_gmsgs()
    self.gsock.mt_drop()


def ac_timeout_waiting_payload_data(self, event):
    """ Timeout frame start.
        Too much time waiting the frame header.
    """
    self.remove_gmsgs()
    self.gsock.mt_drop()


def ac_disconnected(self, event):
    """ Parter has disconnected.
    """


def ac_process_frame_header_start(self, event):
    """ Process two first bytes frame start.
    """
    gmsg = self.rx_gmsg
    if not gmsg:
        gmsg = self.rx_gmsg = GMsg(1024)
    if event.data:
        gmsg.putdata(event.data)

    #
    # Have we got already a frame header struct?
    #
    hd = self.frame_header
    if hd is None:
        #
        # Read and analize the two first header bytes.
        # Reject it if there is no at list 2 bytes.
        #
        hd = analize_header(gmsg, self.iam_server)
        if hd.close or hd.error:
            self.remove_gmsgs()
            self.gsock.mt_drop()
            return
        if not hd.complete:
            return
        self.frame_header = hd

    #
    #  Calculate the frame lenght
    #
    ln = hd.payload_len

    if ln < 126:
        # we've got the length.
        # next: read 4 bytes of masking key if iam_server
        self.frame_len = hd.payload_len
        print ">>>> frame_len", self.frame_len
        if self.frame_len > 0:
            print ">>>>>>>>>> PAYLOAD GMSG"
            self.data_gmsg = GMsg(self.frame_len)
        if self.iam_server:
            self.set_new_state('ST_WAITING_HEADER_MASKING_KEY')
        else:
            self.set_new_state('ST_WAITING_PAYLOAD_DATA')

    elif ln == 126:
        # next: read 2 bytes of extended payload length
        # next: read 4 bytes of masking key if iam_server
        self.set_new_state('ST_WAITING_HEADER_EXTENDED_LENGTH')

    elif ln == 127:
        # next: read 8 bytes of extended payload length
        # next: read 4 bytes of masking key if iam_server
        self.set_new_state('ST_WAITING_HEADER_EXTENDED_LENGTH')

    self.send_event(self, 'EV_RX_DATA', data=None)


def ac_process_header_extended_length(self, event):
    """
    """
    gmsg = self.rx_gmsg
    if event.data:
        gmsg.putdata(event.data)

    hd = self.frame_header
    ln = hd.payload_len
    if ln == 126:
        # read 2 bytes of extended payload length
        # next: read 4 bytes of masking key if iam_server
        data = gmsg.getdata(2)
        if data is None:
            # wait: there is no enough data
            return
        self.frame_len = data

    elif ln == 127:
        # read 8 bytes of extended payload length
        # next: read 4 bytes of masking key if iam_server
        data = gmsg.getdata(8)
        if data is None:
            # wait: there is no enough data
            return
        self.frame_len = data

    else:
        logging.error("ERROR payload length: %d", ln)
        self.remove_gmsgs()
        self.gsock.mt_drop()
        return

    self.data_gmsg = GMsg(self.frame_len)

    if self.iam_server:
        self.set_new_state('ST_WAITING_HEADER_MASKING_KEY')
        self.send_event(self, 'EV_RX_DATA', data=None)
    else:
        data = gmsg.getdata(gmsg.bytesleft())
        self.set_new_state('ST_WAITING_PAYLOAD_DATA')
        self.send_event(self, 'EV_RX_DATA', data=data)


def ac_process_header_masking_key(self, event):
    """ Get the 4 bytes of masking key
    """
    gmsg = self.rx_gmsg
    if event.data:
        gmsg.putdata(event.data)
    if not self.iam_server:
        self.set_new_state('ST_WAITING_PAYLOAD_DATA')
        self.send_event(self, 'EV_RX_DATA', data=None)
        return

    data = gmsg.getdata(4)
    if data is None:
        # wait: there is no enough data
        return
    self.masking_key = data

    self.set_new_state('ST_WAITING_PAYLOAD_DATA')
    self.send_event(self, 'EV_RX_DATA', data=None)


def ac_process_payload_data(self, event):
    """ Get payload data
    """
    print "GETTINNNG PAYLOAD"
    gmsg = self.rx_gmsg
    if event.data:
        gmsg.putdata(event.data)

    data_gmsg = self.data_gmsg
    if data_gmsg is None:
        # frame with lenght 0
        print "CONTROLLLL"
        self.flush_current_frame()
        return

    free = data_gmsg.free_space()
    print "FREEEE", free
    if free > 0:
        data = gmsg.getdata(free)
        if data is None:
            # wait: need more data
            return
        data_gmsg.putdata(data)

    self.flush_current_frame()


GWEBSOCKET_FSM = {
    'event_list': (
        'EV_ON_OPEN:top output',
        'EV_ON_CLOSE:top output',
        'EV_ON_MESSAGE:top output',
        'EV_RX_DATA:bottom input',
#        'EV_TRANSMIT_READY:bottom input',
        'EV_DISCONNECTED:bottom input',
        'EV_SET_TIMER:bottom output',
        'EV_TIMEOUT:bottom input',
    ),
    'state_list': (
        'ST_WAITING_HEADER',
        'ST_WAITING_HEADER_EXTENDED_LENGTH',
        'ST_WAITING_HEADER_MASKING_KEY',
        'ST_WAITING_PAYLOAD_DATA',
    ),
    'machine': {
        'ST_WAITING_HEADER':
        (
            ('EV_DISCONNECTED', ac_disconnected,                    None),
            ('EV_TIMEOUT',      ac_timeout_waiting_frame_header,    None),
            ('EV_RX_DATA',      ac_process_frame_header_start,      None),
        ),

        'ST_WAITING_HEADER_EXTENDED_LENGTH':
        (
            ('EV_DISCONNECTED', ac_disconnected,                    None),
            ('EV_TIMEOUT',      ac_timeout_waiting_frame_header,    None),
            ('EV_RX_DATA',      ac_process_header_extended_length,  None),
        ),
        'ST_WAITING_HEADER_MASKING_KEY':
        (
            ('EV_DISCONNECTED', ac_disconnected,                    None),
            ('EV_TIMEOUT',      ac_timeout_waiting_frame_header,    None),
            ('EV_RX_DATA',      ac_process_header_masking_key,      None),
        ),

        'ST_WAITING_PAYLOAD_DATA':
        (
            ('EV_DISCONNECTED', ac_disconnected,                    None),
            ('EV_TIMEOUT',      ac_timeout_waiting_payload_data,    None),
            ('EV_RX_DATA',      ac_process_payload_data,            None),
        ),
    }
}

GWEBSOCKET_GCONFIG = {
    'gsock': [None, None, 0, None, "GSock connection."],
    'request': [None, None, 0, None, "websocket request."],
    'iam_server': [bool, True, 0, None, "What side? server or client."],
    'subscriber': [None, None, 0, None,
        "subcriber of all output-events."
        "Default is ``None``, i.e., the parent"
    ],
}


class GWebSocket(GObj):
    """  GWebSocket GObj.
    WebSocket protocol:
    `RFC 6455  <http://tools.ietf.org/html/rfc6455>`_.

    .. ginsfsm::
       :fsm: GWEBSOCKET_FSM
       :gconfig: GWEBSOCKET_GCONFIG

    *Input-Events:*
        * :attr:`'EV_INPUT_EVENT'`: sample input event.

          Event attributes:

              * ``data``: sample event attribute.

    *Output-Events:*
        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.

          Event attributes:

              * ``data``: sample event attribute.

    """

    KEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

    def __init__(self):
        GObj.__init__(self, GWEBSOCKET_FSM, GWEBSOCKET_GCONFIG)
        self.frame_header = None
        self.rx_gmsg = None
        self.data_gmsg = None
        self.masking_key = None

    def start_up(self):
        """ Initialization zone.
        """
        if self.subscriber is None:
            self.subscriber = self.parent
        self.subscribe_event(None, self.subscriber)
        if self.gsock:
            # We've got already the connection
            self.execute()
        # Setup the timers
        self.inactivity_timer = self.create_gobj(
            None,
            GTimer,
            self,
            timeout_event_name='EV_TIMEOUT'
        )
        self.start_inactivity_timer()

    def start_inactivity_timer(self, seconds=5):
        self.send_event(
            self.inactivity_timer,
            'EV_SET_TIMER',
            seconds=seconds
        )

    def stop_inactivity_timer(self):
        self.send_event(
            self.inactivity_timer,
            'EV_SET_TIMER',
            seconds=-1
        )

    def execute(self):
        # Websocket only supports GET method
        if self.request.method != "GET":
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 405 Method Not Allowed\r\n"
                "Allow: GET\r\n"
                "Connection: Close\r\n"
                "\r\n"
            ))
            self.gsock.mt_drop()
            return

        # Upgrade header should be present and should be equal to WebSocket
        if self.request.headers.get("Upgrade", "").lower() != "websocket":
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 400 Bad Request\r\n"
                "Connection: Close\r\n"
                "\r\n"
                "Can \"Upgrade\" only to \"WebSocket\"."
            ))
            self.gsock.mt_drop()
            return

        # Connection header should be upgrade.
        # Some proxy servers/load balancers
        # might mess with it.
        headers = self.request.headers
        connection = map(lambda s: s.strip().lower(),
                         headers.get("Connection", "").split(","))
        if "upgrade" not in connection:
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 400 Bad Request\r\n"
                "Connection: Close\r\n"
                "\r\n"
                "\"Connection\" must be \"Upgrade\"."
            ))
            self.gsock.mt_drop()
            return

        # The difference between version 8 and 13 is that in 8 the
        # client sends a "Sec-Websocket-Origin" header and in 13 it's
        # simply "Origin".
        supported_version = ("7", "8", "13")
        if not self.request.headers.get(
                "Sec-WebSocket-Version") in supported_version:
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 426 Upgrade Required\r\n"
                "Sec-WebSocket-Version: 13\r\n\r\n"))
            self.gsock.mt_drop()
            return

        fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version")
        if not all(map(lambda f: self.request.headers.get(f), fields)):
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 400 Bad Request\r\n"
                "Connection: Close\r\n"
                "\r\n"
                "Missing/Invalid WebSocket headers."
            ))
            self.gsock.mt_drop()
            return

        key = self.request.headers.get("Sec-Websocket-Key", None)
        if not key or len(base64.b64decode(key)) != 16:
            self.gsock.mt_send_data(ginsfsm.escape.utf8(
                "HTTP/1.1 400 Bad Request\r\n"
                "Connection: Close\r\n"
                "\r\n"
                "Sec-Websocket-Key is invalid key."
            ))
            self.gsock.mt_drop()
            return

        #------------------------------#
        #   Accept the connection
        #------------------------------#
        subprotocol_header = ''
        subprotocols = self.request.headers.get("Sec-WebSocket-Protocol", '')
        subprotocols = [s.strip() for s in subprotocols.split(',')]
        if subprotocols:
            selected = self.select_subprotocol(subprotocols)
            if selected:
                assert selected in subprotocols
                subprotocol_header = "Sec-WebSocket-Protocol: %s\r\n" % (
                    selected)

        self.gsock.mt_send_data(ginsfsm.escape.utf8(
            "HTTP/1.1 101 Switching Protocols\r\n"
            "Upgrade: websocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Accept: %s\r\n"
            "%s"
            "\r\n" % (
                base64.b64encode(sha1(key + self.KEY).digest()),
                subprotocol_header)
            )
        )

        #
        #   Subscribe all gsock events.
        #
        self.gsock.delete_all_subscriptions()  # TODO: igual borro delete http
        self.gsock.subscribe_event(None, self)
        # TODO: mira interactuar con los timers del canal http.
        #self.broadcast_event('EV_ON_OPEN')
        self.gaplic.add_callback(self.broadcast_event, 'EV_ON_OPEN')

    def select_subprotocol(self, subprotocols):
        """Invoked when a new WebSocket requests specific subprotocols.

        ``subprotocols`` is a list of strings identifying the
        subprotocols proposed by the client.  This method may be
        overridden to return one of those strings to select it, or
        ``None`` to not select a subprotocol.  Failure to select a
        subprotocol does not automatically abort the connection,
        although clients may close the connection if none of their
        proposed subprotocols was selected.
        """
        return None

    def remove_gmsgs(self):
        self.remove_header_gmsg()
        self.remove_data_gmsg()

    def remove_header_gmsg(self):
        if self.rx_gmsg:
            gmsg_remove(self.rx_gmsg)
            self.rx_gmsg = None

    def remove_data_gmsg(self):
        if self.data_gmsg:
            gmsg_remove(self.data_gmsg)
            self.data_gmsg = None

    def flush_current_frame(self):
        hd = self.frame_header
        print "==============> OPCODE", hd.opcode
        self.frame_header = None

        gmsg = self.data_gmsg
        if gmsg:
            gmsg.reset_rd()
            ln = gmsg.bytesleft()
            unmasked = gmsg.getdata(ln)
            mask = self.masking_key
            for i in xrange(ln):
                unmasked[i] = unmasked[i] ^ mask[i % 4]

            if hd.fin:
                print "<====== MESSAGE", unmasked
                self.handle_message(hd.opcode, unmasked)

        self.remove_data_gmsg()
        self.set_new_state('ST_WAITING_HEADER')
        self.post_event(self, 'EV_RX_DATA', data=None)

    def handle_message(self, opcode, data):
        if opcode == OPCODE_TEXT_FRAME:
            if True:  # TODO self._auto_decode:
                data = data.decode("utf-8")
            self.gaplic.add_callback(
                self.broadcast_event,
                'EV_ON_MESSAGE',
                data=data
            )
        elif opcode == OPCODE_BINARY_FRAME:
            self.gaplic.add_callback(
                self.broadcast_event,
                'EV_ON_MESSAGE',
                data=data
            )
        elif opcode == OPCODE_CONTROL_CLOSE:
            self.gsock.mt_drop()
        elif opcode == OPCODE_CONTROL_PING:
            pass
        elif opcode == OPCODE_CONTROL_PONG:
            pass
        else:
            pass

    def write_message(self, message, binary=False):
        """Sends the given message to the client of this Web Socket."""
        if binary:
            opcode = 0x2
        else:
            opcode = 0x1
        message = ginsfsm.escape.utf8(message)
        assert isinstance(message, binary_type)
        self._write_frame(True, opcode, message)

    def _write_frame(self, fin, opcode, data):
        if fin:
            finbit = opcode | 0x80
        else:
            finbit = opcode

        l = len(data)
        if l < 126:
            frame = STRUCT_BB.pack(finbit, l)
        elif l <= 0xFFFF:
            frame = STRUCT_BBH.pack(finbit, 126, l)
        else:
            frame = STRUCT_BBQ.pack(finbit, 127, l)
        frame += data
        self.gsock.mt_send_data(frame)