Skip to content

Commit

Permalink
Merge PR #63
Browse files Browse the repository at this point in the history
  • Loading branch information
kazu-yamamoto committed Jul 11, 2024
2 parents 892942b + 900ad8e commit 7b0cf71
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 11 deletions.
31 changes: 22 additions & 9 deletions Data/IP/Addr.hs
Original file line number Diff line number Diff line change
Expand Up @@ -500,17 +500,30 @@ octet = 0 <$ char '0'
in if n' <= 255 then f n' else Nothing

ip4 :: Parser IPv4
ip4 = skipSpaces >> toIPv4 <$> ip4'

ip4' :: Parser [Int]
ip4' = do
as <- octet `sepBy1` char '.'
when (length as /= 4) (fail "IPv4 address")
ip4 = skipSpaces >> toIPv4 <$> ip4' True

ip4' :: Bool -> Parser [Int]
ip4' checkTermination = do
a0 <- octet
_ <- char '.'
a1 <- octet
_ <- char '.'
a2 <- octet
_ <- char '.'
a3 <- octet
let as = [a0, a1, a2, a3]
skipSpaces
when checkTermination termination
return as

skipSpaces :: Parser ()
skipSpaces = void $ many (char ' ')

termination :: Parser ()
termination = P $ \str -> case str of
[] -> (Just (), "")
_ -> (Nothing, str)

----------------------------------------------------------------
--
-- IPv6 Parser (RFC 4291)
Expand Down Expand Up @@ -562,16 +575,16 @@ ip6' = ip4Embedded
ip4Embedded :: Parser [Int]
ip4Embedded = try (do colon2
bs <- beforeEmbedded
embedded <- ip4'
embedded <- ip4' True
format [] (bs ++ ip4ToIp6 embedded))
-- matches 2001:db8::192.0.2.1
<|> try (do bs1 <- manyTill (try $ hex <* char ':') (char ':')
bs2 <- option [] beforeEmbedded
embedded <- ip4'
embedded <- ip4' True
format bs1 (bs2 ++ ip4ToIp6 embedded))
-- matches 2001:db8:11e:c00:aa:bb:192.0.2.1
<|> try (do bs <- beforeEmbedded
embedded <- ip4'
embedded <- ip4' True
let rs = bs ++ ip4ToIp6 embedded
check rs
return rs)
Expand Down
3 changes: 2 additions & 1 deletion Data/IP/Range.hs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ maskLen maxLen = do

ip4range :: Parser (AddrRange IPv4)
ip4range = do
ip <- ip4
skipSpaces
ip <- toIPv4 <$> ip4' False
len <- maskLen 32
let msk = maskIPv4 len
adr = ip `maskedIPv4` msk
Expand Down
8 changes: 7 additions & 1 deletion test/IPSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ import RouteTableSpec ()
data InvalidIPv4Str = Iv4 String deriving (Show)

instance Arbitrary InvalidIPv4Str where
arbitrary = arbitraryIIPv4Str arbitrary 32
arbitrary =
frequency [(9, arbitraryIIPv4Str arbitrary 32)
,(1, Iv4 . (++ ".") . show <$> genIPv4)
]
where
genIPv4 :: Gen IPv4
genIPv4 = arbitrary

arbitraryIIPv4Str :: Gen IPv4 -> Int -> Gen InvalidIPv4Str
arbitraryIIPv4Str adrGen msklen = toIv4 <$> adrGen <*> lenGen
Expand Down

0 comments on commit 7b0cf71

Please sign in to comment.