1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Network.BitTorrent.Exchange.Session
( Session
, LogFun
, newSession
, closeSession
, Network.BitTorrent.Exchange.Session.insert
) where
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Control.Lens
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.State
import Data.ByteString as BS
import Data.ByteString.Lazy as BL
import Data.Conduit
import Data.Function
import Data.IORef
import Data.List as L
import Data.Maybe
import Data.Map as M
import Data.Monoid
import Data.Ord
import Data.Set as S
import Data.Text as T
import Data.Typeable
import Text.PrettyPrint hiding ((<>))
import Text.PrettyPrint.Class
import System.Log.FastLogger (LogStr, ToLogStr (..))
import Data.Torrent (InfoDict (..))
import Data.Torrent.Bitfield as BF
import Data.Torrent.InfoHash
import Data.Torrent.Piece (pieceData, piPieceLength)
import qualified Data.Torrent.Piece as Torrent (Piece (Piece))
import Network.BitTorrent.Core
import Network.BitTorrent.Exchange.Assembler
import Network.BitTorrent.Exchange.Block as Block
import Network.BitTorrent.Exchange.Message
import Network.BitTorrent.Exchange.Session.Status as SS
import Network.BitTorrent.Exchange.Status
import Network.BitTorrent.Exchange.Wire
import System.Torrent.Storage
{-----------------------------------------------------------------------
-- Exceptions
-----------------------------------------------------------------------}
data ExchangeError
= InvalidRequest BlockIx StorageFailure
| CorruptedPiece PieceIx
deriving (Show, Typeable)
instance Exception ExchangeError
packException :: Exception e => (e -> ExchangeError) -> IO a -> IO a
packException f m = try m >>= either (throwIO . f) return
{-----------------------------------------------------------------------
-- Session
-----------------------------------------------------------------------}
data ConnectionEntry = ConnectionEntry
{ initiatedBy :: !ChannelSide
, connection :: !(Connection Session)
}
data Session = Session
{ tpeerId :: PeerId
, infohash :: InfoHash
, storage :: Storage
, status :: MVar SessionStatus
, unchoked :: [PeerAddr IP]
, connections :: MVar (Map (PeerAddr IP) ConnectionEntry)
, broadcast :: Chan Message
, logger :: LogFun
}
-- | Logger function.
type LogFun = Loc -> LogSource -> LogLevel -> LogStr -> IO ()
newSession :: LogFun
-> PeerAddr (Maybe IP) -- ^ /external/ address of this peer;
-> FilePath -- ^ root directory for content files;
-> InfoDict -- ^ torrent info dictionary;
-> IO Session -- ^
newSession logFun addr rootPath dict = do
connVar <- newMVar M.empty
store <- openInfoDict ReadWriteEx rootPath dict
statusVar <- newMVar $ sessionStatus (BF.haveNone (totalPieces store))
(piPieceLength (idPieceInfo dict))
chan <- newChan
return Session
{ tpeerId = fromMaybe (error "newSession: impossible") (peerId addr)
, infohash = idInfoHash dict
, status = statusVar
, storage = store
, unchoked = []
, connections = connVar
, broadcast = chan
, logger = logFun
}
closeSession :: Session -> IO ()
closeSession = undefined
instance MonadLogger (Connected Session) where
monadLoggerLog loc src lvl msg = do
conn <- ask
ses <- asks connSession
addr <- asks connRemoteAddr
let addrSrc = src <> " @ " <> T.pack (render (pretty addr))
liftIO $ logger ses loc addrSrc lvl (toLogStr msg)
logMessage :: Message -> Wire Session ()
logMessage msg = logDebugN $ T.pack (render (pretty msg))
logEvent :: Text -> Wire Session ()
logEvent = logInfoN
{-----------------------------------------------------------------------
-- Connections
-----------------------------------------------------------------------}
-- TODO unmap storage on zero connections
insert :: PeerAddr IP
-> {- Maybe Socket
-> -} Session -> IO ()
insert addr ses @ Session {..} = do
forkIO $ do
action `finally` runStatusUpdates status (resetPending addr)
return ()
where
action = do
let caps = def
let ecaps = def
let hs = Handshake def caps infohash tpeerId
chan <- dupChan broadcast
connectWire ses hs addr ecaps chan $ do
conn <- ask
-- liftIO $ modifyMVar_ connections $ pure . M.insert addr conn
lift $ resizeBitfield (totalPieces storage)
logEvent "Connection established"
exchange
-- liftIO $ modifyMVar_ connections $ pure . M.delete addr
delete :: PeerAddr IP -> Session -> IO ()
delete = undefined
deleteAll :: Session -> IO ()
deleteAll = undefined
{-----------------------------------------------------------------------
-- Helpers
-----------------------------------------------------------------------}
withStatusUpdates :: StatusUpdates a -> Wire Session a
withStatusUpdates m = do
Session {..} <- asks connSession
liftIO $ runStatusUpdates status m
getThisBitfield :: Wire Session Bitfield
getThisBitfield = do
ses <- asks connSession
liftIO $ SS.getBitfield (status ses)
readBlock :: BlockIx -> Storage -> IO (Block BL.ByteString)
readBlock bix @ BlockIx {..} s = do
p <- packException (InvalidRequest bix) $ do readPiece ixPiece s
let chunk = BL.take (fromIntegral ixLength) $
BL.drop (fromIntegral ixOffset) (pieceData p)
if BL.length chunk == fromIntegral ixLength
then return $ Block ixPiece ixOffset chunk
else throwIO $ InvalidRequest bix (InvalidSize ixLength)
sendBroadcast :: PeerMessage msg => msg -> Wire Session ()
sendBroadcast msg = do
Session {..} <- asks connSession
ecaps <- use connExtCaps
liftIO $ writeChan broadcast (envelop ecaps msg)
{-----------------------------------------------------------------------
-- Triggers
-----------------------------------------------------------------------}
fillRequestQueue :: Wire Session ()
fillRequestQueue = do
maxN <- lift getMaxQueueLength
rbf <- use connBitfield
addr <- asks connRemoteAddr
blks <- withStatusUpdates $ do
n <- getRequestQueueLength addr
scheduleBlocks addr rbf (maxN - n)
mapM_ (sendMessage . Request) blks
tryFillRequestQueue :: Wire Session ()
tryFillRequestQueue = do
allowed <- canDownload <$> use connStatus
when allowed $ do
fillRequestQueue
interesting :: Wire Session ()
interesting = do
addr <- asks connRemoteAddr
logMessage (Status (Interested True))
sendMessage (Interested True)
logMessage (Status (Choking False))
sendMessage (Choking False)
tryFillRequestQueue
{-----------------------------------------------------------------------
-- Incoming message handling
-----------------------------------------------------------------------}
handleStatus :: StatusUpdate -> Wire Session ()
handleStatus s = do
connStatus %= over remoteStatus (updateStatus s)
case s of
Interested _ -> return ()
Choking True -> do
addr <- asks connRemoteAddr
withStatusUpdates (resetPending addr)
Choking False -> tryFillRequestQueue
handleAvailable :: Available -> Wire Session ()
handleAvailable msg = do
connBitfield %= case msg of
Have ix -> BF.insert ix
Bitfield bf -> const bf
thisBf <- getThisBitfield
case msg of
Have ix
| ix `BF.member` thisBf -> return ()
| otherwise -> interesting
Bitfield bf
| bf `BF.isSubsetOf` thisBf -> return ()
| otherwise -> interesting
handleTransfer :: Transfer -> Wire Session ()
handleTransfer (Request bix) = do
Session {..} <- asks connSession
bitfield <- getThisBitfield
upload <- canUpload <$> use connStatus
when (upload && ixPiece bix `BF.member` bitfield) $ do
blk <- liftIO $ readBlock bix storage
sendMessage (Piece blk)
handleTransfer (Piece blk) = do
Session {..} <- asks connSession
isSuccess <- withStatusUpdates (pushBlock blk storage)
case isSuccess of
Nothing -> liftIO $ throwIO $ userError "block is not requested"
Just isCompleted -> do
when isCompleted $ do
sendBroadcast (Have (blkPiece blk))
-- maybe send not interested
tryFillRequestQueue
handleTransfer (Cancel bix) = filterQueue (not . (transferResponse bix))
where
transferResponse bix (Transfer (Piece blk)) = blockIx blk == bix
transferResponse _ _ = False
{-----------------------------------------------------------------------
-- Event loop
-----------------------------------------------------------------------}
handleMessage :: Message -> Wire Session ()
handleMessage KeepAlive = return ()
handleMessage (Status s) = handleStatus s
handleMessage (Available msg) = handleAvailable msg
handleMessage (Transfer msg) = handleTransfer msg
handleMessage (Port n) = undefined
handleMessage (Fast _) = undefined
handleMessage (Extended _) = undefined
exchange :: Wire Session ()
exchange = do
bf <- getThisBitfield
sendMessage (Bitfield bf)
awaitForever $ \ msg -> do
logMessage msg
handleMessage msg
data Event = NewMessage (PeerAddr IP) Message
| Timeout -- for scheduling
type Exchange a = Wire Session a
awaitEvent :: Exchange Event
awaitEvent = undefined
yieldEvent :: Exchange Event
yieldEvent = undefined
|