-
Notifications
You must be signed in to change notification settings - Fork 8
/
proxy.go
177 lines (150 loc) · 4.86 KB
/
proxy.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
// Copyright 2020 SEQSENSE, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tunnel
import (
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
"golang.org/x/net/websocket"
"github.com/seqsense/aws-iot-device-sdk-go/v6/internal/ioterr"
)
const (
defaultEndpointHostFormat = "data.tunneling.iot.%s.amazonaws.com"
defaultPingPeriod = 5 * time.Second
websocketProtocol = "aws.iot.securetunneling-1.0"
userAgent = "aws-iot-device-sdk-go/tunnel"
)
// ErrUnsupportedScheme indicate that the requested protocol scheme is not supported.
var ErrUnsupportedScheme = errors.New("unsupported scheme")
func endpointHost(region string) string {
return fmt.Sprintf(defaultEndpointHostFormat, region)
}
// Dialer is a proxy destination dialer.
type Dialer func() (io.ReadWriteCloser, error)
// ProxyDestination proxies TCP connection from remote source device to
// the local destination application via IoT secure tunneling.
// This is usually used on IoT things.
func ProxyDestination(dialer Dialer, endpoint, token string, opts ...ProxyOption) error {
ws, opt, err := openProxyConn(endpoint, "destination", token, opts...)
if err != nil {
return ioterr.New(err, "opening proxy destination")
}
pingCancel := newPinger(ws, opt.PingPeriod)
defer pingCancel()
return proxyDestination(ws, dialer, opt.ErrorHandler, opt.Stat)
}
// ProxySource proxies TCP connection from local socket to
// remote destination application via IoT secure tunneling.
// This is usually used on a computer or bastion server.
func ProxySource(listener net.Listener, endpoint, token string, opts ...ProxyOption) error {
ws, opt, err := openProxyConn(endpoint, "source", token, opts...)
if err != nil {
return ioterr.New(err, "opening proxy source")
}
pingCancel := newPinger(ws, opt.PingPeriod)
defer pingCancel()
return proxySource(ws, listener, opt.ErrorHandler, opt.Stat)
}
func openProxyConn(endpoint, mode, token string, opts ...ProxyOption) (*websocket.Conn, *ProxyOptions, error) {
opt := &ProxyOptions{
Scheme: "wss",
PingPeriod: defaultPingPeriod,
}
for _, o := range opts {
if err := o(opt); err != nil {
return nil, nil, ioterr.New(err, "applying options")
}
}
if err := opt.validate(); err != nil {
return nil, nil, err
}
wsc, err := websocket.NewConfig(
fmt.Sprintf("%s://%s/tunnel?local-proxy-mode=%s", opt.Scheme, endpoint, mode),
fmt.Sprintf("https://%s", endpoint),
)
if err != nil {
return nil, nil, ioterr.New(err, "creating ws config")
}
if opt.Scheme == "wss" {
wsc.TlsConfig = &tls.Config{
// Remove protocol default port number from the URI to avoid TLS certificate validation error.
ServerName: serverNameFromEndpoint(opt.Scheme, endpoint),
InsecureSkipVerify: opt.InsecureSkipVerify,
}
}
wsc.Header = http.Header{
"Access-Token": []string{token},
"User-Agent": []string{userAgent},
}
wsc.Protocol = append(wsc.Protocol, websocketProtocol)
ws, err := websocket.DialConfig(wsc)
if err != nil {
return nil, nil, ioterr.New(err, "creating ws dial config")
}
ws.PayloadType = websocket.BinaryFrame
return ws, opt, nil
}
// ErrorHandler is an interface to handler error.
type ErrorHandler interface {
HandleError(error)
}
// ErrorHandlerFunc type is an adapter to use handler function as ErrorHandler.
type ErrorHandlerFunc func(error)
// HandleError implements ErrorHandler interface.
func (f ErrorHandlerFunc) HandleError(err error) {
f(err)
}
// ProxyOption is a type of functional options.
type ProxyOption func(*ProxyOptions) error
// ProxyOptions stores options of the proxy.
type ProxyOptions struct {
InsecureSkipVerify bool
Scheme string
ErrorHandler ErrorHandler
PingPeriod time.Duration
Stat Stat
}
func (o *ProxyOptions) validate() error {
switch o.Scheme {
case "wss", "ws":
default:
return ioterr.New(ErrUnsupportedScheme, o.Scheme)
}
return nil
}
// WithErrorHandler sets a ErrorHandler.
func WithErrorHandler(h ErrorHandler) ProxyOption {
return func(opt *ProxyOptions) error {
opt.ErrorHandler = h
return nil
}
}
// WithPingPeriod sets ping send period.
func WithPingPeriod(d time.Duration) ProxyOption {
return func(opt *ProxyOptions) error {
opt.PingPeriod = d
return nil
}
}
// WithStat enables statistics.
func WithStat(stat Stat) ProxyOption {
return func(opt *ProxyOptions) error {
opt.Stat = stat
return nil
}
}