示例#1
0
    def __init__(self):
        self.left_back = None
        self.right_back = None

        self.commands = Commands()
        self.generalpacket = Packet()
        self.get_data = Packet(8, PacketID.GET_VALUES, Scale.NONE)
        self.alive = Packet(8, PacketID.ALIVE, Scale.NONE)
  def generatePacket(self, time, source, destination, message):
    packet = Packet()
    packet.addBody("time", time)
    packet.addBody("source", source)
    packet.addBody("destination", destination)
    packet.addBody("message", message)

    self.lastPacket = packet # Used just for visualization purposes
    return packet
示例#3
0
    def read(self):
        """
        Read packet from serial.
        """
        pkt_buffer = bytes()

        # first, wait for our magic
        magic = self.interface.read(1)
        while magic != b'\xbc':
            #print('...')
            magic = self.interface.read(1)
        pkt_buffer += bytes(magic)

        # get operation and flags
        opflags = self.interface.read(1)
        pkt_buffer += bytes(opflags)

        # get packet size
        pkt_size = self.interface.read(2)
        pkt_buffer += pkt_size
        _pkt_size = unpack('<H', pkt_size)[0]

        # read packet size (data)
        data = self.interface.read(_pkt_size)
        pkt_buffer = pkt_buffer + data

        # read checksum
        checksum = self.interface.read(1)
        pkt_buffer += bytes(checksum)

        # Create packet from data
        packet = Packet.fromBytes(pkt_buffer)
        return packet
示例#4
0
    def handle(self, packet):
        """
            Handle a raw protocol packet and return the constructed packet. Since it follows the protocol codes,
            the only allowed response codes are the protocols response codes, any other code will raise a InvalidPacketCode
            exception.

            :param packet: The packet content.
            :return: The packet object or None.
        """
        # Decode the packet fragments.
        code, data, params = protocol.from_packet(packet)

        if code is protocol.SUCCESS_CODE:
            # The packet was succesfull understood by the client.
            return Packet(content=data, params=params, code=code)
        elif code is protocol.ERROR_CODE:
            # The packet had errors or not had been understood by the client.
            if self._on_error is not None:

                # Execute the on error event with the packet data.
                self._on_error(data)
            return None
        else:
            raise protocol.InvalidPacketCode(
                'Invalid response code. Code: {}'.format(code))
示例#5
0
    def parse_fifo(self):
        if not self.sock:
            return -1

        while len(self.rfifo) >= 2:
            cmd = Packet.parse_header(self.rfifo[:2])
            print(format(cmd, '#06x'))
            dlen = len(self.rfifo)
            print(dlen)
            cls = zd_packet_dict[cmd]
            print(cls)
            plen = cls.get_fmt_len()
            print(plen)

            if plen == -1:
                print('variable len!')
                if dlen <= 4:
                    return 0
                plen = cls.get_var_len_buffer(self.rfifo)

            print(plen)
            if plen > dlen:
                return 0

            pkt = cls(self.rfifo[:plen])
            print(pkt.get_data(as_string=True))
            if pkt.parse(self):
                self.eof = True

            self.rfifo = self.rfifo[plen:]
        return 0
示例#6
0
def process_buffer(buffer):
    """
    This function processes the given buffer (bytearray). When a packet is received, the function calls the process_packet fucntion
    :param buffer: The given bytearray to proces
    :return: None
    """
    global phase, payload, length, crc
    """
    This is an integer that indicates the state the message reading is in.
    0: Starting a package read
    1: Reading payload length - long version
    2: Reading payload length - both versions
    3: Reading payload
    4: Reading CRC checksum - first byte
    5: Reading CRC checksum - second byte
    6: Checking checksum
    """

    for x in range(len(buffer)):

        curr_byte = buffer[x]
        if phase == 0:
            payload = bytearray()
            length = 0
            crc = 0
            if curr_byte == 2:
                phase += 2
            elif curr_byte == 3:
                phase += 1
        elif phase == 1:
            length = curr_byte << 8
            phase += 1
        elif phase == 2:
            length |= curr_byte
            phase += 1
        elif phase == 3:
            payload.append(curr_byte)
            if len(payload) == length:
                phase += 1
        elif phase == 4:
            crc = curr_byte << 8
            phase += 1
        elif phase == 5:
            crc |= curr_byte
            phase += 1
        elif phase == 6:
            phase = 0
            if curr_byte == 3 and packets.calc_crc(payload) == crc:
                process_packet(Packet(payload))
                return True
        else:
            phase = 0
