def build(self):
        """
		Build the packet
		Adds padding to the data, adds the RID, PID, opcode, and checksum.

		Parameters: None

		Returns: Bytestring of the packet.

		Raises: None

		"""
        # Construct the packet's data

        # Do a TMR expansion where the data is replicated 3 times but not next to each other
        # to avoid burst errors.
        # if self.useFEC:
        # 	data = self.data * 3
        # else:
        # 	data = self.data
        data = self.data

        padding = DataPacket.data_size - len(data)
        data += DataPacket.padding_byte * padding
        self.paddingSize = padding
        packet = self.rid.to_bytes(
            1, byteorder='big') + self.opcode + DataPacket.pid.to_bytes(
                4, byteorder='big') + data
        # If the packet is for download use safe checksum maker
        if self.downloadPacketChecksum:
            packet += self.generateDownloadChecksum(data)
        else:
            packet += generateChecksum(packet)
        # After constructing the packet's contents, pad the end of the packet until we reach the max size.
        return packet
    def build(self):
        """
		Override for the dummy packet's build.

		Parameters: None

		Returns: the packet's bytestring

		Raises: None

		"""
        toSend = self.rid + self.opcode + self.data
        return toSend + generateChecksum(toSend)
示例#3
0
    def checkValidity(fieldData, packetData):
        logger.logInfo("Entered: checkValidity")
        """
		Check to see if a packet is valid and not corrupt.

		Parameters:
		fieldData - dictonary returned by decodePacket

		Returns: tuple of data
		tuple[0] = True if the packet is good, False if corrupted
		tuple[1] = the fieldData passed in or modified data

		Raises: None

		"""
        # Figure out the data without the checksum
        if fieldData:
            if fieldData['TYPE'] == 'UNKNOWN':
                isValid = False
                fieldData = None
            else:
                packetString = bytes([
                    fieldData['route']
                ]) + fieldData['opcode'] + fieldData['contents']
                isValid = fieldData['route'] in validRoutes and fieldData[
                    'checksum'] == generateChecksum(packetData[:-4])

            if fieldData['TYPE'] == 'DATA':
                pass
            elif fieldData['TYPE'] == 'NORM':
                #print("The tag of this packet is", fieldData['tag'].decode("utf-8"))
                #print("FEILD DATA TAG:", fieldData['tag'])
                validTag = checker.isValidTag(fieldData['tag'])
                if isValid and not validTag:
                    logger.logSystem(
                        'Interpreter: A valid packet came in, but the tag was wrong. The packet is being dropped.'
                    )
                isValid = isValid and validTag

            elif fieldData['TYPE'] == 'DLACK':
                # Honestly, I don't think there's anything to do here...
                checker.clearTagList()

        else:
            isValid = False
        logger.logInfo("Exited: checkValidity")
        return isValid, fieldData
    def finish(information):
        """
		Finish the scaffold, remove the extension, and remove the extra padding by the last packet.

		Parameters: information - all the data found in the NOOP! packet.

		Returns: a tuple of values
		tuple[0] = True or False if the checksums match from the calculated one and the file's reported checksum
		tuple[1] = the filename of the downloaded file

		Raises: None

		"""
        if UploadRequest.isActive():
            information = information.split(b' ')
            checksum = information[0]
            paddingUsed = int.from_bytes(information[1], byteorder='big')
            filename = information[2][:information[2].
                                      find(DataPacket.padding_byte)].replace(
                                          b'/', b'@').decode('ascii')
            with open(TEMPPATH + filename + '.scaffold', 'rb+') as f:
                info = f.read()
                f.seek(0)
                f.truncate()
                if paddingUsed:
                    f.write(info[:-paddingUsed])
                else:
                    f.write(info)
            checksumMatch = checksum == generateChecksum(
                open(TEMPPATH + filename + '.scaffold', 'rb').read())
            try:
                os.rename('{}{}.scaffold'.format(TEMPPATH, filename),
                          ROOTPATH + filename.replace('@', '/'))
                os.rename('{}{}.nore'.format(TEMPPATH, filename),
                          "{}{}.nore".format(GRAVEPATH, filename))
            except:
                pass
            return checksumMatch, UploadRequest.finished(filename)
    def build(self):
        """
		Build a packet out of the four chunks

		Parameters: None

		Returns: The bytestring of the packet

		Raises: None

		"""
        if ChunkPacket.complete:
            packet = b''
            for chunk in ChunkPacket.chunks:
                packet += chunk
            if len(packet) != DataPacket.max_size:
                self.logger.logSystem(
                    "Packet is not {} bytes! It is {} bytes!".format(
                        str(DataPacket.max_size), str(len(packet))),
                    str(packet)[50:])
                #print("QUICK FIX IN QPACE FILE HANDLER")
                packet = packet[(len(packet) - DataPacket.max_size):]
                if (packet[-4:] != generateChecksum(packet[:-4])):
                    packet = b''
                    #print("THE DATA SEND ISN'T VALID:\nCHECKSUMS DON'T MATCH")
                    Command.PrivilegedPacket(
                        opcode=b"ERROR", plainText=b"ERROR OCCURING").send()
                #else:
                #print("QUICK FIX IS VALID")
            ChunkPacket.chunks[:] = []  #reset chunks to empty
            ChunkPacket.complete = False  #reset copmlete to False
            ChunkPacket.lastInputTime = None  # reset the timer.
            return packet
        else:
            #print('Packet is not complete yet.')
            pass