summaryrefslogtreecommitdiff
path: root/src/Network/Torrent/Handshake.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Network/Torrent/Handshake.hs')
-rw-r--r--src/Network/Torrent/Handshake.hs47
1 files changed, 38 insertions, 9 deletions
diff --git a/src/Network/Torrent/Handshake.hs b/src/Network/Torrent/Handshake.hs
index d48d04e6..7643b2e9 100644
--- a/src/Network/Torrent/Handshake.hs
+++ b/src/Network/Torrent/Handshake.hs
@@ -1,25 +1,54 @@
1{-# LANGUAGE OverloadedStrings #-} 1{-# LANGUAGE OverloadedStrings #-}
2module Network.Torrent.Handshake 2module Network.Torrent.Handshake
3 ( Handshake 3 ( Handshake
4 , defaultProtocol, defaultReserved, defaultHandshake
4 ) where 5 ) where
5 6
7import Control.Applicative
6import Data.Word 8import Data.Word
7import Data.ByteString (ByteString) 9import Data.ByteString (ByteString)
8import qualified Data.ByteString as B 10import qualified Data.ByteString as B
11import Data.Serialize
9 12
13import Network.Torrent.PeerID
14
15-- | In order to establish the connection between peers we should send 'Handshake'
16-- message. The 'Handshake' is a required message and must be the first message
17-- transmitted by the peer to the another peer.
10data Handshake = Handshake { 18data Handshake = Handshake {
11 hsProtocol :: ByteString 19 hsProtocol :: ByteString -- ^ Identifier of the protocol.
12 , hsReserved :: Word64 20 , hsReserved :: Word64 -- ^ Reserved bytes, rarely used.
13 , hsInfoHash :: ByteString 21 , hsInfoHash :: ByteString -- ^ Hash from the metainfo file.
14 , hsPeerID :: ByteString 22 -- This /should be/ same hash that is transmitted in tracker requests.
23 , hsPeerID :: PeerID -- ^ Peer id of the initiator.
24 -- This is /usually the same peer id that is transmitted in tracker requests.
15 } deriving (Show, Eq) 25 } deriving (Show, Eq)
16 26
27instance Serialize Handshake where
28 put hs = do
29 putWord8 (49 + fromIntegral (B.length (hsProtocol hs)))
30 putByteString (hsProtocol hs)
31 putWord64be (hsReserved hs)
32 putByteString (hsInfoHash hs)
33 put (hsPeerID hs)
34
35 get = do
36 len <- getWord8
37 Handshake <$> getBytes (fromIntegral len)
38 <*> getWord64be
39 <*> getBytes 20
40 <*> get
41
42-- | Default protocol string "BitTorrent protocol" as is.
17defaultProtocol :: ByteString 43defaultProtocol :: ByteString
18defaultProtocol = "BitTorrent protocol" 44defaultProtocol = "BitTorrent protocol"
19 45
46-- | Default reserved word is 0.
47defaultReserved :: Word64
48defaultReserved = 0
20 49
21fromByteString :: ByteString -> Handshake 50-- | Length of info hash and peer id is unchecked, so it /should/ be equal 20.
22fromByteString = undefined 51defaultHandshake :: ByteString -- ^ Info hash string.
23 52 -> PeerID
24toByteString :: Handshake -> ByteString 53 -> Handshake
25toByteString = undefined \ No newline at end of file 54defaultHandshake hash pid = Handshake defaultProtocol defaultReserved hash pid \ No newline at end of file