示例#7
0
def ParseDHCPCode(data):
	PTid        = data[4:8]
	Seconds     = data[8:10]
	CurrentIP   = socket.inet_ntoa(data[12:16])
	RequestedIP = socket.inet_ntoa(data[16:20])
	MacAddr     = data[28:34]
	MacAddrStr  = ':'.join('%02x' % ord(m) for m in MacAddr).upper()
	OpCode      = data[242:243]
	RequestIP   = data[245:249]

	# DHCP Inform
	if OpCode == "\x08": 
		IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=socket.inet_aton(CurrentIP))
		Packet = DHCPInformACK(Tid=PTid, ClientMac=MacAddr, ActualClientIP=socket.inet_aton(CurrentIP), \
								GiveClientIP=socket.inet_aton("0.0.0.0"), \
								NextServerIP=socket.inet_aton("0.0.0.0"), \
								RelayAgentIP=socket.inet_aton("0.0.0.0"), \
								ElapsedSec=Seconds)

		Packet.calculate()
		Buffer = UDP(Data = Packet)
		Buffer.calculate()
		SendDHCP(str(IP_Header)+str(Buffer), (CurrentIP, 68))

		return 'Acknowledged DHCP Inform for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))

	# DHCP Request
	if OpCode == "\x03" and Respond_To_Requests:
		IP = FindIP(data)
		if IP:
			IPConv = socket.inet_ntoa(IP)
			if RespondToThisIP(IPConv):
				IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=IP)
				Packet = DHCPACK(Tid=PTid, ClientMac=MacAddr, GiveClientIP=IP, ElapsedSec=Seconds)
				Packet.calculate()

				Buffer = UDP(Data = Packet)
				Buffer.calculate()

				SendDHCP(str(IP_Header)+str(Buffer), (IPConv, 68))

				return 'Acknowledged DHCP Request for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))

	# DHCP Discover
	if OpCode == "\x01" and Respond_To_Requests:
		IP = FindIP(data)
		if IP:
			IPConv = socket.inet_ntoa(IP)
			if RespondToThisIP(IPConv):
				IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=IP)
				Packet = DHCPACK(Tid=PTid, ClientMac=MacAddr, GiveClientIP=IP, DHCPOpCode="\x02", ElapsedSec=Seconds)
				Packet.calculate()

				Buffer = UDP(Data = Packet)
				Buffer.calculate()

				SendDHCP(str(IP_Header)+str(Buffer), (IPConv, 0))

				return 'Acknowledged DHCP Discover for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))
示例#8
0
    def found_terminator(self):
        filename = ''
        data = "".join(self.ibuffer)
        if '\r\n\r\n' not in data and '\n\n' not in data:
            return
        self.set_terminator(None)
        self.ibuffer = []
        LOGGER.info('----> Request: %s', data)

        if ' /result' in data:
            tmp = RE_RESULT.search(data)
            if tmp:
                with open('result.txt', 'wb') as f:
                    f.write(urllib.unquote(tmp.group(1)))
        elif ' /interactive' in data:
            flist = self.get_filelist()
            if flist:
                state_tmp = global_file_state.get(self.addr[0], set())
                not_read = set(flist) - set(state_tmp)
                if not_read:
                    filename = not_read.pop()
                    state_tmp.add(filename)
                    global_file_state[self.addr[0]] = state_tmp

        # Get payload result
        try:
            query = self.parse_query(data)
        except:
            LOGGER.debug('Unparsed query: %r', data)
            return

        reload(config)
        try:
            result = config.PAYLOADS.get(query.path.lstrip('/'), Packet())
        except:
            self.close_when_done()
            return

        result = str(result).format(
            **{
                'host': config.HOST,
                'port': config.LISTEN_PORT,
                'filename': urllib.unquote(filename or query.query)
            })
        LOGGER.debug('Formatted result: %r', result)

        # Sending and closing connection
        self.push(result)
        self.close_when_done()
