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