-
Notifications
You must be signed in to change notification settings - Fork 70
/
dial.go
157 lines (143 loc) · 3.38 KB
/
dial.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package btconn
import (
"bytes"
"context"
"net"
"time"
"github.com/cenkalti/rain/internal/logger"
"github.com/cenkalti/rain/internal/mse"
)
// Dial new connection to the address. Does the BitTorrent protocol handshake.
// Handles encryption. May try to connect again if encryption does not match with given setting.
// Returns a net.Conn that is ready for sending/receiving BitTorrent peer protocol messages.
func Dial(
addr net.Addr,
dialTimeout, handshakeTimeout time.Duration,
enableEncryption,
forceEncryption bool,
ourExtensions [8]byte,
ih [20]byte,
ourID [20]byte,
stopC chan struct{}) (
conn net.Conn, cipher mse.CryptoMethod, peerExtensions [8]byte, peerID [20]byte, err error) {
log := logger.New("conn -> " + addr.String())
done := make(chan struct{})
defer close(done)
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-stopC:
cancel()
case <-done:
}
}()
// First connection
log.Debug("Connecting to peer...")
dialer := net.Dialer{Timeout: dialTimeout}
conn, err = dialer.DialContext(ctx, addr.Network(), addr.String())
if err != nil {
return
}
log.Debug("Connected")
defer func(conn net.Conn) {
if err != nil {
conn.Close()
}
}(conn)
go func(conn net.Conn) {
select {
case <-stopC:
conn.Close()
case <-done:
}
}(conn)
// Write first part of BitTorrent handshake to a buffer because we will use it in both encrypted and unencrypted handshake.
out := bytes.NewBuffer(make([]byte, 0, 68))
err = writeHandshake(out, ih, ourID, ourExtensions)
if err != nil {
return
}
// Handshake must be completed in allowed duration.
if err = conn.SetDeadline(time.Now().Add(handshakeTimeout)); err != nil {
return
}
if enableEncryption {
sKey := make([]byte, 20)
copy(sKey, ih[:])
provide := mse.RC4
if !forceEncryption {
provide |= mse.PlainText
}
// Try encryption handshake
encConn := mse.WrapConn(conn)
cipher, err = encConn.HandshakeOutgoing(sKey, provide, out.Bytes())
if err != nil {
select {
case <-stopC:
return
default:
}
log.Debugln("Encrytpion handshake has failed:", err)
if forceEncryption {
log.Debug("Will not try again because ougoing encryption is forced.")
err = errNotEncrypted
return
}
// Close current connection and try again without encryption
conn.Close()
log.Debug("Connecting again without encryption...")
conn, err = dialer.DialContext(ctx, addr.Network(), addr.String())
if err != nil {
return
}
log.Debug("Connected")
defer func(conn net.Conn) {
if err != nil {
conn.Close()
}
}(conn)
go func(conn net.Conn) {
select {
case <-stopC:
conn.Close()
case <-done:
}
}(conn)
// Send BT handshake
if err = conn.SetDeadline(time.Now().Add(handshakeTimeout)); err != nil {
return
}
if _, err = conn.Write(out.Bytes()); err != nil {
return
}
} else {
log.Debugf("Encryption handshake is successful. Selected cipher: %s", cipher)
conn = encConn
}
} else {
// Send BT handshake
_, err = conn.Write(out.Bytes())
if err != nil {
return
}
}
// Read BT handshake
var ihRead [20]byte
peerExtensions, ihRead, err = readHandshake1(conn)
if err != nil {
return
}
if ihRead != ih {
err = errInvalidInfoHash
return
}
peerID, err = readHandshake2(conn)
if err != nil {
return
}
if peerID == ourID {
err = errOwnConnection
return
}
return
}