예제 #1
0
    def test_too_small_packet(self):
        """
		Tests if too small packets are rejected due to the
		minimum length requirement.
		"""

        with self.assertRaises(ValueError):
            packet.parse_packet([10])
예제 #2
0
 def poll(self):
     """
         poll the socket and see if there is any data to be processed.
         if so, loop through the packets and process all of it before 
         the next loop.
     """
     if self.sock.read():
         messages = []
         while self.sock.read():
             messages.append(self.sock.get_packet())
         for m in messages:
             parse_packet(self, m)
         self.sock.buf = ''
     return True
예제 #3
0
    def test_fuzzy_2(self):
        """
		Fuzzy testing.

		If parsing of a packet is successful, then unparsing must be
		successful as well and the buffers must match.
		"""

        i = 0

        while i < 1024 * 100:
            buf = self._random_buf_2()

            plus_packet = None

            try:
                plus_packet = packet.parse_packet(buf)
            except:
                plus_packet = None

            if plus_packet != None:
                try:
                    self.assertEqual(plus_packet.to_bytes(), buf)
                except:
                    print(plus_packet.to_dict())
                    raise ValueError("Buffer mismatch?")

            i += 1
예제 #4
0
def __handler(data):
    status, data = packet.parse_packet(data)
    print(status, data)
    if status:
        epoch, temps = data
        __process(epoch, temps)
        return packet.make_ack_packet()
예제 #5
0
    def send(self, data, sendTo, flag=0):
        unacked = len(self.pkts)
        packet = make_packet(self.nextseq, data, flag)
        oldest_unack = (self.nextseq - unacked) & 0xffff

        # fall back to fixed timeout value
        self.localSocket.settimeout(0.1)
        lastsent = False

        if flag == 2 and unacked < self.window_size:
            self.sendPkt(packet)
            lastsent = True

        while unacked >= self.window_size or (flag == 2 and unacked > 0):
            try:
                pkt, address = self.localSocket.recvfrom(MAX_SIZE)

            except socket.timeout:
                # resend all pkts
                if time.time() - self.timer < self.TIMEOUT:
                    self.start_timer()
                    self.sendAll(sendTo)
                    print("go back n, resend all")
            else:
                csum, rsum, seq, _, _ = parse_packet(pkt)

                # not corrupted
                if csum == rsum:
                    # cumulative acknowledgement
                    cum_acks = seq - oldest_unack + 1
                    if cum_acks < 0:  # seqnum restarts from zero
                        cum_acks = seq + 1 + 0xffff - oldest_unack + 1
                    self.pkts = self.pkts[cum_acks:]
                    #print("seq: {}, oldest: {} cum ACK {}".format(seq, oldest_unack, cum_acks))
                    unacked -= cum_acks
                    oldest_unack = (oldest_unack + cum_acks) & 0xffff

                    if unacked != 0:
                        self.start_timer()

                    if flag == 2 and not lastsent:
                        self.sendPkt(packet, sendTo)
                        lastsent = True

        # ok to send now
        if flag != 2:
            self.sendPkt(packet, sendTo)
예제 #6
0
    def test_parse_packet_7(self):
        """
		Tests parsing an extended packet.
		"""

        buf = bytes([
            0xD8,
            0x00,
            0x7F,
            0xF1,  # magic + flags (x bit set)
            0x12,
            0x34,
            0x56,
            0x78,  # cat
            0x12,
            0x34,
            0x56,
            0x71,  # cat..
            0x13,
            0x11,
            0x11,
            0x12,  # psn
            0x23,
            0x22,
            0x22,
            0x23,  # pse
            0x00,
            0x00,
            0xF3,  # PCF Type := 0x00,
            # PCF Len 60, PCF I = 11b,
            0x01,
            0x02,
            0x03,
            0x04,
            0x05,
            0x06,  # 6 bytes PCF value
            0x99,
            0x98,
            0x97,
            0x96
        ])  # 4 bytes payload

        # This needs to fail because pcf_len is 60 but pcf_value + payload
        # aren't even that long in the buf
        with self.assertRaises(ValueError):
            plus_packet = packet.parse_packet(buf)
예제 #7
0
    def recv(self):
        total = 0
        self.receiveSocket.settimeout(.1)
        while True:
            try:
                message = self.receiveSocket.recv(MAX_SIZE)
                _, _, _, flag, data = parse_packet(message)
                total += 1
                print("total: {} data: {}".format(total, len(data)), end="\r")
                if flag == 2 or not data:
                    break
                yield data
                # last packet, don't wait for timeout

            except socket.timeout:
                print('timeout. end.')
                break
