summaryrefslogtreecommitdiff
path: root/src/Data/Torrent/InfoHash.hs
diff options
context:
space:
mode:
authorSam Truzjan <pxqr.sta@gmail.com>2013-11-29 18:37:42 +0400
committerSam Truzjan <pxqr.sta@gmail.com>2013-11-29 18:37:42 +0400
commit88b590239ad66f8624723beefefa8b0ef56942e1 (patch)
treec5e2e3afcb0ca97d469b371cbfada675a462442c /src/Data/Torrent/InfoHash.hs
parentc689257a818c0a7581666f4bdfd4549e52dbd075 (diff)
More safiety in InfoHash convertions
Diffstat (limited to 'src/Data/Torrent/InfoHash.hs')
-rw-r--r--src/Data/Torrent/InfoHash.hs16
1 files changed, 8 insertions, 8 deletions
diff --git a/src/Data/Torrent/InfoHash.hs b/src/Data/Torrent/InfoHash.hs
index 6313948b..15682250 100644
--- a/src/Data/Torrent/InfoHash.hs
+++ b/src/Data/Torrent/InfoHash.hs
@@ -125,21 +125,21 @@ instance Convertible BS.ByteString InfoHash where
125-- | Parse infohash from base16\/base32\/base64 encoded string. 125-- | Parse infohash from base16\/base32\/base64 encoded string.
126instance Convertible Text InfoHash where 126instance Convertible Text InfoHash where
127 safeConvert t 127 safeConvert t
128 | hashLen <= 28 = 128 | 26 <= hashLen && hashLen <= 28 =
129 case Base64.decode hashStr of 129 case Base64.decode hashStr of
130 Left msg -> convError ("invalid base64 encoding " ++ msg) t 130 Left msg -> convError ("invalid base64 encoding " ++ msg) t
131 Right ihStr -> pure $ InfoHash ihStr 131 Right ihStr -> safeConvert ihStr
132 132
133 | hashLen == 32 = 133 | hashLen == 32 =
134 case Base32.decode hashStr of 134 case Base32.decode hashStr of
135 Left msg -> convError msg t 135 Left msg -> convError msg t
136 Right ihStr -> pure $ InfoHash ihStr 136 Right ihStr -> safeConvert ihStr
137 137
138 | hashLen == 40 = 138 | hashLen == 40 =
139 let (ihStr, inv) = Base16.decode hashStr 139 let (ihStr, inv) = Base16.decode hashStr
140 in if BS.length inv == 0 140 in if BS.length inv /= 0
141 then pure $ InfoHash ihStr 141 then convError "invalid base16 encoding" t
142 else convError "invalid base16 encoding" t 142 else safeConvert ihStr
143 143
144 | otherwise = convError "invalid length" t 144 | otherwise = convError "invalid length" t
145 where 145 where
@@ -156,8 +156,8 @@ instance ToJSON InfoHash where
156 156
157-- | Convert from base16\/base32\/base64 encoded JSON string. 157-- | Convert from base16\/base32\/base64 encoded JSON string.
158instance FromJSON InfoHash where 158instance FromJSON InfoHash where
159 parseJSON = withText "JSON" $ -- TODO 159 parseJSON = withText "InfoHash" $
160 maybe (fail "could not parse InfoHash") pure . textToInfoHash 160 either (fail . prettyConvertError) pure . safeConvert
161 161
162ignoreErrorMsg :: Either a b -> Maybe b 162ignoreErrorMsg :: Either a b -> Maybe b
163ignoreErrorMsg = either (const Nothing) Just 163ignoreErrorMsg = either (const Nothing) Just