From c689257a818c0a7581666f4bdfd4549e52dbd075 Mon Sep 17 00:00:00 2001 From: Sam Truzjan Date: Fri, 29 Nov 2013 18:30:13 +0400 Subject: Catch base32 decoding errors in pure code --- bittorrent.cabal | 4 +--- src/Data/Torrent/InfoHash.hs | 12 ++++++------ 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/bittorrent.cabal b/bittorrent.cabal index 6d31ca1f..46be6600 100644 --- a/bittorrent.cabal +++ b/bittorrent.cabal @@ -97,7 +97,6 @@ library , conduit >= 1.0 , network-conduit >= 1.0 , cereal-conduit >= 0.5 - , binary-conduit -- Data & Data structures , bytestring >= 0.10.0.0 @@ -117,10 +116,9 @@ library -- Codecs & Serialization , aeson , base16-bytestring - , base32-bytestring + , base32-bytestring >= 0.2 , base64-bytestring , bencoding >= 0.4 - , binary , cereal >= 0.3 -- Time diff --git a/src/Data/Torrent/InfoHash.hs b/src/Data/Torrent/InfoHash.hs index f730effa..6313948b 100644 --- a/src/Data/Torrent/InfoHash.hs +++ b/src/Data/Torrent/InfoHash.hs @@ -127,11 +127,13 @@ instance Convertible Text InfoHash where safeConvert t | hashLen <= 28 = case Base64.decode hashStr of - Left msg -> convError ("invalid base64 encoding" ++ msg) t + Left msg -> convError ("invalid base64 encoding " ++ msg) t Right ihStr -> pure $ InfoHash ihStr - | hashLen == 32 = pure $ InfoHash $ Base32.decode hashStr --- TODO FIX Base32.decode can return 'undefined' + | hashLen == 32 = + case Base32.decode hashStr of + Left msg -> convError msg t + Right ihStr -> pure $ InfoHash ihStr | hashLen == 40 = let (ihStr, inv) = Base16.decode hashStr @@ -146,9 +148,7 @@ instance Convertible Text InfoHash where -- | Decode from base16\/base32\/base64 encoded string. instance IsString InfoHash where - fromString str = fromMaybe err $ textToInfoHash $ T.pack str - where - err = error $ "fromString: invalid infohash string" ++ str + fromString = either (error . prettyConvertError) id . safeConvert . T.pack -- | Convert to base16 encoded JSON string. instance ToJSON InfoHash where -- cgit v1.2.3