class PacketGen::Header::HTTP::Response

An HTTP/1.1 Response packet consists of:

Create a HTTP Response header

# standalone
http_resp = PacketGen::Header::HTTP::Response.new
# in a packet
pkt = PacketGen.gen("IP").add("TCP").add("HTTP::Response")
# access to HTTP Response header
pkt.http_response # => PacketGen::Header::HTTP::Response

Note: When creating a HTTP Response packet, sport and dport attributes of TCP header are not set.

HTTP Response attributes

http_resp.version     = "HTTP/1.1"
http_resp.status_code = "200"
http_resp.status_mesg = "OK"
http_resp.body        = "this is a body"
http_resp.headers     = "Host: tcpdump.org"     # string or
http_resp.headers     = { "Host": "tcpdump.org" } # even a hash

@author Kent 'picat' Gruber

Public Class Methods

new(options={}) click to toggle source

@param [Hash] options @option options [String] :version @option options [String] :status_code @option options [String] :status_mesg @option options [String] :body @option options [Hash] :headers

Calls superclass method PacketGen::Header::Base::new
# File lib/packetgen/header/http/response.rb, line 62
def initialize(options={})
  super(options)
  self.headers ||= options[:headers]
end

Public Instance Methods

parse?() click to toggle source
# File lib/packetgen/header/http/response.rb, line 101
def parse?
  version.start_with?('HTTP/1.')
end
read(str) click to toggle source

Read in the HTTP portion of the packet, and parse it. @return [PacketGen::HTTP::Response]

# File lib/packetgen/header/http/response.rb, line 69
def read(str)
  str = str.bytes.map!(&:chr).join unless str.valid_encoding?
  arr = str.split("\r\n")
  headers = [] # header stream
  data = [] # data stream
  switch = false
  arr.each do |line|
    if line.empty?
      data << line if switch # already done
      switch = true
      next
    end
    case switch
    when true
      data << line
    else
      headers << line
    end
  end
  unless headers.empty?
    first_line = headers.shift.split
    if first_line.size >= 3
      self[:version].read first_line[0]
      self[:status_code].read first_line[1]
      self[:status_mesg].read first_line[2..-1].join(' ')
    end
    self[:headers].read(headers.join("\n"))
  end
  self[:body].read data.join("\n")
  self
end
to_s() click to toggle source

String representation of data. @return [String]

# File lib/packetgen/header/http/response.rb, line 107
def to_s
  raise FormatError, 'Missing #status_code.' if self.status_code.empty?
  raise FormatError, 'Missing #status_mesg.' if self.status_mesg.empty?
  raise FormatError, 'Missing #version.'     if self.version.empty?

  str = +''
  str << self.version << ' ' << self.status_code << ' ' << self.status_mesg << "\r\n"
  str << self[:headers].to_s if self[:headers].given?
  str << self.body
end