Package dpkt :: Module tftp
[hide private]
[frames] | no frames]

Source Code for Module dpkt.tftp

 1  # $Id: tftp.py 23 2006-11-08 15:45:33Z dugsong $ 
 2  # -*- coding: utf-8 -*- 
 3  """Trivial File Transfer Protocol.""" 
 4  from __future__ import print_function 
 5  from __future__ import absolute_import 
 6   
 7  import struct 
 8   
 9  from . import dpkt 
10   
11  # Opcodes 
12  OP_RRQ = 1  # read request 
13  OP_WRQ = 2  # write request 
14  OP_DATA = 3  # data packet 
15  OP_ACK = 4  # acknowledgment 
16  OP_ERR = 5  # error code 
17   
18  # Error codes 
19  EUNDEF = 0  # not defined 
20  ENOTFOUND = 1  # file not found 
21  EACCESS = 2  # access violation 
22  ENOSPACE = 3  # disk full or allocation exceeded 
23  EBADOP = 4  # illegal TFTP operation 
24  EBADID = 5  # unknown transfer ID 
25  EEXISTS = 6  # file already exists 
26  ENOUSER = 7  # no such user 
27   
28   
29 -class TFTP(dpkt.Packet):
30 """Trivial File Transfer Protocol. 31 32 TODO: Longer class information.... 33 34 Attributes: 35 __hdr__: Header fields of TFTP. 36 TODO. 37 """ 38 39 __hdr__ = (('opcode', 'H', 1), ) 40
41 - def unpack(self, buf):
42 dpkt.Packet.unpack(self, buf) 43 if self.opcode in (OP_RRQ, OP_WRQ): 44 l = self.data.split(b'\x00') 45 self.filename = l[0] 46 self.mode = l[1] 47 self.data = b'' 48 elif self.opcode in (OP_DATA, OP_ACK): 49 self.block = struct.unpack('>H', self.data[:2])[0] 50 self.data = self.data[2:] 51 elif self.opcode == OP_ERR: 52 self.errcode = struct.unpack('>H', self.data[:2]) 53 self.errmsg = self.data[2:].split(b'\x00')[0] 54 self.data = b''
55
56 - def __len__(self):
57 return len(bytes(self))
58
59 - def __bytes__(self):
60 if self.opcode in (OP_RRQ, OP_WRQ): 61 s = self.filename + b'\x00' + self.mode + b'\x00' 62 elif self.opcode in (OP_DATA, OP_ACK): 63 s = struct.pack('>H', self.block) 64 elif self.opcode == OP_ERR: 65 s = struct.pack('>H', self.errcode) + (b'%s\x00' % self.errmsg) 66 else: 67 s = b'' 68 return self.pack_hdr() + s + self.data
69 70
71 -def test_op_rrq():
72 s = b'\x00\x01\x72\x66\x63\x31\x33\x35\x30\x2e\x74\x78\x74\x00\x6f\x63\x74\x65\x74\x00' 73 t = TFTP(s) 74 assert t.filename == b'rfc1350.txt' 75 assert t.mode == b'octet' 76 assert bytes(t) == s
77 78
79 -def test_op_data():
80 s = b'\x00\x03\x00\x01\x0a\x0a\x4e\x65\x74\x77\x6f\x72\x6b\x20\x57\x6f\x72\x6b\x69\x6e\x67\x20\x47\x72\x6f\x75\x70' 81 t = TFTP(s) 82 assert t.block == 1 83 assert t.data == b'\x0a\x0aNetwork Working Group' 84 assert bytes(t) == s
85 86
87 -def test_op_err():
88 pass # XXX - TODO
89 90 91 if __name__ == '__main__': 92 test_op_rrq() 93 test_op_data() 94 test_op_err() 95 96 print('Tests Successful...') 97