blob: 154aec83d12557839d6070b38a067b30ce3f988e [file] [log] [blame]
Norman James8b2b7222015-10-08 07:01:38 -05001"""This module implements the TftpPacketFactory class, which can take a binary
2buffer, and return the appropriate TftpPacket object to represent it, via the
3parse() method."""
4
5from TftpShared import *
6from TftpPacketTypes import *
7
8class 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