(self)
Parser that keeps trying to interpret bytes it is fed with as
        incoming frames part of a message.

        Control message are single frames only while data messages, like text
        and binary, may be fragmented accross frames.

        The way it works is by instanciating a :class:`wspy.framing.Frame` object,
        then running its parser generator which yields how much bytes
        it requires to performs its task. The stream parser yields this value
        to its caller and feeds the frame parser.

        When the frame parser raises :exc:`StopIteration`, the stream parser
        tries to make sense of the parsed frame. It dispatches the frame's bytes
        to the most appropriate message type based on the frame's opcode.

        Overall this makes the stream parser totally agonstic to
        the data provider.
Parser that keeps trying to interpret bytes it is fed with as
        incoming frames part of a message.
Parser that keeps trying to interpret bytes it is fed with as incoming frames part of a message .
def receiver(self):
        """
        Parser that keeps trying to interpret bytes it is fed with as
        incoming frames part of a message.

        Control message are single frames only while data messages, like text
        and binary, may be fragmented accross frames.

        The way it works is by instanciating a :class:`wspy.framing.Frame` object,
        then running its parser generator which yields how much bytes
        it requires to performs its task. The stream parser yields this value
        to its caller and feeds the frame parser.

        When the frame parser raises :exc:`StopIteration`, the stream parser
        tries to make sense of the parsed frame. It dispatches the frame's bytes
        to the most appropriate message type based on the frame's opcode.

        Overall this makes the stream parser totally agonstic to
        the data provider.
        """
        utf8validator = Utf8Validator()
        running = True
        frame = None
        while running:
            frame = Frame()
            while 1:
                try:
                    bytes = (yield next(frame.parser))
                    frame.parser.send(bytes)
                except StopIteration:
                    frame._cleanup()
                    bytes = frame.body

                    # Let's avoid unmasking when there is no payload
                    if bytes:
                        if frame.masking_key and self.expect_masking:
                            bytes = frame.unmask(bytes)
                        elif not frame.masking_key and self.expect_masking:
                            msg = CloseControlMessage(code=1002, reason='Missing masking when expected')
                            self.errors.append(msg)
                            break
                        elif frame.masking_key and not self.expect_masking:
                            msg = CloseControlMessage(code=1002, reason='Masked when not expected')
                            self.errors.append(msg)
                            break
                        else:
                            bytes = bytearray(bytes)

                    if frame.opcode == OPCODE_TEXT:
                        if self.message and not self.message.completed:
                            # We got a text frame before we completed the previous one
                            msg = CloseControlMessage(code=1002, reason='Received a new message before completing previous')
                            self.errors.append(msg)
                            break

                        m = TextMessage(bytes)
                        m.completed = (frame.fin == 1)
                        self.message = m

                        if bytes:
                            is_valid, end_on_code_point, _, _ = utf8validator.validate(bytes)

                            if not is_valid or (m.completed and not end_on_code_point):
                                self.errors.append(CloseControlMessage(code=1007, reason='Invalid UTF-8 bytes'))
                                break

                    elif frame.opcode == OPCODE_BINARY:
                        m = BinaryMessage(bytes)
                        m.completed = (frame.fin == 1)
                        self.message = m

                    elif frame.opcode == OPCODE_CONTINUATION:
                        m = self.message
                        if m is None:
                            self.errors.append(CloseControlMessage(code=1002, reason='Message not started yet'))
                            break

                        m.extend(bytes)
                        m.completed = (frame.fin == 1)
                        if m.opcode == OPCODE_TEXT:
                            if bytes:
                                is_valid, end_on_code_point, _, _ = utf8validator.validate(bytes)

                                if not is_valid or (m.completed and not end_on_code_point):
                                    self.errors.append(CloseControlMessage(code=1007, reason='Invalid UTF-8 bytes'))
                                    break

                    elif frame.opcode == OPCODE_CLOSE:
                        code = 1000
                        reason = ""
                        if frame.payload_length == 0:
                            self.closing = CloseControlMessage(code=1000)
                        elif frame.payload_length == 1:
                            self.closing = CloseControlMessage(code=1002, reason='Payload has invalid length')
                        else:
                            try:
                                code = int(unpack("!H", enc(bytes[0:2]))[0])
                            except TypeError:
                                code = 1002
                                reason = 'Invalid Closing Frame Code Type'
                            except struct.error:
                                code = 1002
                                reason = 'Failed at decoding closing code'
                            else:
                                # Those codes are reserved or plainly forbidden
                                if code not in VALID_CLOSING_CODES and not (2999 < code < 5000):
                                    reason = 'Invalid Closing Frame Code: %d' % code
                                    code = 1002
                                elif frame.payload_length > 1:
                                    reason = bytes[2:] if frame.masking_key else bytearray(frame.body[2:])

                                    is_valid, end_on_code_point, _, _ = utf8validator.validate(reason)
                                    if not is_valid or not end_on_code_point:
                                        self.errors.append(CloseControlMessage(code=1007, reason='Invalid UTF-8 bytes'))
                                        break
                            self.closing = CloseControlMessage(code=code, reason=reason)

                    elif frame.opcode == OPCODE_PING:
                        self.pings.append(PingControlMessage(bytes))

                    elif frame.opcode == OPCODE_PONG:
                        self.pongs.append(PongControlMessage(bytes))

                    else:
                        self.errors.append(CloseControlMessage(code=1003))

                    break

                except ProtocolException:
                    self.errors.append(CloseControlMessage(code=1002))
                    break
                except FrameTooLargeException:
                    self.errors.append(CloseControlMessage(code=1002, reason="Frame was too large"))
                    break
                except StreamClosed:
                    running = False
                    break

            frame.body = None
            frame = None

            if self.message is not None and self.message.completed:
                utf8validator.reset()

        if frame:
            frame._cleanup()
            frame = None

        utf8validator.reset()
        utf8validator = None

        self._cleanup()
