summaryrefslogtreecommitdiff
path: root/src/Network/BitTorrent/Exchange.hs
blob: b0a94853bc7288f61a60fa5aaf4be5a434ad4604 (plain)
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
{- TODO turn awaitEvent and yieldEvent to sourcePeer and sinkPeer

      sourceSocket sock   $=
        conduitGet S.get  $=
          sourcePeer      $=
            p2p           $=
          sinkPeer        $=
        conduitPut S.put  $$
      sinkSocket sock

       measure performance
 -}

-- |
--   Copyright   :  (c) Sam T. 2013
--   License     :  MIT
--   Maintainer  :  pxqr.sta@gmail.com
--   Stability   :  experimental
--   Portability :  portable
--
--   This module provides P2P communication and aims to hide the
--   following stuff under the hood:
--
--     * TODO;
--
--     * /keep alives/ -- ;
--
--     * /choking mechanism/ -- is used ;
--
--     * /message broadcasting/ -- ;
--
--     * /message filtering/ -- due to network latency and concurrency
--     some arriving messages might not make sense in the current
--     session context;
--
--     * /scatter\/gather pieces/ -- ;
--
--     * /various P2P protocol extensions/ -- .
--
--   Finally we get a simple event-based communication model.
--
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE BangPatterns               #-}
module Network.BitTorrent.Exchange
       ( P2P
       , runP2P
       , spawnP2P

         -- * Query
       , getHaveCount
       , getWantCount
       , getPieceCount
       , peerOffer

         -- * Events
       , Event(..)
       , awaitEvent
       , yieldEvent
       , handleEvent

         -- * Exceptions
       , disconnect
       , protocolError

         -- * Block
       , Block(..), BlockIx(..)
       ) where

import Control.Applicative
import Control.Exception
import Control.Concurrent
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Resource

import Data.IORef
import Data.Conduit as C
import Data.Conduit.Cereal as S
import Data.Conduit.Serialization.Binary as B
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


{-----------------------------------------------------------------------
    Peer wire
-----------------------------------------------------------------------}

type PeerWire = ConduitM Message Message IO

runPeerWire :: Socket -> PeerWire () -> IO ()
runPeerWire sock p2p =
  sourceSocket sock     $=
    S.conduitGet S.get  $=
--    B.conduitDecode     $=
      p2p               $=
    S.conduitPut S.put  $$
--    B.conduitEncode     $$
  sinkSocket sock

