Class: TFTP::Protocol::Packet

Inherits:
Object
  • Object
show all
Defined in:
lib/em-tftp.rb

Overview

Used to decode incoming packets TFTP packets have a simple structure: the port number from the encapsulating UDP datagram doubles as a ‘transfer ID’,

allowing multiple, simultaneous transfers betweent the same hosts

The first 2 bytes of the payload are an integral ‘opcode’ from 1-5, in network byte order The opcodes are: Read ReQuest, Write ReQuest, DATA, ACK, and ERROR Depending on the opcode, different fields can follow. All fields are either 16-bit integers in network byte order,

or null-terminated strings

Constant Summary collapse

OPCODES =
{1 => :rrq, 2 => :wrq, 3 => :data, 4 => :ack, 5 => :error}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Packet

Returns a new instance of Packet.

Raises:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/em-tftp.rb', line 45

def initialize(data)
  raise TFTP::Error, "TFTP packet too small (#{data.size} bytes)" if data.size < 4
  raise TFTP::Error, "TFTP packet too large (#{data.size} bytes)" if data.size > 516
  @opcode = OPCODES[data.getbyte(1)]
  if opcode == :data
    @block_no = (data.getbyte(2) << 8) + data.getbyte(3)
    @data = data[4..-1]
  elsif opcode == :rrq || opcode == :wrq
    @filename, _mode = data[2..-1].unpack("Z*Z*") # mode is ignored
  elsif opcode == :error
    @err_code = (data.getbyte(2) << 8) + data.getbyte(3)
    @err_msg  = data[4..-2] # don't include null terminator
    if @err_msg.size == 0
      @err_msg = ERROR_MESSAGES[@err_code] || "Unknown error"
    end
    raise TFTP::Error, @err_msg
  elsif opcode == :ack
    @block_no = (data.getbyte(2) << 8) + data.getbyte(3)
  else
    raise TFTP::Error, "Unknown TFTP packet type (opcode #{data.getbyte(1)})"
  end
end

Instance Attribute Details

#block_noObject (readonly)

Returns the value of attribute block_no.



68
69
70
# File 'lib/em-tftp.rb', line 68

def block_no
  @block_no
end

#dataObject (readonly)

Returns the value of attribute data.



68
69
70
# File 'lib/em-tftp.rb', line 68

def data
  @data
end

#filenameObject (readonly)

Returns the value of attribute filename.



68
69
70
# File 'lib/em-tftp.rb', line 68

def filename
  @filename
end

#opcodeObject (readonly)

Returns the value of attribute opcode.



68
69
70
# File 'lib/em-tftp.rb', line 68

def opcode
  @opcode
end