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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
-- |
-- Copyright : (c) Sam T. 2013
-- License : MIT
-- Maintainer : pxqr.sta@gmail.com
-- Stability : experimental
-- Portability : portable
--
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
module Network.BitTorrent.Exchange
( -- * Block
Block(..), BlockIx(..)
-- * Event
, Event(..)
, P2P
, runP2P, spawnP2P
, awaitEvent, yieldEvent
) where
import Control.Applicative
import Control.Exception
import Control.Concurrent
import Control.Lens
import Control.Monad.Fork.Class
import Control.Monad.Reader
import Control.Monad.Trans.Resource
import Data.Conduit as C
import Data.Conduit.Cereal
import Data.Conduit.Network
import Data.Serialize as S
import Text.PrettyPrint as PP hiding (($$))
import Network
import Network.BitTorrent.Internal
import Network.BitTorrent.Extension
import Network.BitTorrent.Peer
import Network.BitTorrent.Exchange.Protocol
import Data.Bitfield as BF
data Event = Available Bitfield
| Want BlockIx
| Fragment Block
deriving Show
{-----------------------------------------------------------------------
Peer wire
-----------------------------------------------------------------------}
type PeerWire = ConduitM Message Message IO
runPeerWire :: Socket -> PeerWire () -> IO ()
runPeerWire sock p2p =
sourceSocket sock $=
conduitGet S.get $=
p2p $=
conduitPut S.put $$
sinkSocket sock
awaitMessage :: P2P Message
awaitMessage = P2P (ReaderT (const go))
where
go = await >>= maybe disconnect return
yieldMessage :: Message -> P2P ()
yieldMessage msg = P2P $ ReaderT $ \se -> C.yield msg
{-----------------------------------------------------------------------
P2P monad
-----------------------------------------------------------------------}
-- |
-- Exceptions:
--
-- * SessionException: is visible only within one peer
-- session. Use this exception to terminate P2P session, but not
-- the swarm session.
--
newtype P2P a = P2P {
unP2P :: ReaderT PeerSession PeerWire a
} deriving ( Functor, Applicative, Monad
, MonadIO, MonadThrow, MonadActive
, MonadReader PeerSession
)
-- TODO instance for MonadFork
runSession :: SwarmSession -> PeerAddr -> P2P () -> IO ()
runSession se addr p2p =
handle isIOException $
withPeerSession se addr $ \(sock, pses) -> do
runPeerWire sock (runReaderT (unP2P p2p) pses)
where
isIOException :: IOException -> IO ()
isIOException _ = return ()
-- | Run P2P session in the current thread. Normally you don't need this
-- function in client application.
runP2P :: SwarmSession -> PeerAddr -> P2P () -> IO ()
runP2P se addr p2p = waitVacancy se $ runSession se addr p2p
-- | Run P2P session in forked thread. Might be used in listener or
-- some other loop. Note that this function may block while waiting
-- for a vacant place: use forkIO and runP2P instead.
spawnP2P :: SwarmSession -> PeerAddr -> P2P () -> IO ThreadId
spawnP2P se addr p2p = do
enterSwarm se
forkIO $ do
runSession se addr p2p `finally` leaveSwarm se
{-----------------------------------------------------------------------
Exceptions
-----------------------------------------------------------------------}
disconnect :: MonadThrow m => m a
disconnect = monadThrow PeerDisconnected
protocolError :: MonadThrow m => Doc -> m a
protocolError = monadThrow . ProtocolError
{-----------------------------------------------------------------------
Helpers
-----------------------------------------------------------------------}
peerWant :: P2P Bitfield
peerWant = BF.difference <$> getClientBF <*> use bitfield
clientWant :: P2P Bitfield
clientWant = BF.difference <$> use bitfield <*> getClientBF
peerOffer :: P2P Bitfield
peerOffer = do
sessionStatus <- use status
if canDownload sessionStatus then clientWant else emptyBF
clientOffer :: P2P Bitfield
clientOffer = do
sessionStatus <- use status
if canUpload sessionStatus then peerWant else emptyBF
revise :: P2P Bitfield
revise = do
want <- clientWant
let peerInteresting = not (BF.null want)
clientInterested <- use (status.clientStatus.interested)
when (clientInterested /= peerInteresting) $ do
yieldMessage $ if peerInteresting then Interested else NotInterested
status.clientStatus.interested .= peerInteresting
return want
requireExtension :: Extension -> P2P ()
requireExtension required = do
enabled <- asks enabledExtensions
unless (required `elem` enabled) $
protocolError $ ppExtension required <+> "not enabled"
-- haveMessage bf = do
-- cbf <- undefined -- liftIO $ readIORef $ clientBitfield swarmSession
-- if undefined -- ix `member` bf
-- then nextEvent se
-- else undefined -- return $ Available diff
{-----------------------------------------------------------------------
Exchange
-----------------------------------------------------------------------}
-- |
-- +----------+---------+
-- | Leacher | Seeder |
-- |----------+---------+
-- | Available| |
-- | Want | Want |
-- | Fragment | |
-- +----------+---------+
--
--
-- properties:
--
-- forall (Fragment block). isPiece block == True
--
awaitEvent :: P2P Event
awaitEvent = awaitMessage >>= go
where
go KeepAlive = awaitEvent
go Choke = do
status.peerStatus.choking .= True
awaitEvent
go Unchoke = do
status.peerStatus.choking .= False
offer <- peerOffer
if BF.null offer
then awaitEvent
else return (Available offer)
go Interested = do
status.peerStatus.interested .= True
awaitEvent
go NotInterested = do
status.peerStatus.interested .= False
awaitEvent
go (Have idx) = do
new <- singletonBF idx
bitfield %= BF.union new
_ <- revise
offer <- peerOffer
if not (BF.null offer)
then return (Available offer)
else awaitEvent
go (Bitfield bf) = do
new <- adjustBF bf
bitfield .= new
_ <- revise
offer <- peerOffer
if not (BF.null offer)
then return (Available offer)
else awaitEvent
go (Request bix) = do
bf <- clientOffer
if ixPiece bix `BF.member` bf
then return (Want bix)
else do
-- check if extension is enabled
-- yieldMessage (RejectRequest bix)
awaitEvent
go (Piece blk) = do
-- this protect us from malicious peers and duplication
wanted <- clientWant
if blkPiece blk `BF.member` wanted
then return (Fragment blk)
else awaitEvent
go (Cancel _) = do
error "cancel message not implemented"
go (Port _) = do
requireExtension ExtDHT
error "port message not implemented"
go HaveAll = do
requireExtension ExtFast
bitfield <~ fullBF
_ <- revise
awaitEvent
go HaveNone = do
requireExtension ExtFast
bitfield <~ emptyBF
_ <- revise
awaitEvent
go (SuggestPiece idx) = do
requireExtension ExtFast
bf <- use bitfield
if idx `BF.notMember` bf
then Available <$> singletonBF idx
else awaitEvent
go (RejectRequest _) = do
requireExtension ExtFast
awaitEvent
go (AllowedFast _) = do
requireExtension ExtFast
awaitEvent
-- |
-- @
-- +----------+---------+
-- | Leacher | Seeder |
-- |----------+---------+
-- | Available| |
-- | Want |Fragment |
-- | Fragment | |
-- +----------+---------+
-- @
--
yieldEvent :: Event -> P2P ()
yieldEvent (Available _ ) = undefined
yieldEvent (Want bix) = do
offer <- peerOffer
if ixPiece bix `BF.member` offer
then yieldMessage (Request bix)
else return ()
yieldEvent (Fragment blk) = do
offer <- clientOffer
if blkPiece blk `BF.member` offer
then yieldMessage (Piece blk)
else return ()
--flushBroadcast :: P2P ()
--flushBroadcast = nextBroadcast >>= maybe (return ()) go
-- where
-- go = undefined
checkPiece :: PieceLIx -> {-ByteString -> -} P2P Bool
checkPiece = undefined
|