]> Sergey Matveev's repositories - btrtrc.git/blob - peer_protocol/handshake.go
PEX: add connection tracking
[btrtrc.git] / peer_protocol / handshake.go
1 package peer_protocol
2
3 import (
4         "encoding/hex"
5         "fmt"
6         "io"
7
8         "golang.org/x/xerrors"
9
10         "github.com/anacrolix/missinggo"
11
12         "github.com/anacrolix/torrent/metainfo"
13 )
14
15 type ExtensionBit uint
16
17 const (
18         ExtensionBitDHT      = 0  // http://www.bittorrent.org/beps/bep_0005.html
19         ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
20         ExtensionBitFast     = 2  // http://www.bittorrent.org/beps/bep_0006.html
21 )
22
23 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
24         var err error
25         for b := range bb {
26                 _, err = w.Write(b)
27                 if err != nil {
28                         break
29                 }
30         }
31         done <- err
32 }
33
34 type (
35         PeerExtensionBits [8]byte
36 )
37
38 func (me PeerExtensionBits) String() string {
39         return hex.EncodeToString(me[:])
40 }
41
42 func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
43         for _, b := range bits {
44                 ret.SetBit(b)
45         }
46         return
47 }
48
49 func (pex PeerExtensionBits) SupportsExtended() bool {
50         return pex.GetBit(ExtensionBitExtended)
51 }
52
53 func (pex PeerExtensionBits) SupportsDHT() bool {
54         return pex.GetBit(ExtensionBitDHT)
55 }
56
57 func (pex PeerExtensionBits) SupportsFast() bool {
58         return pex.GetBit(ExtensionBitFast)
59 }
60
61 func (pex *PeerExtensionBits) SetBit(bit ExtensionBit) {
62         pex[7-bit/8] |= 1 << (bit % 8)
63 }
64
65 func (pex PeerExtensionBits) GetBit(bit ExtensionBit) bool {
66         return pex[7-bit/8]&(1<<(bit%8)) != 0
67 }
68
69 type HandshakeResult struct {
70         PeerExtensionBits
71         PeerID [20]byte
72         metainfo.Hash
73 }
74
75 // ih is nil if we expect the peer to declare the InfoHash, such as when the peer initiated the
76 // connection. Returns ok if the Handshake was successful, and err if there was an unexpected
77 // condition other than the peer simply abandoning the Handshake.
78 func Handshake(
79         sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits,
80 ) (
81         res HandshakeResult, err error,
82 ) {
83         // Bytes to be sent to the peer. Should never block the sender.
84         postCh := make(chan []byte, 4)
85         // A single error value sent when the writer completes.
86         writeDone := make(chan error, 1)
87         // Performs writes to the socket and ensures posts don't block.
88         go handshakeWriter(sock, postCh, writeDone)
89
90         defer func() {
91                 close(postCh) // Done writing.
92                 if err != nil {
93                         return
94                 }
95                 // Wait until writes complete before returning from handshake.
96                 err = <-writeDone
97                 if err != nil {
98                         err = fmt.Errorf("error writing: %s", err)
99                 }
100         }()
101
102         post := func(bb []byte) {
103                 select {
104                 case postCh <- bb:
105                 default:
106                         panic("mustn't block while posting")
107                 }
108         }
109
110         post([]byte(Protocol))
111         post(extensions[:])
112         if ih != nil { // We already know what we want.
113                 post(ih[:])
114                 post(peerID[:])
115         }
116         var b [68]byte
117         _, err = io.ReadFull(sock, b[:68])
118         if err != nil {
119                 err = xerrors.Errorf("while reading: %w", err)
120                 return
121         }
122         if string(b[:20]) != Protocol {
123                 err = xerrors.Errorf("unexpected protocol string")
124                 return
125         }
126         missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
127         missinggo.CopyExact(&res.Hash, b[28:48])
128         missinggo.CopyExact(&res.PeerID, b[48:68])
129         // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
130
131         // TODO: Maybe we can just drop peers here if we're not interested. This
132         // could prevent them trying to reconnect, falsely believing there was
133         // just a problem.
134         if ih == nil { // We were waiting for the peer to tell us what they wanted.
135                 post(res.Hash[:])
136                 post(peerID[:])
137         }
138
139         return
140 }