示例#9
0
def ParseDHCPCode(data):
	PTid        = data[4:8]
	Seconds     = data[8:10]
	CurrentIP   = socket.inet_ntoa(data[12:16])
	RequestedIP = socket.inet_ntoa(data[16:20])
	MacAddr     = data[28:34]
	MacAddrStr  = ':'.join('%02x' % ord(m) for m in MacAddr).upper()
	OpCode      = data[242:243]
	RequestIP   = data[245:249]

	# DHCP Inform
	if OpCode == "\x08": 
		IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=socket.inet_aton(CurrentIP))
		Packet = DHCPInformACK(Tid=PTid, ClientMac=MacAddr, ActualClientIP=socket.inet_aton(CurrentIP),
								GiveClientIP=socket.inet_aton("0.0.0.0"),
								NextServerIP=socket.inet_aton("0.0.0.0"),
								RelayAgentIP=socket.inet_aton("0.0.0.0"),
								ElapsedSec=Seconds)
		Packet.calculate()
		Buffer = UDP(Data = Packet)
		Buffer.calculate()
		SendDHCP(str(IP_Header)+str(Buffer), (CurrentIP, 68))
		return 'Acknowledged DHCP Inform for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))
	elif OpCode == "\x03" and Respond_To_Requests:  # DHCP Request
		IP = FindIP(data)
		if IP:
			IPConv = socket.inet_ntoa(IP)
			if RespondToThisIP(IPConv):
				IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=IP)
				Packet = DHCPACK(Tid=PTid, ClientMac=MacAddr, GiveClientIP=IP, ElapsedSec=Seconds)
				Packet.calculate()
				Buffer = UDP(Data = Packet)
				Buffer.calculate()
				SendDHCP(str(IP_Header)+str(Buffer), (IPConv, 68))
				return 'Acknowledged DHCP Request for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))
	elif OpCode == "\x01" and Respond_To_Requests:  # DHCP Discover
		IP = FindIP(data)
		if IP:
			IPConv = socket.inet_ntoa(IP)
			if RespondToThisIP(IPConv):
				IP_Header = IPHead(SrcIP = socket.inet_aton(SpoofIP(Spoof)), DstIP=IP)
				Packet = DHCPACK(Tid=PTid, ClientMac=MacAddr, GiveClientIP=IP, DHCPOpCode="\x02", ElapsedSec=Seconds)
				Packet.calculate()
				Buffer = UDP(Data = Packet)
				Buffer.calculate()
				SendDHCP(str(IP_Header)+str(Buffer), (IPConv, 0))
				return 'Acknowledged DHCP Discover for IP: %s, Req IP: %s, MAC: %s Tid: %s' % (CurrentIP, RequestedIP, MacAddrStr, '0x'+PTid.encode('hex'))
