summaryrefslogtreecommitdiff
path: root/src/Network/BitTorrent/Extension.hs
blob: e37f3afbbc6a34a6a4ed814838298c09e7297fa3 (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
-- |
--   Copyright   :  (c) Sam T. 2013
--   License     :  MIT
--   Maintainer  :  pxqr.sta@gmail.com
--   Stability   :  experimental
--   Portability :  portable
--
--   This module provides peer capabilities detection.
--
--   > See http://www.bittorrent.org/beps/bep_0004.html
--
module Network.BitTorrent.Extension
       ( Capabilities, ppCaps, defaultCaps, enabledCaps
       , Extension, ppExtension, encodeExts, decodeExts
       ) where

import Data.Bits
import Data.List
import Data.Word


type Capabilities = Word64

ppCaps :: Capabilities -> String
ppCaps = intercalate ", " . map ppExtension . decodeExts

defaultCaps :: Capabilities
defaultCaps = 0

enabledCaps :: Capabilities -- ^ of the client.
            -> Capabilities -- ^ of the peer.
            -> Capabilities -- ^ should be considered as enabled.
enabledCaps = (.&.)



data Extension = ExtDHT  -- ^ BEP 5
               | ExtFast -- ^ BEP 6
                 deriving (Show, Eq, Ord, Enum, Bounded)

ppExtension :: Extension -> String
ppExtension ExtDHT  = "DHT"
ppExtension ExtFast = "Fast Extension"

extensionMask :: Extension -> Word64
extensionMask ExtDHT  = 0x01
extensionMask ExtFast = 0x04


encodeExts :: [Extension] -> Capabilities
encodeExts = foldr (.&.) 0 . map extensionMask

decodeExts :: Capabilities -> [Extension]
decodeExts rb = filter (testMask rb . extensionMask) [minBound..maxBound]
  where
    testMask bits x = bits .&. x > 0