-
Notifications
You must be signed in to change notification settings - Fork 3
/
connect.go
290 lines (268 loc) · 7.36 KB
/
connect.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package main
import (
"context"
"crypto/tls"
"encoding/binary"
"fmt"
"github.com/hashicorp/yamux"
"github.com/jpillora/backoff"
"io"
"k8s.io/klog"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var (
version = "unknown"
timeout = 10 * time.Second
tlsSkipVerify = false
endpointsRefreshInterval = 10 * time.Minute
backoffFactor = 2.
backoffMin = 5 * time.Second
backoffMax = time.Minute
streamTimeout = 5 * time.Minute
)
type Tunnel struct {
address string
serverName string
token string
config []byte
cancelFn context.CancelFunc
gwConn net.Conn
}
func NewTunnel(address, serverName string, token string, config []byte) *Tunnel {
t := &Tunnel{
address: address,
serverName: serverName,
token: token,
config: config,
}
var ctx context.Context
ctx, t.cancelFn = context.WithCancel(context.Background())
go t.keepConnected(ctx)
return t
}
func (t *Tunnel) keepConnected(ctx context.Context) {
b := backoff.Backoff{Factor: backoffFactor, Min: backoffMin, Max: backoffMax}
var err error
for {
select {
case <-ctx.Done():
return
default:
t.gwConn, err = connect(t.address, t.serverName, t.token, t.config)
if err == nil {
start := time.Now()
err = proxy(ctx, t.gwConn)
_ = t.gwConn.Close()
if time.Since(start) > b.Max {
b.Reset()
}
}
if err != nil {
klog.Errorln(err)
d := b.Duration()
klog.Infof("reconnecting to %s in %.0fs", t.address, d.Seconds())
time.Sleep(d)
continue
}
b.Reset()
}
}
}
func (t *Tunnel) Close() {
t.cancelFn()
if t.gwConn != nil {
_ = t.gwConn.Close()
}
}
func main() {
resolverUrl := os.Getenv("RESOLVER_URL")
if resolverUrl == "" {
resolverUrl = "https://gw.coroot.com/connect/resolve"
}
token := mustEnv("PROJECT_TOKEN")
if len(token) != 36 {
klog.Exitln("invalid project token")
}
configPath := mustEnv("CONFIG_PATH")
data, err := os.ReadFile(configPath)
if err != nil {
klog.Exitln("failed to read config:", err)
}
config := []byte(os.ExpandEnv(string(data)))
klog.Infof("version: %s", version)
loop(token, resolverUrl, config)
}
func loop(token, resolverUrl string, config []byte) {
u, err := url.Parse(resolverUrl)
if err != nil {
klog.Exitf("invalid resolver URL %s: %s", resolverUrl, err)
}
tlsServerName := u.Hostname()
tunnels := map[string]*Tunnel{}
b := backoff.Backoff{Factor: backoffFactor, Min: backoffMin, Max: backoffMax}
for {
klog.Infof("updating gateways endpoints from %s", resolverUrl)
endpoints, err := getEndpoints(resolverUrl, token)
if err != nil {
d := b.Duration()
klog.Errorf("failed to get gateway endpoints: %s, retry in %.0fs", err, d.Seconds())
time.Sleep(d)
continue
}
b.Reset()
klog.Infof("desired endpoints: %s", endpoints)
fresh := map[string]bool{}
for _, e := range endpoints {
fresh[e] = true
if _, ok := tunnels[e]; !ok {
klog.Infof("starting a tunnel to %s", e)
tunnels[e] = NewTunnel(e, tlsServerName, token, config)
}
}
for e, t := range tunnels {
if !fresh[e] {
klog.Infof("closing tunnel with %s", e)
t.Close()
delete(tunnels, e)
}
}
time.Sleep(endpointsRefreshInterval)
}
}
func getEndpoints(resolverUrl, token string) ([]string, error) {
req, _ := http.NewRequest("GET", resolverUrl, nil)
req.Header.Set("X-Token", token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
payload, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%s: %s", resp.Status, string(payload))
}
return strings.Split(strings.TrimSpace(string(payload)), ";"), nil
}
type RequestHeader struct {
Token [36]byte
Version [16]byte
ConfigSize uint32
}
type ResponseHeader struct {
Status uint16
MessageSize uint16
}
func connect(gwAddr, serverName, token string, config []byte) (net.Conn, error) {
requestHeader := RequestHeader{}
copy(requestHeader.Token[:], token)
copy(requestHeader.Version[:], version)
requestHeader.ConfigSize = uint32(len(config))
klog.Infof("connecting to %s (%s)", gwAddr, serverName)
deadline := time.Now().Add(timeout)
dialer := &net.Dialer{Deadline: deadline}
tlsCfg := &tls.Config{ServerName: serverName, InsecureSkipVerify: tlsSkipVerify}
gwConn, err := tls.DialWithDialer(dialer, "tcp", gwAddr, tlsCfg)
if err != nil {
return nil, fmt.Errorf("failed to establish a connection to %s: %s", gwAddr, err)
}
klog.Infof("connected to gateway %s", gwAddr)
_ = gwConn.SetDeadline(deadline)
if err = binary.Write(gwConn, binary.LittleEndian, requestHeader); err != nil {
_ = gwConn.Close()
return nil, fmt.Errorf("failed to send config to %s: %s", gwAddr, err)
}
if _, err = gwConn.Write(config); err != nil {
_ = gwConn.Close()
return nil, fmt.Errorf("failed to send config to %s: %s", gwAddr, err)
}
var responseHeader ResponseHeader
if err := binary.Read(gwConn, binary.LittleEndian, &responseHeader); err != nil {
_ = gwConn.Close()
return nil, fmt.Errorf("failed to read the response from %s: %s", gwAddr, err)
}
var responseMessage string
if responseHeader.MessageSize > 0 {
buf := make([]byte, responseHeader.MessageSize)
if _, err := gwConn.Read(buf); err != nil {
_ = gwConn.Close()
return nil, fmt.Errorf("failed to read the response from %s: %s", gwAddr, err)
}
responseMessage = string(buf)
}
_ = gwConn.SetDeadline(time.Time{})
if responseHeader.Status != 200 {
_ = gwConn.Close()
return nil, fmt.Errorf("got %d from %s: %s", responseHeader.Status, gwAddr, responseMessage)
}
klog.Infof("ready to proxy requests from %s", gwAddr)
return gwConn, nil
}
func proxy(ctx context.Context, gwConn net.Conn) error {
cfg := yamux.DefaultConfig()
cfg.KeepAliveInterval = time.Second
cfg.LogOutput = io.Discard
session, err := yamux.Server(gwConn, cfg)
if err != nil {
return fmt.Errorf("failed to start a TCP multiplexing server: %s", err)
}
defer session.Close()
for {
select {
case <-ctx.Done():
return nil
default:
gwStream, err := session.Accept()
if err != nil {
return fmt.Errorf("failed to accept a stream: %s", err)
}
go func(c net.Conn) {
defer c.Close()
deadline := time.Now().Add(streamTimeout)
if err := c.SetDeadline(deadline); err != nil {
klog.Errorf("failed to set a deadline for the stream: %s", err)
return
}
var dstLen uint16
if err := binary.Read(c, binary.LittleEndian, &dstLen); err != nil {
klog.Errorf("failed to read the destination size: %s", err)
return
}
dest := make([]byte, int(dstLen))
if _, err := io.ReadFull(c, dest); err != nil {
klog.Errorf("failed to read the destination address: %s", err)
return
}
destAddress := string(dest)
destConn, err := net.DialTimeout("tcp", destAddress, timeout)
if err != nil {
klog.Errorf("failed to establish a connection to %s: %s", destAddress, err)
return
}
defer destConn.Close()
if err = destConn.SetDeadline(deadline); err != nil {
klog.Errorf("failed to set a deadline for the dest connection: %s", err)
return
}
go func() {
io.Copy(c, destConn)
}()
io.Copy(destConn, c)
}(gwStream)
}
}
}
func mustEnv(key string) string {
value := os.Getenv(key)
if value == "" {
klog.Exitln(key, "environment variable is required")
}
return value
}