示例#10
0
    def findandmapcontrollers(self):
        left_back_port = ""
        right_back_port = ""
        get_data = Packet(8, PacketID.GET_VALUES, Scale.NONE)
        if sys.platform.startswith('linux'):
            temp_list = glob.glob('/dev/tty[A]*')

            for a_port in temp_list:

                try:
                    vesc_usb = serial.Serial(a_port, 115200, timeout=0.1)
                    vesc_usb.flush()
                    sleep(2)
                    get_data.send(vesc_usb)
                    sleep(0.5)
                    if vesc_usb.in_waiting > 5:
                        buffer = Packet()
                        converted = [
                            int(elem.encode("hex"), 16)
                            for elem in vesc_usb.read_all()
                        ]
                        if buffer.process_buffer(converted):
                            self.commands.process_packet(buffer.goodpacket)
                            if self.commands.mcData.vesc_id == 100:
                                left_back_port = a_port
                                print "Found left wheel.\n"
                            elif self.commands.mcData.vesc_id == 200:
                                print "Found right wheel.\n"
                                right_back_port = a_port

                    vesc_usb.close()
                except serial.SerialException:
                    pass

        if len(left_back_port) > 0 and len(right_back_port) > 0:
            self.left_back = serial.Serial(left_back_port, 115200, timeout=0.1)
            self.right_back = serial.Serial(right_back_port,
                                            115200,
                                            timeout=0.1)
            self.left_back.flush()
            self.right_back.flush()
示例#11
0
    def lineReceived(self, line):
        """
        Called when a line has been received.

        :param line: the line
        """
        # Try to parse the line as a packet
        try:
            dct = json.loads(line, object_hook=self._byteify)
            packet = Packet.parsePacket(dct)
        except Exception as e:
            self._logger.warning("Invalid packet received: %s" % line)
            self._logger.exception(e)
            return

        # Wait for raw data if it is a container
        if isinstance(packet, Container):
            self._content = b''
            self._container = packet
            self.setRawMode()
            return  # do not go any further

        self.packetReceived(packet)
示例#12
0
              str(packet.get_next_number(32, 1)))
        print("Fault code: " + str(packet.get_next_number(8, 1)))


def get_duty_for_counter(counter):
    return min(0.05 * counter, 0.95)


phase = 0
payload = bytearray()
length = 0
crc = 0
vesc_usb = serial.Serial('COM3', 38400, timeout=0.1)
time.sleep(1)  # give the connection a second to settle

current_control = Packet(8, CURRENT_CONTROL_ID, NO_SCALE, 32, 0.3,
                         CURRENT_CONTROL_ACCURACY)
current_control_high = Packet(8, CURRENT_CONTROL_ID, NO_SCALE, 32, 0.5,
                              CURRENT_CONTROL_ACCURACY)
duty_control = Packet(8, DUTY_CONTROL_ID, NO_SCALE, 32, 0.1,
                      DUTY_CONTROL_ACCURACY)
alive = Packet(8, ALIVE_ID, NO_SCALE)
reboot = Packet(8, REBOOT_ID, NO_SCALE)
stop = Packet(8, 6, 1, 32, 0, CURRENT_CONTROL_ACCURACY)
get_rt_data = Packet(8, GET_VALUES_ID, NO_SCALE)

get_rt_data.send(vesc_usb)
data = [[] for x in range(20)]
counter = 0
data_counter = 0
wait_until = time.time() + 1
data_req_sent = False
示例#13
0
hand: readable string of the name best hand
besthand: 0 if it's not the best hand and 1 if it's the best hand
         best hand is the hand that win the most money
       
serial: integer uniquely identifying a player.
game_id: integer uniquely identifying a game.
"""

    info = PacketPokerCards.info + ( ("side", "", 's'),
                                     ("hand", "", 's'),
                                     ("bestcards", [], 'Bl'),
                                     ("board", [], 'Bl'),
                                     ("besthand", 0, 'B'),
                                     )

Packet.infoDeclare(globals(), PacketPokerBestCards, PacketPokerCards, 'POKER_BEST_CARDS', 170) # 0xaa # %SEQ%

########################################

class PacketPokerPotChips(Packet):
    """\
Semantics: the "bet" put in the "index" pot of the "game_id" game.

Direction: client <=> client

context: this packet is sent at least each time the pot index is
updated.

