Skip to content

Commit

Permalink
Remove octal/hexadecimal parsing from IPv4. Fixes JuliaLang#9187
Browse files Browse the repository at this point in the history
  • Loading branch information
Keno authored and kleinhenz committed Jan 26, 2017
1 parent 20347a6 commit fe664fe
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
19 changes: 7 additions & 12 deletions base/socket.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ end

# Parsing

const ipv4_leading_zero_error = """
Leading zeros in IPv4 addresses are disallowed due to ambiguity.
If octal or hexadecimal, convert to decimal, otherwise remove leading zero.
"""

function parse(::Type{IPv4}, str::AbstractString)
fields = split(str,'.')
i = 1
Expand All @@ -156,18 +161,8 @@ function parse(::Type{IPv4}, str::AbstractString)
if isempty(f)
throw(ArgumentError("empty field in IPv4 address"))
end
if f[1] == '0'
if length(f) >= 2 && f[2] == 'x'
if length(f) > 8 # 2+(3*2) - prevent parseint from overflowing on 32bit
throw(ArgumentError("IPv4 field too large"))
end
r = parse(Int,f[3:end],16)
else
if length(f) > 9 # 1+8 - prevent parseint from overflowing on 32bit
throw(ArgumentError("IPv4 field too large"))
end
r = parse(Int,f,8)
end
if length(f) > 1 && f[1] == '0'
throw(ArgumentError(ipv4_leading_zero_error))
else
r = parse(Int,f,10)
end
Expand Down
12 changes: 7 additions & 5 deletions test/socket.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

@test ip"127.0.0.1" == IPv4(127,0,0,1)
@test ip"192.0" == IPv4(192,0,0,0)
@test ip"192.0xFFF" == IPv4(192,0,15,255)
@test ip"192.0xFFFF" == IPv4(192,0,255,255)
@test ip"192.0xFFFFF" == IPv4(192,15,255,255)
@test ip"192.0xFFFFFF" == IPv4(192,255,255,255)
@test ip"022.0.0.1" == IPv4(18,0,0,1)

# These used to work, but are now disallowed. Check that they error
@test_throws ArgumentError parse(IPv4, "192.0xFFF") # IPv4(192,0,15,255)
@test_throws ArgumentError parse(IPv4, "192.0xFFFF") # IPv4(192,0,255,255)
@test_throws ArgumentError parse(IPv4, "192.0xFFFFF") # IPv4(192,15,255,255)
@test_throws ArgumentError parse(IPv4, "192.0xFFFFFF") # IPv4(192,255,255,255)
@test_throws ArgumentError parse(IPv4, "022.0.0.1") # IPv4(18,0,0,1)

@test UInt(IPv4(0x01020304)) == 0x01020304
@test Int(IPv4("1.2.3.4")) == Int(0x01020304) == Int32(0x01020304)
Expand Down

0 comments on commit fe664fe

Please sign in to comment.