]> git.rkrishnan.org Git - functorrent.git/blobdiff - src/FuncTorrent/Peer.hs
peer: more refactoring. Supports all messages as before
[functorrent.git] / src / FuncTorrent / Peer.hs
index 798f60acf0712eef0c0644b320c8fe97750cb212..cf5b66d35f35e6069b26cf1f56ecb1d893984fd8 100644 (file)
 {-# LANGUAGE OverloadedStrings #-}
 module FuncTorrent.Peer
     (Peer(..),
-     handShake
+     handlePeerMsgs
     ) where
 
-import Prelude hiding (lookup, concat, replicate, splitAt)
+import Prelude hiding (lookup, concat, replicate, splitAt, take)
 
-import System.IO
-import Data.ByteString (ByteString, unpack, concat, hGet, hPut, singleton)
-import Data.ByteString.Char8 (replicate, pack)
+import System.IO (Handle, BufferMode(..), hSetBuffering)
+import Data.ByteString (ByteString, unpack, concat, hGet, hPut, take, empty)
+import qualified Data.ByteString.Char8 as BC (length)
 import Network (connectTo, PortID(..))
+import Control.Monad.State
+import Data.Bits
+import Data.Word (Word8)
+import Data.Map (Map, fromList, toList, (!), mapWithKey, adjust)
+import qualified Crypto.Hash.SHA1 as SHA1 (hash)
 
-type ID = String
-type IP = String
-type Port = Integer
-
-data PeerState = PeerState { am_choking :: Bool
-                           , am_interested :: Bool
-                           , peer_choking :: Bool
-                           , peer_interested :: Bool }
-
--- | Peer is a PeerID, IP address, port tuple
-data Peer = Peer ID IP Port
-          deriving (Show, Eq)
-
-data Msg = HandShakeMsg ByteString ID
-         | KeepAliveMsg
-         | ChokeMsg
-         | UnChokeMsg
-         | InterestedMsg
-         | NotInterestedMsg
-         | HaveMsg Integer
-         | BitFieldMsg Integer
-         | RequestMsg Integer Integer Integer
-         | PieceMsg Integer Integer Integer
-         | CancelMsg Integer Integer Integer
-         | PortMsg Port
-         deriving (Show)
-
-genHandShakeMsg :: ByteString -> String -> ByteString
-genHandShakeMsg infoHash peer_id = concat [pstrlen, pstr, reserved, infoHash, peerID]
-  where pstrlen = singleton 19
-        pstr = pack "BitTorrent protocol"
-        reserved = replicate 8 '\0'
-        peerID = pack peer_id
-
-handShake :: Peer -> ByteString -> String -> IO ByteString
-handShake (Peer _ ip port) infoHash peerid = do
-  let hs = genHandShakeMsg infoHash peerid
-  handle <- connectTo ip (PortNumber (fromIntegral port))
-  hSetBuffering handle LineBuffering
-  hPut handle hs
-  rlenBS <- hGet handle 1
-  let rlen = fromIntegral $ (unpack rlenBS) !! 0
-  hGet handle rlen
-
--- sendMsg :: Peer -> Handle -> PeerMsg -> IO ()
--- recvMsg :: Peer -> Handle -> Msg
+import FuncTorrent.Metainfo (Info(..), Metainfo(..))
+import FuncTorrent.Utils (splitN, splitNum)
+import FuncTorrent.Fileops (createDummyFile, writeFileAtOffset)
+import FuncTorrent.PeerMsgs (Peer(..), PeerMsg(..), sendMsg, getMsg, genHandshakeMsg)
+
+data PState = PState { handle :: Handle
+                     , peer :: Peer
+                     , meChoking :: Bool
+                     , meInterested :: Bool
+                     , heChoking :: Bool
+                     , heInterested :: Bool}
+
+type PeerState = State PState
+
+data PieceDlState = Pending
+                  | InProgress
+                  | Have
+                  deriving (Show, Eq)
+
+-- todo - map with index to a new data structure (peers who have that piece amd state)
+data PieceData = PieceData { peers :: [Peer]        -- ^ list of peers who have this piece
+                           , dlstate :: PieceDlState  -- ^ state of the piece from download perspective.
+                           , hash  :: ByteString    -- ^ piece hash
+                           , len :: Integer }       -- ^ piece length
+
+-- which piece is with which peers
+type PieceMap = Map Integer PieceData
+
+
+-- Make the initial Piece map, with the assumption that no peer has the
+-- piece and that every piece is pending download.
+mkPieceMap :: Integer -> ByteString -> [Integer] -> PieceMap
+mkPieceMap numPieces pieceHash pLengths = fromList kvs
+  where kvs = [(i, PieceData { peers = []
+                             , dlstate = Pending
+                             , hash = h
+                             , len = pLen })
+              | (i, h, pLen) <- zip3 [0..numPieces] hashes pLengths]
+        hashes = splitN 20 pieceHash
+
+havePiece :: PieceMap -> Integer -> Bool
+havePiece pm index =
+  dlstate (pm ! index) == Have
+
+connectToPeer :: Peer -> IO Handle
+connectToPeer (Peer _ ip port) = do
+  h <- connectTo ip (PortNumber (fromIntegral port))
+  hSetBuffering h LineBuffering
+  return h
+
+doHandshake :: Handle -> Peer -> ByteString -> String -> IO ()
+doHandshake h peer infoHash peerid = do
+  let hs = genHandshakeMsg infoHash peerid
+  hPut h hs
+  putStrLn $ "--> handhake to peer: " ++ show peer
+  _ <- hGet h (length (unpack hs))
+  putStrLn $ "<-- handshake from peer: " ++ show peer
+  return ()
+
+bitfieldToList :: [Word8] -> [Integer]
+bitfieldToList bs = go bs 0
+  where go [] _ = []
+        go (b:bs') pos =
+          let setBits = [pos*8 + toInteger i | i <- [0..8], testBit b i]
+          in
+           setBits ++ go bs' (pos + 1)
+
+-- helper functions to manipulate PeerState
+toPeerState :: Handle
+            -> Peer
+            -> Bool  -- ^ meChoking
+            -> Bool  -- ^ meInterested
+            -> Bool  -- ^ heChoking
+            -> Bool  -- ^ heInterested
+            -> PState
+toPeerState h p meCh meIn heCh heIn =
+  PState { handle = h
+         , peer = p
+         , heChoking = heCh
+         , heInterested = heIn
+         , meChoking = meCh
+         , meInterested = meIn }
+
+-- simple algorithm to pick piece.
+-- pick the first piece from 0 that is not downloaded yet.
+pickPiece :: PieceMap -> Maybe Integer
+pickPiece m =
+  let pieceList = toList m
+      allPending = filter (\(_, v) -> dlstate v == Pending) pieceList
+  in
+   case allPending of
+    [] -> Nothing
+    ((i, _):_) -> Just i
+
+updatePieceAvailability :: PieceMap -> Peer -> [Integer] -> PieceMap
+updatePieceAvailability pieceStatus p pieceList =
+  mapWithKey (\k pd -> if k `elem` pieceList
+                       then (pd { peers = p : peers pd })
+                       else pd) pieceStatus
+
+handlePeerMsgs :: Peer -> Metainfo -> String -> IO ()
+handlePeerMsgs p m peerId = do
+  h <- connectToPeer p
+  doHandshake h p (infoHash m) peerId
+  let pstate = toPeerState h p False True False True
+      pieceHash = pieces (info m)
+      numPieces = (toInteger . (`quot` 20) . BC.length) pieceHash
+      pLen = pieceLength (info m)
+      fileLen = lengthInBytes (info m)
+      fileName = name (info m)
+      pieceStatus = mkPieceMap numPieces pieceHash (splitNum fileLen pLen)
+  createDummyFile fileName (fromIntegral fileLen)
+  (r, _) <- runStateT (msgLoop pieceStatus fileName) pstate
+  return ()
+
+msgLoop :: PieceMap -> FilePath -> StateT PState IO ()
+msgLoop pieceStatus file = do
+  h <- gets handle
+  st <- get
+  case st of
+    PState { meInterested = False, heChoking = True } -> do
+      liftIO $ sendMsg h InterestedMsg
+      gets peer >>= (\p -> liftIO $ putStrLn $ "--> InterestedMsg to peer: " ++ show p)
+      modify (\st -> st { meInterested = True })
+      msgLoop pieceStatus file
+    PState { meInterested = True, heChoking = False } -> do
+      case pickPiece pieceStatus of
+        Nothing -> liftIO $ putStrLn "Nothing to download"
+        Just workPiece -> do
+          let pLen = len (pieceStatus ! workPiece)
+          liftIO $ putStrLn $ "piece length = " ++ show pLen
+          pBS <- liftIO $ downloadPiece h workPiece pLen
+          if not $ verifyHash pBS (hash (pieceStatus ! workPiece))
+            then
+            liftIO $ putStrLn $ "Hash mismatch: " ++ show (hash (pieceStatus ! workPiece)) ++ " vs " ++ show (take 20 (SHA1.hash pBS))
+            else do
+            let fileOffset = if workPiece == 0 then 0 else workPiece * len (pieceStatus ! (workPiece - 1))
+            liftIO $ putStrLn $ "Write into file at offset: " ++ show fileOffset
+            liftIO $ writeFileAtOffset file fileOffset pBS
+            msgLoop (adjust (\pieceData -> pieceData { dlstate = Have }) workPiece pieceStatus) file
+    _ -> do
+      msg <- liftIO $ getMsg h
+      gets peer >>= (\p -> liftIO $ putStrLn $ "<-- " ++ show msg ++ "from peer: " ++ show p)
+      case msg of
+        KeepAliveMsg -> do
+          liftIO $ sendMsg h KeepAliveMsg
+          gets peer >>= (\p -> liftIO $ putStrLn $ "--> " ++ "KeepAliveMsg to peer: " ++ show p)
+          msgLoop pieceStatus file
+        BitFieldMsg bss -> do
+          p <- gets peer
+          let pieceList = bitfieldToList (unpack bss)
+              pieceStatus' = updatePieceAvailability pieceStatus p pieceList
+          liftIO $ putStrLn $ show (length pieceList) ++ " Pieces"
+          -- for each pieceIndex in pieceList, make an entry in the pieceStatus
+          -- map with pieceIndex as the key and modify the value to add the peer.
+          -- download each of the piece in order
+          msgLoop pieceStatus' file
+        UnChokeMsg -> do
+          modify (\st -> st {heChoking = False })
+          msgLoop pieceStatus file
+
+
+downloadPiece :: Handle -> Integer -> Integer -> IO ByteString
+downloadPiece h index pieceLength = do
+  let chunks = splitNum pieceLength 16384
+  liftM concat $ forM (zip [0..] chunks) (\(i, pLen) -> do
+                                             sendMsg h (RequestMsg index (i*pLen) pLen)
+                                             putStrLn $ "--> " ++ "RequestMsg for Piece "
+                                               ++ show index ++ ", part: " ++ show i ++ " of length: "
+                                               ++ show pLen
+                                             msg <- getMsg h
+                                             case msg of
+                                              PieceMsg index begin block -> do
+                                                putStrLn $ " <-- PieceMsg for Piece: "
+                                                  ++ show index
+                                                  ++ ", offset: "
+                                                  ++ show begin
+                                                return block
+                                              _ -> do
+                                                putStrLn "ignoring irrelevant msg"
+                                                return empty)
+
+verifyHash :: ByteString -> ByteString -> Bool
+verifyHash bs pieceHash =
+  take 20 (SHA1.hash bs) == pieceHash