awaitMessage :: P2P Message
awaitMessage = P2P $ ReaderT $ const $ {-# SCC awaitMessage #-} go
  where
    go = await >>= maybe (monadThrow PeerDisconnected) return
{-# INLINE awaitMessage #-}

yieldMessage :: Message -> P2P ()
yieldMessage msg =  P2P $ ReaderT $ const $ {-# SCC yieldMessage #-} C.yield msg
{-# INLINE yieldMessage #-}

flushPending :: P2P ()
flushPending = {-# SCC flushPending #-} do
  se <- ask
  q  <- liftIO (getPending se)
  -- TODO send vectored
  mapM_ yieldMessage q

{-----------------------------------------------------------------------
    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
             )

instance MonadState SessionState P2P where
  {-# SPECIALIZE instance MonadState SessionState P2P #-}
  get    = asks sessionState >>= liftIO . readIORef
  {-# INLINE get #-}
  put !s = asks sessionState >>= \ref -> liftIO $ writeIORef ref s
  {-# INLINE put #-}

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, except for debugging.
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

-- TODO unify this all using PeerConnection
{-
listenP2P :: SwarmSession -> P2P () -> IO PortNumber
listenP2P _ _ = undefined

chainP2P :: SwarmSession -> PeerConnection -> P2P () -> IO ()
-}
{-----------------------------------------------------------------------
    Exceptions
-----------------------------------------------------------------------}

-- | Terminate the current 'P2P' session.
disconnect :: P2P a
disconnect = monadThrow PeerDisconnected

-- TODO handle all protocol details here so we can hide this from
-- public interface |
protocolError ::  Doc -> P2P a
protocolError = monadThrow . ProtocolError

{-----------------------------------------------------------------------
    Helpers
-----------------------------------------------------------------------}

getClientBF :: P2P Bitfield
getClientBF = asks swarmSession >>= liftIO . getClientBitfield
{-# INLINE getClientBF #-}

-- | Count of client /have/ pieces.
getHaveCount :: P2P PieceCount
getHaveCount = haveCount <$> getClientBF
{-# INLINE getHaveCount #-}

-- | Count of client do not /have/ pieces.
getWantCount :: P2P PieceCount
getWantCount = totalCount <$> getClientBF
{-# INLINE getWantCount #-}

-- | Count of both /have/ and /want/ pieces.
getPieceCount :: P2P PieceCount
getPieceCount = asks findPieceCount
{-# INLINE getPieceCount #-}

-- for internal use only
emptyBF :: P2P Bitfield
emptyBF = liftM haveNone getPieceCount

fullBF ::  P2P Bitfield
fullBF = liftM haveAll getPieceCount

singletonBF :: PieceIx -> P2P Bitfield
singletonBF i = liftM (BF.singleton i) getPieceCount

adjustBF :: Bitfield -> P2P Bitfield
adjustBF bf = (`adjustSize` bf) `liftM` getPieceCount


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
-----------------------------------------------------------------------}


-- | The 'Event' occur when either client or a peer change their
-- state. 'Event' are similar to 'Message' but differ in. We could
-- both wait for an event or raise an event using the 'awaitEvent' and
-- 'yieldEvent' functions respectively.
--
--
--   'awaitEvent'\/'yieldEvent' properties:
--
--     * between any await or yield state of the (another)peer could not change.
--
data Event
    -- | Generalize 'Bitfield', 'Have', 'HaveAll', 'HaveNone',
    -- 'SuggestPiece', 'AllowedFast' messages.
  = Available Bitfield

    -- | Generalize 'Request' and 'Interested' messages.
  | Want      BlockIx

    -- | Generalize 'Piece' and 'Unchoke' messages.
  | Fragment  Block
    deriving Show

-- INVARIANT:
--
--   * Available Bitfield is never empty
--

-- | You could think of 'awaitEvent' as wait until something interesting occur.
--
--   The following table shows which events may occur:
--
--   > +----------+---------+
--   > | Leacher  |  Seeder |
--   > |----------+---------+
--   > | Available|         |
--   > | Want     |   Want  |
--   > | Fragment |         |
--   > +----------+---------+
--
--   The reason is that seeder is not interested in any piece, and
--   both available or fragment events doesn't make sense in this context.
--
--   Some properties:
--
--     forall (Fragment block). isPiece block == True
--
awaitEvent :: P2P Event
awaitEvent = {-# SCC 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
      bitfield %= have idx
      _ <- 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

-- TODO minimize number of peerOffer calls

-- | Raise an events which may occur
--
--   This table shows when a some specific events /makes sense/ to yield:
--
--   @
--   +----------+---------+
--   | Leacher  |  Seeder |
--   |----------+---------+
--   | Available|         |
--   | Want     |Fragment |
--   | Fragment |         |
--   +----------+---------+
--   @
--
--   Seeder should not yield:
--
--     * Available -- seeder could not store anything new.
--
--     * Want -- seeder alread have everything, no reason to want.
--
--   Hovewer, it's okay to not obey the rules -- if we are yield some
--   event which doesn't /makes sense/ in the current context then it
--   most likely will be ignored without any network IO.
--
yieldEvent  :: Event -> P2P ()
yieldEvent e = {-# SCC yieldEvent #-} go e
  where
    go (Available ixs) = asks swarmSession >>= liftIO . available ixs
    go (Want      bix) = do
      offer <- peerOffer
      if ixPiece bix `BF.member` offer
        then yieldMessage (Request bix)
        else return ()

    go (Fragment  blk) = do
      offer <- clientOffer
      if blkPiece blk `BF.member` offer
        then yieldMessage (Piece blk)
        else return ()


handleEvent :: (Event -> P2P Event) -> P2P ()
handleEvent action = awaitEvent >>= action >>= yieldEvent