Validate incoming packet.
764407
def _valid_packet(raw_packet):
        """"""
        if raw_packet[0:1] != b'\xcc':
            return False
        if len(raw_packet) != 19:
            return False
        checksum = 0
        for i in range(1, 17):
            checksum += raw_packet[i]
        if checksum != raw_packet[18]:
            return False
        return True
744533
async def _handle_data(self, data):
        
        try:
            _, _, verification_tag, chunks = parse_packet(data)
        except ValueError:
            return

        # is this an init?
        init_chunk = len([x for x in chunks if isinstance(x, InitChunk)])
        if init_chunk:
            assert len(chunks) == 1
            expected_tag = 0
        else:
            expected_tag = self._local_verification_tag

        # verify tag
        if verification_tag != expected_tag:
            self.__log_debug('Bad verification tag %d vs %d',
                             verification_tag, expected_tag)
            return

        # handle chunks
        for chunk in chunks:
            await self._receive_chunk(chunk)

        # send SACK if needed
        if self._sack_needed:
            await self._send_sack()
78238
def validate(self):
        """"""
        if not self.get('api_key'):
            raise ValueError("api_key not found in config. Please see documentation.")
        host = self.get('host') or DEFAULT_CLOUD_HOST
        if host:
            # remove extraneous slashes and force to byte string
            # otherwise msg += message_body in httplib will fail in python2
            # when message_body contains binary data, and url is unicode

            # remaining failure modes include at least:
            # passing bytes in python3 will fail as we try to strip unicode '/' characters
            # passing unicode code points in python2 will fail due to httplib host.encode('ascii')
            host = host.strip('/')
            if not isinstance(host, str):
                host = host.encode('utf-8')
            self['host'] = host

        self.setdefault('autostart_notification_thread', True)
1308187
def validate(self):
        
        endpoint = '/validate'

        payload = dict(accessToken=self.access_token)
        rep = self._ygg_req(endpoint, payload)
        return not bool(rep)
68367
def validate(self):
        """"""
        try:
            for pkg in self.resolved_packages:
                pkg.validate_data()
        except RezError as e:
            raise ResolvedContextError("%s: %s" % (e.__class__.__name__, str(e)))
744645
def _validate(self):
        
        if not is_valid_subject(self.subject):
            raise MessageError("Invalid subject: '%s'" % self.subject)
        if not is_valid_type(self.type):
            raise MessageError("Invalid type: '%s'" % self.type)
        if not is_valid_sender(self.sender):
            raise MessageError("Invalid sender: '%s'" % self.sender)
        if not self.binary and not is_valid_data(self.data):
            raise MessageError("Invalid data: data is not JSON serializable: %s"
                               % str(self.data))
1172728
def _handle_ping(self, packet, protocol):
        
        if 'payload' in packet:
            is_valid_node = True
            node_ids = list(packet['payload'].values())
            for node_id in node_ids:
                if self._repository.get_node(node_id) is None:
                    is_valid_node = False
                    break
            if is_valid_node:
                self._pong(packet, protocol)
        else:
            self._pong(packet, protocol)
324005
def validate_bytes(data, length=4):
        '''
        
        '''
        if (not isinstance(data, ByteData)
                and not isinstance(data, bytes)
                and not isinstance(data, bytearray)):
            raise ValueError('Expected byte-like object. '
                             'Got: {}'.format(type(data)))

        if length is None:
            return

        if len(data) != length:
            raise ValueError('Expected byte-like object with length {}. '
                             'Got {} with length {}.'
                             .format(length, type(data), len(data)))
951166
def parse_packet(packet):
    """"""
    frame = parse_ltv_packet(packet)
    if frame is None:
        frame = parse_ibeacon_packet(packet)
    return frame
939126
def packet_queue(self, pkt):
        """"""
        
        pkt.pos = 0
        pkt.to_process = pkt.packet_length
        
        self.out_packet.append(pkt)
        return NC.ERR_SUCCESS
1271103
def handle_lines(self):
        """"""
        while "\r\n" in self.buffer:
            line, self.buffer = self.buffer.split("\r\n", 1)
            if valid_packet(line):
                self.handle_raw_packet(line)
            else:
                log.warning('dropping invalid data: %s', line)
1181962
def handle_suback(self):
        """"""
        self.logger.info("SUBACK received")
        
        ret, mid = self.in_packet.read_uint16()
        
        if ret != NC.ERR_SUCCESS:
            return ret
        
        qos_count = self.in_packet.remaining_length - self.in_packet.pos
        granted_qos = bytearray(qos_count)
        
        if granted_qos is None:
            return NC.ERR_NO_MEM
        
        i = 0
        while self.in_packet.pos < self.in_packet.remaining_length:
            ret, byte = self.in_packet.read_byte()
            
            if ret != NC.ERR_SUCCESS:
                granted_qos = None
                return ret
            
            granted_qos[i] = byte
            
            i += 1
        
        evt = event.EventSuback(mid, list(granted_qos))
        self.push_event(evt)
        
        granted_qos = None
        
        return NC.ERR_SUCCESS
1237239
def was_packet_accepted(self, packet):
        ''''''
        self._validatepacket(packet)
        cmd = ord(packet[2])
        if cmd == Vendapin.ACK: # Accepted/Positive Status
            return True
        elif cmd == Vendapin.NAK: # Rejected/Negative Status
            print('NAK - Rejected/Negative Status')
            return False
        elif cmd == Vendapin.INC: # Incomplete Command Packet
            raise Exception('INC - Incomplete Command Packet')
        elif cmd == Vendapin.UNR: # Unrecognized Command Packet
            raise Exception('UNR - Unrecognized Command Packet')
        elif cmd == Vendapin.CER: # Data Packet Checksum Error
            raise Exception('CER - Data Packet Checksum Error')
        else:
            raise Exception('Received bad CMD in response from card dispenser')
427890
def handle(self, pkt, raddress, rport):
        """"""
        if isinstance(pkt, TftpPacketDAT):
            return self.handleDat(pkt)

        # Every other packet type is a problem.
        elif isinstance(pkt, TftpPacketACK):
            # Umm, we ACK, you don't.
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received ACK from peer when expecting DAT")

        elif isinstance(pkt, TftpPacketWRQ):
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received WRQ from peer when expecting DAT")

        elif isinstance(pkt, TftpPacketERR):
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received ERR from peer: " + str(pkt))

        else:
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received unknown packet type from peer: " + str(pkt))
237559
def incoming(self, packet):
        
        # This might be done prettier ;-)
        console_text = packet.data.decode('UTF-8')

        self.receivedChar.call(console_text)
1234084
def validate(self, nonce):
        """"""
        if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr)
        try:
            opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable
            if expiretime < time.time():
                if self.debug: print("Nonce expired",file=sys.stderr)
                self.remove(nonce)
                return False
            elif ip != flask.request.remote_addr:
                if self.debug: print("Nonce IP mismatch",file=sys.stderr)
                self.remove(nonce)
                return False
            else:
                return True
        except KeyError:
            if self.debug: print("Nonce " + nonce + " does not exist",file=sys.stderr)
            return False
1265380
private static boolean checkValidity(ClientSocket client, byte from, StateConnection expected)
    {
        return from >= 0 && client.getState() == expected;
    }