generated from openziti/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
address.go
355 lines (293 loc) · 9.11 KB
/
address.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
Copyright NetFoundry 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
https://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 transport
import (
"fmt"
"github.com/openziti/identity"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"io"
"math"
"net"
"strings"
"time"
)
const (
KeyProxy = "proxy"
KeyProtocol = "protocol"
KeyCachedProxyConfiguration = "cachedProxyConfiguration"
KeyHandshakeTimeout = "handshakeTimeout"
KeyCachedHandshakeTimeout = "cachedHandshakeTimeout"
)
type Configuration map[interface{}]interface{}
// Protocols returns supported or requested application protocols (used for ALPN support)
func (self Configuration) Protocols() []string {
if self == nil {
return nil
}
p, found := self[KeyProtocol]
if found {
switch v := p.(type) {
case string:
return []string{v}
case []string:
return v
default:
panic("invalid transport.Configuration[protocols] type")
}
}
return nil
}
func (self Configuration) GetProxyConfiguration() (*ProxyConfiguration, error) {
if self == nil {
return nil, nil
}
if val, found := self[KeyCachedProxyConfiguration]; found {
return val.(*ProxyConfiguration), nil
}
val, found := self[KeyProxy]
if !found {
return nil, nil
}
cfg, ok := val.(map[interface{}]interface{})
if !ok {
return nil, errors.New("invalid proxy configuration value, should be map")
}
result, err := LoadProxyConfiguration(cfg)
if err != nil {
return nil, err
}
self[KeyCachedProxyConfiguration] = result
return result, nil
}
func (self Configuration) GetHandshakeTimeout() (time.Duration, error) {
if val, ok := self[KeyCachedHandshakeTimeout]; ok {
if timeout, ok := val.(time.Duration); ok {
return timeout, nil
}
}
if val, ok := self[KeyHandshakeTimeout]; ok {
if strVal, ok := val.(string); ok {
timeout, err := time.ParseDuration(strVal)
if err == nil {
self[KeyCachedHandshakeTimeout] = timeout
}
return timeout, errors.Wrapf(err, "unable to parse handshake timeout '%s' to duration", strVal)
} else {
return 0, errors.New("invalid handshake timeout, must be string value")
}
}
return 0, nil
}
func (self Configuration) GetUIntValue(first string, rest ...string) (uint, bool, error) {
val, err := self.GetValue(first, rest...)
if val == nil {
return 0, false, err
}
intVal, ok := val.(int)
if !ok {
key := strings.Join(self.toSlice(first, rest...), ":")
return 0, false, errors.Errorf("value for key %s should be int, not %v of type '%T'", key, val, val)
}
if intVal < 0 {
key := strings.Join(self.toSlice(first, rest...), ":")
return 0, false, errors.Errorf("value for key %s should be positive, not %v ", key, intVal)
}
if intVal > math.MaxInt {
key := strings.Join(self.toSlice(first, rest...), ":")
return 0, false, errors.Errorf("value for key %s should be less or equal to %d, not %v ", key, math.MaxInt, intVal)
}
return uint(intVal), true, nil
}
func (self Configuration) GetInt64Value(first string, rest ...string) (int64, bool, error) {
val, err := self.GetValue(first, rest...)
if val == nil {
return 0, false, err
}
intVal, ok := val.(int)
if !ok {
key := strings.Join(self.toSlice(first, rest...), ":")
return 0, false, errors.Errorf("value for key %s should be int, not %v of type '%T'", key, val, val)
}
return int64(intVal), true, nil
}
func (self Configuration) toSlice(first string, rest ...string) []string {
if len(rest) == 0 {
return []string{first}
}
key := make([]string, len(rest)+1)
key[0] = first
copy(key[1:], rest)
return key
}
func (self Configuration) GetValue(first string, rest ...string) (interface{}, error) {
return self.getValue(0, self.toSlice(first, rest...)...)
}
func (self Configuration) getValue(index int, key ...string) (interface{}, error) {
if index == len(key)-1 {
return self[key[index]], nil
}
val, ok := self[key[index]]
if !ok {
return nil, nil
}
subMap, ok := val.(map[interface{}]interface{})
if !ok {
return nil, fmt.Errorf("invalid transport configuration value. %s should be map, not %T",
strings.Join(key[:index+1], ":"), val)
}
return Configuration(subMap).getValue(index+1, key...)
}
type ProxyType string
const (
ProxyTypeNone ProxyType = "none"
ProxyTypeHttpConnect ProxyType = "http"
)
type ProxyConfiguration struct {
Type ProxyType
Address string
Auth *proxy.Auth
}
func LoadProxyConfiguration(cfg map[interface{}]interface{}) (*ProxyConfiguration, error) {
val, found := cfg["type"]
if !found {
return nil, errors.New("proxy configuration does not specify proxy type")
}
proxyType, ok := val.(string)
if !ok {
return nil, errors.New("proxy type must be a string")
}
if proxyType == string(ProxyTypeNone) {
return &ProxyConfiguration{
Type: ProxyTypeNone,
}, nil
}
result := &ProxyConfiguration{}
switch proxyType {
case string(ProxyTypeHttpConnect):
result.Type = ProxyTypeHttpConnect
default:
return nil, errors.Errorf("invalid proxy type %s", proxyType)
}
val, found = cfg["address"]
if !found {
return nil, errors.Errorf("no address specified for %s proxy", string(result.Type))
}
if addr, ok := val.(string); !ok {
return nil, errors.Errorf("invalid value for %s proxy address [%v], must be string", string(result.Type), val)
} else {
result.Address = addr
}
if val, found = cfg["username"]; found {
if username, ok := val.(string); ok {
result.Auth = &proxy.Auth{
User: username,
}
} else {
return nil, errors.Errorf("invalid value for %s proxy username [%v], must be string", string(result.Type), val)
}
if val, found = cfg["password"]; found {
if password, ok := val.(string); ok {
result.Auth.Password = password
} else {
return nil, errors.Errorf("invalid value for %s proxy password [%v], must be string", string(result.Type), val)
}
}
}
return result, nil
}
// Address implements the functionality provided by a generic "address".
type Address interface {
Dial(name string, i *identity.TokenId, timeout time.Duration, tcfg Configuration) (Conn, error)
DialWithLocalBinding(name string, binding string, i *identity.TokenId, timeout time.Duration, tcfg Configuration) (Conn, error)
Listen(name string, i *identity.TokenId, acceptF func(Conn), tcfg Configuration) (io.Closer, error)
MustListen(name string, i *identity.TokenId, acceptF func(Conn), tcfg Configuration) io.Closer
String() string
Type() string
}
type HostPortAddress interface {
Address
Hostname() string
Port() uint16
}
// AddressParser implements the functionality provided by an "address parser".
type AddressParser interface {
Parse(addressString string) (Address, error)
}
// AddAddressParser adds an AddressParser to the globally-configured address parsers.
func AddAddressParser(addressParser AddressParser) {
for _, e := range addressParsers {
if addressParser == e {
return
}
}
addressParsers = append(addressParsers, addressParser)
}
// ParseAddress uses the globally-configured AddressParser instances to parse an address.
func ParseAddress(addressString string) (Address, error) {
if addressParsers == nil || len(addressParsers) < 1 {
return nil, errors.New("no configured address parsers")
}
for _, addressParser := range addressParsers {
address, err := addressParser.Parse(addressString)
if err == nil {
return address, nil
}
}
return nil, fmt.Errorf("address (%v) not parsed", addressString)
}
// The globally-configured address parsers.
var addressParsers = make([]AddressParser, 0)
// Resolve a network interface by name or IP address
func ResolveInterface(toResolve string) (*net.Interface, error) {
// Easy check first - see if the interface is specified by name
ief, err := net.InterfaceByName(toResolve)
if err == nil {
return ief, nil
}
// Nope! Scan all network interfaces to if there is an IP match
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
if (iface.Flags & net.FlagUp) == 0 {
log.Debugf("Interface %s is down, ignoring it for address resolution", iface.Name)
continue
}
addrs, err := iface.Addrs()
if err != nil {
log.Warnf("Could not check interface %s (%s)", iface.Name, err)
continue
}
for _, addr := range addrs {
log.Tracef("Checking interface %s (%s) against %s", iface.Name, addr.String(), toResolve)
var ip net.IP
switch addr := addr.(type) {
case *net.IPAddr:
ip = addr.IP
case *net.IPNet:
ip = addr.IP
default:
continue
}
if ip.To4() != nil && ip.To4().String() == toResolve {
log.Debugf("Resolved %s to interface %s", toResolve, iface.Name)
return &iface, nil
}
}
}
// Not an IP either, not sure how to resolve this interface
return nil, errors.Errorf("no network interface found for %s", toResolve)
}