2014-07-21 20:40:18 +00:00
|
|
|
# -*- coding: binary -*-
|
2014-07-18 17:29:14 +00:00
|
|
|
|
|
|
|
module Rex
|
|
|
|
module Proto
|
|
|
|
# SIP protocol support
|
|
|
|
module SIP
|
|
|
|
SIP_STATUS_REGEX = /^SIP\/(\d\.\d) (\d{3})\s*(.*)$/
|
|
|
|
|
2014-07-18 18:33:47 +00:00
|
|
|
# Represents a generic SIP message
|
2014-07-18 18:25:20 +00:00
|
|
|
class Message
|
|
|
|
attr_accessor :headers
|
|
|
|
|
|
|
|
def initialize
|
|
|
|
@headers = {}
|
|
|
|
end
|
2014-07-18 17:29:14 +00:00
|
|
|
|
2014-07-18 18:25:20 +00:00
|
|
|
# Returns a list of all values from all +name+ headers, regardless of case,
|
|
|
|
# or nil if no matching header is found
|
2014-07-18 17:29:14 +00:00
|
|
|
def header(name)
|
2014-07-18 18:25:20 +00:00
|
|
|
matches = @headers.select { |k, _| k.downcase == name.downcase }
|
|
|
|
return nil if matches.empty?
|
|
|
|
matches.values.flatten
|
2014-07-18 17:29:14 +00:00
|
|
|
end
|
|
|
|
|
2014-07-18 18:25:20 +00:00
|
|
|
# Returns a hash of header name to values mapping
|
|
|
|
# from the provided message, or nil if no headers
|
|
|
|
# are found
|
|
|
|
def self.extract_headers(message)
|
|
|
|
pairs = message.scan(/^([^\s:]+):\s*(.*)$/)
|
|
|
|
return nil if pairs.empty?
|
|
|
|
headers = {}
|
|
|
|
pairs.each do |pair|
|
|
|
|
headers[pair.first] ||= []
|
|
|
|
headers[pair.first] << pair.last.strip
|
|
|
|
end
|
|
|
|
headers
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Represents a SIP response message
|
|
|
|
class Response < Message
|
|
|
|
attr_accessor :code, :message, :status_line, :version
|
|
|
|
|
2014-07-18 18:33:47 +00:00
|
|
|
# Parses +data+, constructs and returns a Response
|
2014-07-18 17:29:14 +00:00
|
|
|
def self.parse(data)
|
|
|
|
response = Response.new
|
|
|
|
# do some basic sanity checking on this response to ensure that it is SIP
|
2014-07-18 18:25:20 +00:00
|
|
|
response.status_line = data.split(/\r\n/)[0]
|
|
|
|
unless response.status_line && response.status_line =~ SIP_STATUS_REGEX
|
2014-07-18 20:27:21 +00:00
|
|
|
fail(ArgumentError, "Invalid SIP status line: #{response.status_line}")
|
2014-07-18 17:29:14 +00:00
|
|
|
end
|
|
|
|
response.version = Regexp.last_match(1)
|
|
|
|
response.code = Regexp.last_match(2)
|
|
|
|
response.message = Regexp.last_match(3)
|
2014-07-18 18:25:20 +00:00
|
|
|
response.headers = extract_headers(data)
|
2014-07-18 17:29:14 +00:00
|
|
|
response
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|