]> Sergey Matveev's repositories - btrtrc.git/blob - handshake.go
sortimports
[btrtrc.git] / handshake.go
1 package torrent
2
3 import (
4         "bytes"
5         "encoding/hex"
6         "fmt"
7         "io"
8         "net"
9         "time"
10
11         "github.com/anacrolix/missinggo"
12
13         "github.com/anacrolix/torrent/metainfo"
14         "github.com/anacrolix/torrent/mse"
15         pp "github.com/anacrolix/torrent/peer_protocol"
16 )
17
18 type ExtensionBit uint
19
20 const (
21         ExtensionBitDHT      = 0  // http://www.bittorrent.org/beps/bep_0005.html
22         ExtensionBitExtended = 20 // http://www.bittorrent.org/beps/bep_0010.html
23         ExtensionBitFast     = 2  // http://www.bittorrent.org/beps/bep_0006.html
24 )
25
26 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
27         var err error
28         for b := range bb {
29                 _, err = w.Write(b)
30                 if err != nil {
31                         break
32                 }
33         }
34         done <- err
35 }
36
37 type (
38         peerExtensionBytes [8]byte
39         peerID             [20]byte
40 )
41
42 func (pex peerExtensionBytes) SupportsExtended() bool {
43         return pex.GetBit(ExtensionBitExtended)
44 }
45
46 func (pex peerExtensionBytes) SupportsDHT() bool {
47         return pex.GetBit(ExtensionBitDHT)
48 }
49
50 func (pex peerExtensionBytes) SupportsFast() bool {
51         return pex.GetBit(ExtensionBitFast)
52 }
53
54 func (pex *peerExtensionBytes) SetBit(bit ExtensionBit) {
55         pex[7-bit/8] |= 1 << bit % 8
56 }
57
58 func (pex peerExtensionBytes) GetBit(bit ExtensionBit) bool {
59         return pex[7-bit/8]&(1<<(bit%8)) != 0
60 }
61
62 type handshakeResult struct {
63         peerExtensionBytes
64         peerID
65         metainfo.Hash
66 }
67
68 // ih is nil if we expect the peer to declare the InfoHash, such as when the
69 // peer initiated the connection. Returns ok if the handshake was successful,
70 // and err if there was an unexpected condition other than the peer simply
71 // abandoning the handshake.
72 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
73         // Bytes to be sent to the peer. Should never block the sender.
74         postCh := make(chan []byte, 4)
75         // A single error value sent when the writer completes.
76         writeDone := make(chan error, 1)
77         // Performs writes to the socket and ensures posts don't block.
78         go handshakeWriter(sock, postCh, writeDone)
79
80         defer func() {
81                 close(postCh) // Done writing.
82                 if !ok {
83                         return
84                 }
85                 if err != nil {
86                         panic(err)
87                 }
88                 // Wait until writes complete before returning from handshake.
89                 err = <-writeDone
90                 if err != nil {
91                         err = fmt.Errorf("error writing: %s", err)
92                 }
93         }()
94
95         post := func(bb []byte) {
96                 select {
97                 case postCh <- bb:
98                 default:
99                         panic("mustn't block while posting")
100                 }
101         }
102
103         post([]byte(pp.Protocol))
104         post(extensions[:])
105         if ih != nil { // We already know what we want.
106                 post(ih[:])
107                 post(peerID[:])
108         }
109         var b [68]byte
110         _, err = io.ReadFull(sock, b[:68])
111         if err != nil {
112                 err = nil
113                 return
114         }
115         if string(b[:20]) != pp.Protocol {
116                 return
117         }
118         missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
119         missinggo.CopyExact(&res.Hash, b[28:48])
120         missinggo.CopyExact(&res.peerID, b[48:68])
121         peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
122
123         // TODO: Maybe we can just drop peers here if we're not interested. This
124         // could prevent them trying to reconnect, falsely believing there was
125         // just a problem.
126         if ih == nil { // We were waiting for the peer to tell us what they wanted.
127                 post(res.Hash[:])
128                 post(peerID[:])
129         }
130
131         ok = true
132         return
133 }
134
135 // Wraps a raw connection and provides the interface we want for using the
136 // connection in the message loop.
137 type deadlineReader struct {
138         nc net.Conn
139         r  io.Reader
140 }
141
142 func (r deadlineReader) Read(b []byte) (int, error) {
143         // Keep-alives should be received every 2 mins. Give a bit of gracetime.
144         err := r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
145         if err != nil {
146                 return 0, fmt.Errorf("error setting read deadline: %s", err)
147         }
148         return r.r.Read(b)
149 }
150
151 func handleEncryption(
152         rw io.ReadWriter,
153         skeys mse.SecretKeyIter,
154         policy EncryptionPolicy,
155 ) (
156         ret io.ReadWriter,
157         headerEncrypted bool,
158         cryptoMethod uint32,
159         err error,
160 ) {
161         if !policy.ForceEncryption {
162                 var protocol [len(pp.Protocol)]byte
163                 _, err = io.ReadFull(rw, protocol[:])
164                 if err != nil {
165                         return
166                 }
167                 rw = struct {
168                         io.Reader
169                         io.Writer
170                 }{
171                         io.MultiReader(bytes.NewReader(protocol[:]), rw),
172                         rw,
173                 }
174                 if string(protocol[:]) == pp.Protocol {
175                         ret = rw
176                         return
177                 }
178         }
179         headerEncrypted = true
180         ret, err = mse.ReceiveHandshake(rw, skeys, func(provides uint32) uint32 {
181                 cryptoMethod = func() uint32 {
182                         switch {
183                         case policy.ForceEncryption:
184                                 return mse.CryptoMethodRC4
185                         case policy.DisableEncryption:
186                                 return mse.CryptoMethodPlaintext
187                         case policy.PreferNoEncryption && provides&mse.CryptoMethodPlaintext != 0:
188                                 return mse.CryptoMethodPlaintext
189                         default:
190                                 return mse.DefaultCryptoSelector(provides)
191                         }
192                 }()
193                 return cryptoMethod
194         })
195         return
196 }