]> git.rkrishnan.org Git - functorrent.git/blobdiff - src/FuncTorrent/Utils.hs
WIP: UDP tracker, compiles
[functorrent.git] / src / FuncTorrent / Utils.hs
index 4d89e8348cdf2d8a3f71caf47935b285083ca9fc..fe9b423eeff6f53542b1712339e595c089c298f6 100644 (file)
  -}
 
 module FuncTorrent.Utils
-       (createDummyFile,
-        writeFileAtOffset,
-        readFileAtOffset,
-        splitNum,
-        splitN,
-        verifyHash
+       ( createDummyFile
+       , writeFileAtOffset
+       , readFileAtOffset
+       , splitNum
+       , splitN
+       , verifyHash
+       , IP
+       , Port
+       , toIP
+       , toPort
        )
        where
 
@@ -32,10 +36,15 @@ import Prelude hiding (writeFile, take)
 import qualified Crypto.Hash.SHA1 as SHA1 (hash)
 import Control.Exception.Base (IOException, try)
 import Data.ByteString (ByteString, writeFile, hPut, hGet, take)
+import qualified Data.ByteString.Base16 as B16 (encode)
 import qualified Data.ByteString.Char8 as BC
+import Data.List (intercalate)
 import System.IO (Handle, hSeek, SeekMode(..))
 import System.Directory (doesFileExist)
 
+type IP = String
+type Port = Integer
+
 splitN :: Int -> BC.ByteString -> [BC.ByteString]
 splitN n bs | BC.null bs = []
             | otherwise = BC.take n bs : splitN n (BC.drop n bs)
@@ -68,3 +77,14 @@ readFileAtOffset h offset len = do
 verifyHash :: ByteString -> ByteString -> Bool
 verifyHash bs pieceHash =
   take 20 (SHA1.hash bs) == pieceHash
+
+toPort :: ByteString -> Port
+toPort = read . ("0x" ++) . BC.unpack . B16.encode
+
+toIP :: ByteString -> IP
+toIP = Data.List.intercalate "." .
+       map (show . toInt . ("0x" ++) . BC.unpack) .
+       splitN 2 . B16.encode
+
+toInt :: String -> Integer
+toInt = read