예제 #8
0
    def test_fuzzy_3(self):
        """
		Make random packets. Then unparse and parse again and compare.
		"""

        i = 0
        m = 0
        n = 0
        while i < 1024 * 100:
            plus_packet = None
            plus_packet_ = None

            try:
                plus_packet = self._random_packet()
                n += 1
                buf = plus_packet.to_bytes()
                plus_packet_ = packet.parse_packet(buf)
            except ValueError as e:
                pass

            if plus_packet_ == None:
                i += 1
                continue

            self.assertEqual(plus_packet.l, plus_packet_.l)
            self.assertEqual(plus_packet.r, plus_packet_.r)
            self.assertEqual(plus_packet.s, plus_packet_.s)
            self.assertEqual(plus_packet.x, plus_packet_.x)
            self.assertEqual(plus_packet.cat, plus_packet_.cat)
            self.assertEqual(plus_packet.psn, plus_packet_.psn)
            self.assertEqual(plus_packet.pse, plus_packet_.pse)
            self.assertEqual(plus_packet.payload, plus_packet_.payload)
            self.assertEqual(plus_packet.pcf_type, plus_packet_.pcf_type)
            self.assertEqual(plus_packet.pcf_value, plus_packet_.pcf_value)
            self.assertEqual(plus_packet.pcf_integrity,
                             plus_packet_.pcf_integrity)
            self.assertEqual(plus_packet.is_valid(), True)
            self.assertEqual(plus_packet_.is_valid(), True)

            i += 1
            m += 1

        print(n, m)
예제 #9
0
	def test_parse_packet_3(self):
		"""
		Tests parsing an extended packet.
		"""

		buf = bytes([
			0xD8, 0x00, 0x7F, 0xFF, # magic + flags (x bit set)
			0x12, 0x34, 0x56, 0x78, # cat
			0x12, 0x34, 0x56, 0x78, # cat..
			0x13, 0x11, 0x11, 0x11, # psn
			0x23, 0x22, 0x22, 0x22, # pse
			0xFF, 0x01, 0x00, # PCF Type := 0xFF,
			# PCF Len := 0, PCF I := 00b,
			0x01, 0x02, 0x03, 0x04,
			0x05, 0x06, # 
			0x99, 0x98, 0x97, 0x96]) # 10 bytes payload

		l = True
		r = True
		s = True
		cat = 0x1234567812345678
		psn = 0x13111111
		pse = 0x23222222
		pcf_type = 0xFF
		pcf_len = None
		pcf_integrity = None
		pcf_value = None
		payload = bytes([0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x99, 0x98, 0x97, 0x96])

		plus_packet = packet.parse_packet(buf)

		self.assertEqual(plus_packet.l, l)
		self.assertEqual(plus_packet.r, r)
		self.assertEqual(plus_packet.s, s)
		self.assertEqual(plus_packet.x, True)
		self.assertEqual(plus_packet.cat, cat)
		self.assertEqual(plus_packet.psn, psn)
		self.assertEqual(plus_packet.pse, pse)
		self.assertEqual(plus_packet.payload, payload)
		self.assertEqual(plus_packet.pcf_type, pcf_type)
		self.assertEqual(plus_packet.pcf_value, pcf_value)
		self.assertEqual(plus_packet.pcf_integrity, pcf_integrity)
		self.assertEqual(plus_packet.is_valid(), True)
예제 #10
0
    def test_invalid_magic(self):
        """
		Tests parsing when magic is invalid.
		"""

        buf = bytes([
            0x18,
            0x00,
            0x7F,
            0xFA,  #magic + flags
            0x12,
            0x34,
            0x56,
            0x78,  #cat
            0x21,
            0x43,
            0x65,
            0x87,
            0x87,
            0x65,
            0x43,
            0x21,  #psn
            0x11,
            0x22,
            0x33,
            0x44,  #pse
            0x01,
            0x02,
            0x03,
            0x04,  #payload
            0x10,
            0x20,
            0x30,
            0x40,  #payload
            0x99,
            0x90,
            0x99,
            0x90
        ])

        with self.assertRaises(ValueError):
            plus_packet = packet.parse_packet(buf)
예제 #11
0
    def recv(self):
        acks = 0
        nacs = 0

        self.localSocket.settimeout(60)  # no one can wait for so long
        while True:
            try:
                message, address = self.localSocket.recvfrom(MAX_SIZE)

                csum, rsum, seqnum, flag, data = parse_packet(message)

                # check sum and seqnum
                if csum != rsum or seqnum != self.seq:
                    ACK = make_ack(1 - self.seq)
                    nacs += 1
                    self.localSocket.sendto(ACK, address)
                    print("acks: {}, NAK: {}.".format(acks, nacs), end='\r')
                else:
                    # simulate loss
                    if random.random() < self.prob_loss:
                        ACK = make_ack(1 - self.seq)
                        nacs += 1
                        self.localSocket.sendto(ACK, address)
                        print("acks: {}, NAK: {}.".format(acks, nacs),
                              end='\r')
                        continue

                    # ack
                    ACK = make_ack(self.seq)
                    self.localSocket.sendto(ACK, address)
                    acks += 1
                    print("acks: {}, NAK: {}.".format(acks, nacs), end='\r')
                    self.seq = 1 - self.seq
                    yield data

                    # last packet, don't wait for more packets
                    if flag == 2:
                        print("\n last packet received.")
                        break
            except socket.timeout:
                print('timeout ? end.')
                break
