Norman James | 8b2b722 | 2015-10-08 07:01:38 -0500 | [diff] [blame] | 1 | """This module implements the TftpPacketFactory class, which can take a binary |
| 2 | buffer, and return the appropriate TftpPacket object to represent it, via the |
| 3 | parse() method.""" |
| 4 | |
| 5 | from TftpShared import * |
| 6 | from TftpPacketTypes import * |
| 7 | |
| 8 | class TftpPacketFactory(object): |
| 9 | """This class generates TftpPacket objects. It is responsible for parsing |
| 10 | raw buffers off of the wire and returning objects representing them, via |
| 11 | the parse() method.""" |
| 12 | def __init__(self): |
| 13 | self.classes = { |
| 14 | 1: TftpPacketRRQ, |
| 15 | 2: TftpPacketWRQ, |
| 16 | 3: TftpPacketDAT, |
| 17 | 4: TftpPacketACK, |
| 18 | 5: TftpPacketERR, |
| 19 | 6: TftpPacketOACK |
| 20 | } |
| 21 | |
| 22 | def parse(self, buffer): |
| 23 | """This method is used to parse an existing datagram into its |
| 24 | corresponding TftpPacket object. The buffer is the raw bytes off of |
| 25 | the network.""" |
| 26 | log.debug("parsing a %d byte packet", len(buffer)) |
| 27 | (opcode,) = struct.unpack("!H", buffer[:2]) |
| 28 | log.debug("opcode is %d", opcode) |
| 29 | packet = self.__create(opcode) |
| 30 | packet.buffer = buffer |
| 31 | return packet.decode() |
| 32 | |
| 33 | def __create(self, opcode): |
| 34 | """This method returns the appropriate class object corresponding to |
| 35 | the passed opcode.""" |
| 36 | tftpassert(self.classes.has_key(opcode), |
| 37 | "Unsupported opcode: %d" % opcode) |
| 38 | |
| 39 | packet = self.classes[opcode]() |
| 40 | |
| 41 | return packet |