-
Notifications
You must be signed in to change notification settings - Fork 9
/
probe.go
268 lines (240 loc) · 5.45 KB
/
probe.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package dc
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"net/url"
"sync"
"time"
adcp "github.com/direct-connect/go-dc/adc"
nmdcp "github.com/direct-connect/go-dc/nmdc"
)
var Debug bool
var (
ErrUnsupportedProtocol = errors.New("unsupported protocol")
)
type timeoutErr interface {
Timeout() bool
}
const (
probeTimeout = time.Second * 5
nmdcSchema = nmdcp.SchemeNMDC
nmdcsSchema = nmdcp.SchemeNMDCS
adcSchema = adcp.SchemaADC
adcsSchema = adcp.SchemaADCS
)
func dialContext(ctx context.Context, addr string) (net.Conn, error) {
timeout := probeTimeout
if deadline, ok := ctx.Deadline(); ok {
timeout = deadline.Sub(time.Now())
}
return net.DialTimeout("tcp", addr, timeout)
}
// Probe tries to detect the protocol on a specified host or host:port.
// It returns a canonical address with an appropriate URI scheme.
func Probe(rctx context.Context, addr string) (*url.URL, error) {
u, err := url.Parse(addr)
if err != nil || u.Host == "" {
// may be a hostname:port
if _, _, err := net.SplitHostPort(addr); err != nil {
// assume it's a hostname only
addr += ":411" // TODO: should also try 412, 413, etc
}
u = &url.URL{Host: addr}
}
var wg sync.WaitGroup
defer wg.Wait()
ctx, cancel := context.WithCancel(rctx)
defer cancel()
// race TLS and plaintext connection
errc := make(chan error, 2)
outPlain := make(chan string, 1)
outTLS := make(chan string, 1)
wg.Add(2)
go func() {
defer func() {
wg.Done()
if r := recover(); r != nil {
errc <- fmt.Errorf("panic: %v", r)
}
}()
proto, err := probeTLS(ctx, u.Host)
if err != nil {
errc <- err
return
}
outTLS <- proto
}()
go func() {
defer func() {
wg.Done()
if r := recover(); r != nil {
errc <- fmt.Errorf("panic: %v", r)
}
}()
proto, err := probePlain(ctx, u.Host)
if err != nil {
errc <- err
return
}
outPlain <- proto
}()
var (
protoPlain string
err1 error
)
select {
case protoTLS := <-outTLS:
// prefer TLS
u.Scheme = protoTLS
return u, nil
case protoPlain = <-outPlain:
// wait for TLS response
case err1 = <-errc:
// wait for the second one
}
select {
case protoTLS := <-outTLS:
// prefer TLS
u.Scheme = protoTLS
return u, nil
case protoPlain = <-outPlain:
// the first error was from TLS
u.Scheme = protoPlain
return u, nil
case err := <-errc:
if err1 == nil {
// TLS failed, but plaintext was successful
u.Scheme = protoPlain
return u, nil
}
// both attempts failed
if err == ErrUnsupportedProtocol && err1 == ErrUnsupportedProtocol {
return u, err
} else if e, ok := err.(timeoutErr); ok && e.Timeout() {
// return any if it's a timeout
return u, err
}
// return both
return u, fmt.Errorf("probe failed: %v; %v", err1, err)
}
}
// pretend that we speak a base version of ADC
const adcHandshake = "HSUP ADBAS0 ADBASE ADTIGR\x0a"
func probeTLS(ctx context.Context, addr string) (string, error) {
c, err := dialContext(ctx, addr)
if err != nil {
return "", err
}
defer c.Close()
now := time.Now()
dt := probeTimeout
if deadline, ok := ctx.Deadline(); ok {
sub := deadline.Sub(now)
if sub < 0 {
return "", context.DeadlineExceeded
}
if dt > sub {
dt = sub
}
}
if err = c.SetDeadline(now.Add(dt)); err != nil {
return "", err
}
tc := tls.Client(c, &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"adc", "nmdc"},
})
defer tc.Close()
if err = tc.Handshake(); err != nil {
return "", ErrUnsupportedProtocol
}
// first, check if ALPN handshake was successful
state := tc.ConnectionState()
if Debug && state.NegotiatedProtocol != "" {
log.Println("ALPN negotiated:", state.NegotiatedProtocol)
}
switch state.NegotiatedProtocol {
case "adc":
return adcsSchema, nil
case "nmdc":
return nmdcsSchema, nil
}
// repeat ADC handshake over TLS this time
if err = tc.SetDeadline(now.Add(dt)); err != nil {
return "", err
}
_, err = tc.Write([]byte(adcHandshake))
if err != nil {
return "", err
}
buf := make([]byte, 5)
n, err := tc.Read(buf)
if err == nil && string(buf[:n]) == "ISUP " {
return adcsSchema, nil
}
return "", ErrUnsupportedProtocol
}
func probePlain(ctx context.Context, addr string) (string, error) {
c, err := dialContext(ctx, addr)
if err != nil {
return "", err
}
defer c.Close()
now := time.Now()
dt := probeTimeout
if deadline, ok := ctx.Deadline(); ok {
sub := deadline.Sub(now)
if sub < 0 {
return "", context.DeadlineExceeded
}
if dt > sub {
dt = sub
}
}
if err = c.SetReadDeadline(now.Add(dt)); err != nil {
return "", err
}
buf := make([]byte, 6)
n, err := c.Read(buf)
if err == nil {
// may be NMDC protocol where server speaks first
if string(buf[:n]) == "$Lock " {
return nmdcSchema, nil
}
return "", ErrUnsupportedProtocol
}
te, ok := err.(timeoutErr)
if !ok || !te.Timeout() {
return "", err
}
// timeout, server expects that we speak first
now = time.Now()
curDeadline := now.Add(dt)
if err = c.SetWriteDeadline(curDeadline); err != nil {
return "", err
}
_, err = c.Write([]byte(adcHandshake))
if err != nil {
// FIXME: server may drop the connection earlier, since we waited too long
return "", err
}
if err = c.SetReadDeadline(curDeadline); err != nil {
return "", err
}
buf = buf[:5]
n, err = c.Read(buf)
if err == io.EOF {
return "", ErrUnsupportedProtocol
} else if err != nil {
return "", err
}
if string(buf[:n]) == "ISUP " {
return adcSchema, nil
}
return "", ErrUnsupportedProtocol
}