5
Line | |
---|
1 | # vim: ts=4 sw=4 et ai: |
---|
2 | # -*- coding: utf8 -*- |
---|
3 | """This module implements the TftpPacketFactory class, which can take a binary |
---|
4 | buffer, and return the appropriate TftpPacket object to represent it, via the |
---|
5 | parse() method.""" |
---|
6 | |
---|
7 | |
---|
8 | from .TftpShared import * |
---|
9 | from .TftpPacketTypes import * |
---|
10 | import logging |
---|
11 | |
---|
12 | log = logging.getLogger('tftpy.TftpPacketFactory') |
---|
13 | |
---|
14 | class TftpPacketFactory(object): |
---|
15 | """This class generates TftpPacket objects. It is responsible for parsing |
---|
16 | raw buffers off of the wire and returning objects representing them, via |
---|
17 | the parse() method.""" |
---|
18 | def __init__(self): |
---|
19 | self.classes = { |
---|
20 | 1: TftpPacketRRQ, |
---|
21 | 2: TftpPacketWRQ, |
---|
22 | 3: TftpPacketDAT, |
---|
23 | 4: TftpPacketACK, |
---|
24 | 5: TftpPacketERR, |
---|
25 | 6: TftpPacketOACK |
---|
26 | } |
---|
27 | |
---|
28 | def parse(self, buffer): |
---|
29 | """This method is used to parse an existing datagram into its |
---|
30 | corresponding TftpPacket object. The buffer is the raw bytes off of |
---|
31 | the network.""" |
---|
32 | log.debug("parsing a %d byte packet" % len(buffer)) |
---|
33 | (opcode,) = struct.unpack(str("!H"), buffer[:2]) |
---|
34 | log.debug("opcode is %d" % opcode) |
---|
35 | packet = self.__create(opcode) |
---|
36 | packet.buffer = buffer |
---|
37 | return packet.decode() |
---|
38 | |
---|
39 | def __create(self, opcode): |
---|
40 | """This method returns the appropriate class object corresponding to |
---|
41 | the passed opcode.""" |
---|
42 | tftpassert(opcode in self.classes, |
---|
43 | "Unsupported opcode: %d" % opcode) |
---|
44 | |
---|
45 | packet = self.classes[opcode]() |
---|
46 | |
---|
47 | return packet |
---|
Note: See
TracBrowser
for help on using the repository browser.