2 - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
4 - This file is part of FuncTorrent.
6 - FuncTorrent is free software; you can redistribute it and/or modify
7 - it under the terms of the GNU General Public License as published by
8 - the Free Software Foundation; either version 3 of the License, or
9 - (at your option) any later version.
11 - FuncTorrent is distributed in the hope that it will be useful,
12 - but WITHOUT ANY WARRANTY; without even the implied warranty of
13 - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 - GNU General Public License for more details.
16 - You should have received a copy of the GNU General Public License
17 - along with FuncTorrent; if not, see <http://www.gnu.org/licenses/>
20 {-# LANGUAGE OverloadedStrings #-}
21 module FuncTorrent.Tracker
27 import Control.Concurrent(forkIO)
28 import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
29 import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)
30 import Control.Monad.State (StateT, liftIO, get, runStateT)
31 import Control.Monad (forever)
32 import Data.ByteString.Char8 (ByteString)
33 import Data.List (isPrefixOf)
34 import Network (PortNumber)
36 import qualified FuncTorrent.Tracker.Http as HT (trackerLoop)
37 import qualified FuncTorrent.Tracker.Udp as UT (trackerLoop)
38 import FuncTorrent.Tracker.Types (TState(..), TrackerEventState(..), TrackerProtocol(..), TrackerMsg(..))
39 import qualified FuncTorrent.FileSystem as FS (MsgChannel)
40 import FuncTorrent.PeerMsgs (Peer)
42 type MsgChannel = Chan TrackerMsg
44 newTracker :: IO MsgChannel
47 runTracker :: MsgChannel -> FS.MsgChannel -> ByteString -> PortNumber
48 -> String -> [String] -> Integer -> IO ()
49 runTracker msgChannel fsChan infohash port peerId announceList sz = do
50 let fn = getTrackerLoopFn turl
52 _ <- forkIO $ fn turl port peerId infohash fsChan (initialTState ps)
53 _ <- runStateT (msgHandler msgChannel) (initialTState ps)
55 where getTrackerLoopFn turl' =
56 case getTrackerType turl' of
57 Http -> HT.trackerLoop
59 _ -> error "Tracker Protocol unimplemented"
60 initialTState ps' = TState { currentState = None
61 , connectedPeers = ps'
63 turl = head announceList
65 getTrackerType :: String -> TrackerProtocol
66 getTrackerType url | "http://" `isPrefixOf` url = Http
67 | "udp://" `isPrefixOf` url = Udp
68 | otherwise = UnknownProtocol
71 msgHandler :: MsgChannel -> StateT TState IO ()
72 msgHandler c = forever $ do
74 peers <- liftIO $ readMVar (connectedPeers st)
76 liftIO $ sendResponse msg peers
79 sendResponse msg peers =
81 GetConnectedPeersMsg var ->
84 putStrLn "Unhandled Tracker Msg"
86 getConnectedPeers :: MsgChannel -> IO [Peer]
87 getConnectedPeers c = do
89 writeChan c (GetConnectedPeersMsg v)