def receiver ( self ) : utf8validator = Utf8Validator ( ) running = True frame = None while running : frame = Frame ( ) while 1 : try : bytes = ( yield next ( frame . parser ) ) frame . parser . send ( bytes ) except StopIteration : frame . _cleanup ( ) bytes = frame . body # Let's avoid unmasking when there is no payload if bytes : if frame . masking_key and self . expect_masking : bytes = frame . unmask ( bytes ) elif not frame . masking_key and self . expect_masking : msg = CloseControlMessage ( code = 1002 , reason = 'Missing masking when expected' ) self . errors . append ( msg ) break elif frame . masking_key and not self . expect_masking : msg = CloseControlMessage ( code = 1002 , reason = 'Masked when not expected' ) self . errors . append ( msg ) break else : bytes = bytearray ( bytes ) if frame . opcode == OPCODE_TEXT : if self . message and not self . message . completed : # We got a text frame before we completed the previous one msg = CloseControlMessage ( code = 1002 , reason = 'Received a new message before completing previous' ) self . errors . append ( msg ) break m = TextMessage ( bytes ) m . completed = ( frame . fin == 1 ) self . message = m if bytes : is_valid , end_on_code_point , _ , _ = utf8validator . validate ( bytes ) if not is_valid or ( m . completed and not end_on_code_point ) : self . errors . append ( CloseControlMessage ( code = 1007 , reason = 'Invalid UTF-8 bytes' ) ) break elif frame . opcode == OPCODE_BINARY : m = BinaryMessage ( bytes ) m . completed = ( frame . fin == 1 ) self . message = m elif frame . opcode == OPCODE_CONTINUATION : m = self . message if m is None : self . errors . append ( CloseControlMessage ( code = 1002 , reason = 'Message not started yet' ) ) break m . extend ( bytes ) m . completed = ( frame . fin == 1 ) if m . opcode == OPCODE_TEXT : if bytes : is_valid , end_on_code_point , _ , _ = utf8validator . validate ( bytes ) if not is_valid or ( m . completed and not end_on_code_point ) : self . errors . append ( CloseControlMessage ( code = 1007 , reason = 'Invalid UTF-8 bytes' ) ) break elif frame . opcode == OPCODE_CLOSE : code = 1000 reason = "" if frame . payload_length == 0 : self . closing = CloseControlMessage ( code = 1000 ) elif frame . payload_length == 1 : self . closing = CloseControlMessage ( code = 1002 , reason = 'Payload has invalid length' ) else : try : code = int ( unpack ( "!H" , enc ( bytes [ 0 : 2 ] ) ) [ 0 ] ) except TypeError : code = 1002 reason = 'Invalid Closing Frame Code Type' except struct . error : code = 1002 reason = 'Failed at decoding closing code' else : # Those codes are reserved or plainly forbidden if code not in VALID_CLOSING_CODES and not ( 2999 < code < 5000 ) : reason = 'Invalid Closing Frame Code: %d' % code code = 1002 elif frame . payload_length > 1 : reason = bytes [ 2 : ] if frame . masking_key else bytearray ( frame . body [ 2 : ] ) is_valid , end_on_code_point , _ , _ = utf8validator . validate ( reason ) if not is_valid or not end_on_code_point : self . errors . append ( CloseControlMessage ( code = 1007 , reason = 'Invalid UTF-8 bytes' ) ) break self . closing = CloseControlMessage ( code = code , reason = reason ) elif frame . opcode == OPCODE_PING : self . pings . append ( PingControlMessage ( bytes ) ) elif frame . opcode == OPCODE_PONG : self . pongs . append ( PongControlMessage ( bytes ) ) else : self . errors . append ( CloseControlMessage ( code = 1003 ) ) break except ProtocolException : self . errors . append ( CloseControlMessage ( code = 1002 ) ) break except FrameTooLargeException : self . errors . append ( CloseControlMessage ( code = 1002 , reason = "Frame was too large" ) ) break except StreamClosed : running = False break frame . body = None frame = None if self . message is not None and self . message . completed : utf8validator . reset ( ) if frame : frame . _cleanup ( ) frame = None utf8validator . reset ( ) utf8validator = None self . _cleanup ( )