예제 #12
0
    def recv(self):
        # set time out to prevent it from blocking forever
        self.localSocket.settimeout(10)

        while True:
            try:
                message, address = self.localSocket.recvfrom(MAX_SIZE)
                _, _, _, flag, data = parse_packet(message)

                # simulate packet loss
                #if random.random() < self.prob_loss:
                #    print("packet loss!")
                #    continue
                yield data
                # last packet, don't wait for timeout
                if flag == 2:
                    break
            except socket.timeout:
                print('timeout. end.')
                break
예제 #13
0
	def test_parse_packet_1(self):
		"""
		Tests parsing a basic packet.
		"""

		buf = bytes([
			0xD8, 0x00, 0x7F, 0xFA, #magic + flags
			0x12, 0x34, 0x56, 0x78, #cat
			0x21, 0x43, 0x65, 0x87,
			0x87, 0x65, 0x43, 0x21, #psn
			0x11, 0x22, 0x33, 0x44, #pse
			0x01, 0x02, 0x03, 0x04, #payload
			0x10, 0x20, 0x30, 0x40, #payload
			0x99, 0x90, 0x99, 0x90])

		l = True
		r = False
		s = True

		cat = 0x1234567821436587
		psn = 0x87654321
		pse = 0x11223344

		payload = bytes([
			0x01, 0x02, 0x03, 0x04,
			0x10, 0x20, 0x30, 0x40,
			0x99, 0x90, 0x99, 0x90])

		plus_packet = packet.parse_packet(buf)

		self.assertEqual(plus_packet.l, l)
		self.assertEqual(plus_packet.r, r)
		self.assertEqual(plus_packet.s, s)
		self.assertEqual(plus_packet.x, False)
		self.assertEqual(plus_packet.cat, cat)
		self.assertEqual(plus_packet.psn, psn)
		self.assertEqual(plus_packet.pse, pse)
		self.assertEqual(plus_packet.payload, payload)
		self.assertEqual(plus_packet.is_valid(), True)
예제 #14
0
    def send(self, data, sendTo, flag=0):
        ack_received = False
        packet = make_packet(self.seq, data, flag)

        alpha = 0.875
        beta = 0.25
        ertt = 0.5
        devrtt = 0
        self.localSocket.settimeout(ertt)

        retrans = 0
        while not ack_received:
            start = time.time()
            self.localSocket.sendto(packet, sendTo)

            try:
                message, address = self.localSocket.recvfrom(MAX_SIZE)
            except socket.timeout:
                retrans += 1
                print('timeout, retrans = ' + str(retrans), end='\r')
            else:
                csum, rsum, seqnum, flag, data = parse_packet(message)

                # not corrupted and expected?
                if csum == rsum and seqnum == self.seq:
                    #print("ACK {} received.".format(self.seq))
                    end = time.time()
                    samplertt = end - start
                    ertt = alpha * ertt + (1 - alpha) * samplertt
                    devrtt = (1 - beta) * devrtt + beta * abs(samplertt - ertt)
                    self.localSocket.settimeout(ertt + 4 * devrtt)
                    ack_received = True
                else:
                    retrans += 1
                    print('timeout, retrans = ' + str(retrans), end='\r')
        self.seq = 1 - self.seq
예제 #15
0
    def test_parse_packet_6(self):
        """
		Tests parsing an extended packet.
		"""

        buf = bytes([
            0xD8,
            0x00,
            0x7F,
            0xF1,  # magic + flags (x bit set)
            0x12,
            0x34,
            0x56,
            0x78,  # cat
            0x12,
            0x34,
            0x56,
            0x71,  # cat..
            0x13,
            0x11,
            0x11,
            0x12,  # psn
            0x23,
            0x22,
            0x22,
            0x23,  # pse
            0x00,
            0x00,
            0x1B,  # PCF Type := 0x00,
            # PCF Len 6, PCF I = 11b,
            0x01,
            0x02,
            0x03,
            0x04,
            0x05,
            0x06,  # 6 bytes PCF value
            0x99,
            0x98,
            0x97,
            0x96
        ])  # 4 bytes payload

        l = False
        r = False
        s = False
        cat = 0x1234567812345671
        psn = 0x13111112
        pse = 0x23222223
        pcf_type = 0x00
        pcf_len = 0x06
        pcf_integrity = 0x03
        pcf_value = bytes([0x01, 0x02, 0x03, 0x04, 0x05, 0x06])
        payload = bytes([0x99, 0x98, 0x97, 0x96])

        plus_packet = packet.parse_packet(buf)

        self.assertEqual(plus_packet.l, l)
        self.assertEqual(plus_packet.r, r)
        self.assertEqual(plus_packet.s, s)
        self.assertEqual(plus_packet.x, True)
        self.assertEqual(plus_packet.cat, cat)
        self.assertEqual(plus_packet.psn, psn)
        self.assertEqual(plus_packet.pse, pse)
        self.assertEqual(plus_packet.payload, payload)
        self.assertEqual(plus_packet.pcf_type, pcf_type)
        self.assertEqual(plus_packet.pcf_value, pcf_value)
        self.assertEqual(plus_packet.pcf_integrity, pcf_integrity)
        self.assertEqual(plus_packet.is_valid(), True)