bet: list of pairs ( chip_value, chip_count ).
index: integer uniquely identifying a side pot in the range [0,10[
game_id: integer uniquely identifying a game.
示例#14
0
 def setandmonitorPWM(self, leftduty, rightduty):
     Packet(8, PacketID.SET_DUTY, Scale.NONE, 32, leftduty,
            Scale.E5).send(self.left_back)
     Packet(8, PacketID.SET_DUTY, Scale.NONE, 32, -rightduty,
            Scale.E5).send(self.right_back)
     '''
示例#15
0
 def send_packet(self, packet: Packet):
     packet_id: int = packet.id
     data: bytes = packet.encode()
     packet_bytes = packets.create_packet(packet_id, data)
     self.send(packet_bytes)
def main():
  # Make pygame window
  screen = pygame.display.set_mode((640,640))

  timer = 0
  numClients = 50

  # Create network of clients
  clients = []
  for i in xrange(0, numClients):
    clients.append(client.Client(i))

  # Set up random connections amongst the clients
  for i in xrange(0, numClients):
    for j in xrange(0, 5):
      clients[i].addConnection(clients[random.randrange(0, numClients)])

  # Instantiate network layer
  networkLayer = Network(clients)

  for c in clients:
    c.networkLayer = networkLayer;

  # Get user input
  keyInput = None
  while keyInput != 'q':
    message = None
    sourceID = -1
    destinationID = -1
    keyInput = raw_input("Select Option:\n's' - start\n'q' - end the program\n")
    
    # Start forming a message
    if keyInput == 's':
      # Choose a valid client index
      while sourceID < 0 or sourceID >= numClients:
        sourceID = int(raw_input("Enter the Client ID: "))
      source = clients[sourceID]

      # Choose an option
      keyInput = raw_input("\nSelect Option:\n'm' - submit message\n'd' - display client\n")

      # Send a direct message
      if keyInput == 'm':
        while destinationID < 0 or destinationID >= numClients:
          destinationID = int(raw_input("Enter the Reciever ID: "))
        destination = clients[destinationID]
        message = raw_input("Enter the message to send:\n")
        clients[sourceID].sendMessage(clients[sourceID].user, clients[destinationID].user, message, timer)

        if (len(source.networkLayer.BFS(source.ip, destination.ip)) == 0):
          print "No path between clients"
          continue;

        # Process TCP packets on sender and receiver
        while networkLayer.routing(timer) or len(source.transportLayer.tcpPackets) > 0 or len(destination.transportLayer.tcpPackets) > 0:
          drawClient(screen, source, 20, 20, destination)
          drawClient(screen, destination, 300, 20)

          # Checks if the source has packet to send
          if source.transportLayer.sendPacket():
            srcPacket = source.transportLayer.tcpPackets.pop(0)
            srcPacket.addHeader("send_time", timer)
            networkLayer.process(srcPacket)
            
            # Send the packet to a buffer for resubmission
            if not srcPacket.getHeader("syn") and not srcPacket.getHeader("fin"):
              newPacket = Packet(srcPacket)
              message = newPacket.getBody("message")
              newPacket.addBody("message", message+"(r)")
              newPacket.addHeader("fail", False)
              source.transportLayer.sentPackets.append(newPacket)

          # Checks for a retransmission packet
          retansmitPacket = source.transportLayer.checkRetransmission(timer)
          if retansmitPacket != None:
            nextPacket = Packet(retansmitPacket)
            message = nextPacket.getBody("message")
            networkLayer.process(retansmitPacket)
            nextPacket.addBody("message", message+"(r)")
            nextPacket.addHeader("fail", False)
            source.transportLayer.sentPackets.append(nextPacket)

          if destination.transportLayer.sendPacket():
            networkLayer.process(destination.transportLayer.tcpPackets.pop(0))

          timer += 1
          time.sleep(5)

        # Reset the transport layers
        source.transportLayer.reset()
        destination.transportLayer.reset()

        # Clients update their inbox
        drawClient(screen, source, 20, 20, destination)
        drawClient(screen, destination, 300, 20)

      # Display all IP addresses a client can talk to
      if keyInput == 'd':
        print clients[sourceID].connections
        drawClient(screen, source, 20, 20)