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 #-}
22 module FuncTorrent.Server where
24 import Control.Concurrent (forkIO)
25 import Control.Monad (forever)
26 import Network (withSocketsDo, listenOn, accept, Socket, PortID ( PortNumber ))
27 import System.IO (hSetBuffering, BufferMode ( NoBuffering ))
29 import FuncTorrent.Metainfo (Metainfo)
30 import FuncTorrent.Peer (handlePeerMsgs)
31 import FuncTorrent.PeerMsgs (Peer(..))
32 import FuncTorrent.PieceManager (PieceMap)
33 import qualified FuncTorrent.FileSystem as FS (MsgChannel)
35 -- server is listening on any port from 6881 - 6889
36 -- return the port number used
37 start :: IO (Socket, PortID)
38 start = withSocketsDo $ do
39 let portnums = [6881 .. 6889]
40 sock <- listenOn $ PortNumber $ fromIntegral (head portnums)
41 return (sock, PortNumber $ head portnums)
43 run :: Socket -> String -> Metainfo -> PieceMap -> FS.MsgChannel -> IO ()
44 run listenSock peerid m pieceMap c = forever $ do
45 (handle, ip, port) <- accept listenSock
46 let peer = Peer ip (fromIntegral port)
47 hSetBuffering handle NoBuffering
48 forkIO $ handlePeerMsgs peer peerid m pieceMap False c