]> Sergey Matveev's repositories - btrtrc.git/blob - handshake.go
Add mse.CryptoMethod type
[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 )
40
41 func (me peerExtensionBytes) String() string {
42         return hex.EncodeToString(me[:])
43 }
44
45 func newPeerExtensionBytes(bits ...ExtensionBit) (ret peerExtensionBytes) {
46         for _, b := range bits {
47                 ret.SetBit(b)
48         }
49         return
50 }
51
52 func (pex peerExtensionBytes) SupportsExtended() bool {
53         return pex.GetBit(ExtensionBitExtended)
54 }
55
56 func (pex peerExtensionBytes) SupportsDHT() bool {
57         return pex.GetBit(ExtensionBitDHT)
58 }
59
60 func (pex peerExtensionBytes) SupportsFast() bool {
61         return pex.GetBit(ExtensionBitFast)
62 }
63
64 func (pex *peerExtensionBytes) SetBit(bit ExtensionBit) {
65         pex[7-bit/8] |= 1 << (bit % 8)
66 }
67
68 func (pex peerExtensionBytes) GetBit(bit ExtensionBit) bool {
69         return pex[7-bit/8]&(1<<(bit%8)) != 0
70 }
71
72 type handshakeResult struct {
73         peerExtensionBytes
74         PeerID
75         metainfo.Hash
76 }
77
78 // ih is nil if we expect the peer to declare the InfoHash, such as when the
79 // peer initiated the connection. Returns ok if the handshake was successful,
80 // and err if there was an unexpected condition other than the peer simply
81 // abandoning the handshake.
82 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
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 !ok {
93                         return
94                 }
95                 if err != nil {
96                         panic(err)
97                 }
98                 // Wait until writes complete before returning from handshake.
99                 err = <-writeDone
100                 if err != nil {
101                         err = fmt.Errorf("error writing: %s", err)
102                 }
103         }()
104
105         post := func(bb []byte) {
106                 select {
107                 case postCh <- bb:
108                 default:
109                         panic("mustn't block while posting")
110                 }
111         }
112
113         post([]byte(pp.Protocol))
114         post(extensions[:])
115         if ih != nil { // We already know what we want.
116                 post(ih[:])
117                 post(peerID[:])
118         }
119         var b [68]byte
120         _, err = io.ReadFull(sock, b[:68])
121         if err != nil {
122                 err = nil
123                 return
124         }
125         if string(b[:20]) != pp.Protocol {
126                 return
127         }
128         missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
129         missinggo.CopyExact(&res.Hash, b[28:48])
130         missinggo.CopyExact(&res.PeerID, b[48:68])
131         peerExtensions.Add(res.peerExtensionBytes.String(), 1)
132
133         // TODO: Maybe we can just drop peers here if we're not interested. This
134         // could prevent them trying to reconnect, falsely believing there was
135         // just a problem.
136         if ih == nil { // We were waiting for the peer to tell us what they wanted.
137                 post(res.Hash[:])
138                 post(peerID[:])
139         }
140
141         ok = true
142         return
143 }
144
145 // Wraps a raw connection and provides the interface we want for using the
146 // connection in the message loop.
147 type deadlineReader struct {
148         nc net.Conn
149         r  io.Reader
150 }
151
152 func (r deadlineReader) Read(b []byte) (int, error) {
153         // Keep-alives should be received every 2 mins. Give a bit of gracetime.
154         err := r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
155         if err != nil {
156                 return 0, fmt.Errorf("error setting read deadline: %s", err)
157         }
158         return r.r.Read(b)
159 }
160
161 func handleEncryption(
162         rw io.ReadWriter,
163         skeys mse.SecretKeyIter,
164         policy EncryptionPolicy,
165 ) (
166         ret io.ReadWriter,
167         headerEncrypted bool,
168         cryptoMethod mse.CryptoMethod,
169         err error,
170 ) {
171         if !policy.ForceEncryption {
172                 var protocol [len(pp.Protocol)]byte
173                 _, err = io.ReadFull(rw, protocol[:])
174                 if err != nil {
175                         return
176                 }
177                 rw = struct {
178                         io.Reader
179                         io.Writer
180                 }{
181                         io.MultiReader(bytes.NewReader(protocol[:]), rw),
182                         rw,
183                 }
184                 if string(protocol[:]) == pp.Protocol {
185                         ret = rw
186                         return
187                 }
188         }
189         headerEncrypted = true
190         ret, err = mse.ReceiveHandshake(rw, skeys, func(provides mse.CryptoMethod) mse.CryptoMethod {
191                 switch {
192                 case policy.ForceEncryption:
193                         return mse.CryptoMethodRC4
194                 case policy.DisableEncryption:
195                         return mse.CryptoMethodPlaintext
196                 case policy.PreferNoEncryption && provides&mse.CryptoMethodPlaintext != 0:
197                         return mse.CryptoMethodPlaintext
198                 default:
199                         return mse.DefaultCryptoSelector(provides)
200                 }
201         })
202         return
203 }