# $Id$

"""Trivial File Transfer Protocol."""

import struct
import dpkt

# Opcodes
OP_RRQ     = 1    # read request
OP_WRQ     = 2    # write request
OP_DATA    = 3    # data packet
OP_ACK     = 4    # acknowledgment
OP_ERR     = 5    # error code

# Error codes
EUNDEF     = 0    # not defined
ENOTFOUND  = 1    # file not found
EACCESS    = 2    # access violation
ENOSPACE   = 3    # disk full or allocation exceeded
EBADOP     = 4    # illegal TFTP operation
EBADID     = 5    # unknown transfer ID
EEXISTS    = 6    # file already exists
ENOUSER    = 7    # no such user

class TFTP(dpkt.Packet):
    __hdr__ = (('opcode', 'H', 1), )
    
    def unpack(self, buf):
        dpkt.Packet.unpack(self, buf)
        if self.opcode in (OP_RRQ, OP_WRQ):
            l = self.data.split('\x00')
            self.filename = l[0]
            self.mode = l[1]
            self.data = ''
        elif self.opcode in (OP_DATA, OP_ACK):
            self.block = struct.unpack('>H', self.data[:2])
            self.data = self.data[2:]
        elif self.opcode == OP_ERR:
            self.errcode = struct.unpack('>H', self.data[:2])
            self.errmsg = self.data[2:].split('\x00')[0]
            self.data = ''

    def __len__(self):
        return len(str(self))

    def __str__(self):
        if self.opcode in (OP_RRQ, OP_WRQ):
            s = '%s\x00%s\x00' % (self.filename, self.mode)
        elif self.opcode in (OP_DATA, OP_ACK):
            s = struct.pack('>H', self.block)
        elif self.opcode == OP_ERR:
            s = struct.pack('>H', self.errcode) + ('%s\x00' % self.errmsg)
        else:
            s = ''
        return self.pack_hdr() + s + self.data

@@ -241,16 +241,58 @@
 ror code
+%0AOP_OACK    = 6    # option acknowledgment
 %0A%0A# Erro
@@ -611,16 +611,55 @@
 uch user
+%0AEOPTNEG    = 8    # option negotiation
 %0A%0Aclass 
@@ -840,17 +840,52 @@
         
-l
+(self.filename,self.mode,rfc2347str)
  = self.
@@ -901,16 +901,19 @@
 t('%5Cx00'
+, 2
 )%0A      
@@ -922,57 +922,218 @@
     
-self.filename = l%5B0%5D%0A            self.mode = l%5B1%5D
+if rfc2347str:%0A                option_list = rfc2347str%5B:-1%5D.split('%5Cx00')%0A                self.options = dict(zip(option_list%5B:-1:2%5D, option_list%5B1::2%5D))%0A            else:%0A                self.options = dict()
 %0A   
@@ -1786,32 +1786,32 @@
 code == OP_ERR:%0A
-
             s = 
@@ -1869,16 +1869,211 @@
 errmsg)%0A
+        elif self.opcode == OP_OACK:%0A            if self.options:%0A                s = '%5Cx00'.join(%5B'%5Cx00'.join(item) for item in d.items()%5D) + '%5Cx00'%0A            else:%0A                s = '%5Cx00'%0A
         

add support for rfc2347