Skip to content

Commit

Permalink
Some agents do not produce valid IP addresses -- accept addresses tha…
Browse files Browse the repository at this point in the history
…t do not have exactly 4 octets
  • Loading branch information
hallidave committed Sep 7, 2010
1 parent 4fbdf28 commit 60a9fba
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
25 changes: 15 additions & 10 deletions lib/snmp/varbind.rb
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def make_object_id(oid)
class IpAddress
class << self
def decode(value_data)
IpAddress.new(value_data)
IpAddress.new(value_data, false)
end
end

Expand All @@ -241,14 +241,17 @@ def asn1_type
##
# Create an IpAddress object. The constructor accepts either a raw
# four-octet string or a formatted string of integers separated by dots
# (i.e. "10.1.2.3").
# (i.e. "10.1.2.3"). Validation of the format can be disabled by setting
# the 'validate' flag to false.
#
def initialize(value_data)
def initialize(value_data, validate=true)
ip = value_data.to_str
if ip.length > 4
ip = parse_string(ip)
elsif ip.length != 4
raise InvalidIpAddress, "Expected 4 octets or formatted string, got #{value_data.inspect}"
if (validate)
if ip.length > 4
ip = parse_string(ip)
elsif ip.length != 4
raise InvalidIpAddress, "Expected 4 octets or formatted string, got #{value_data.inspect}"
end
end
@value = ip
end
Expand Down Expand Up @@ -298,12 +301,14 @@ def encode
private
def parse_string(ip_string)
parts = ip_string.split(".")
raise InvalidIpAddress, ip_string.inspect if parts.length != 4
if parts.length != 4
raise InvalidIpAddress, "Expected four octets separated by dots, not #{ip_string.inspect}"
end
value_data = ""
parts.each do |s|
octet = s.to_i
raise InvalidIpAddress, ip_string.inspect if octet > 255
raise InvalidIpAddress, ip_string.inspect if octet < 0
raise InvalidIpAddress, "Octets cannot be greater than 255: #{ip_string.inspect}" if octet > 255
raise InvalidIpAddress, "Octets cannot be negative: #{ip_string.inspect}" if octet < 0
value_data << octet.chr
end
value_data
Expand Down
11 changes: 11 additions & 0 deletions test/test_varbind.rb
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,17 @@ def test_ip_address_decode
assert_equal("1.2.3.4", ip.to_s)
end

def test_ip_address_decode_extra_octets
ip = IpAddress.decode("\000\000\000\000\000\000\000\000")
assert_equal("0.0.0.0.0.0.0.0", ip.to_s)

ip = IpAddress.decode("\001\002\003")
assert_equal("1.2.3", ip.to_s)

ip = IpAddress.decode("\001\002\003\004\005")
assert_equal("1.2.3.4.5", ip.to_s)
end

def test_ip_address_equals
ip1 = IpAddress.new("1.2.3.4")
ip2 = IpAddress.new("1.2.3.4")
Expand Down

0 comments on commit 60a9fba

Please sign in to comment.