-
Notifications
You must be signed in to change notification settings - Fork 0
/
addr.go
335 lines (299 loc) · 8.11 KB
/
addr.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
/*
Copyright 2015 Gravitational, 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 utils
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// NetAddr is network address that includes network, optional path and
// host port
type NetAddr struct {
// Addr is the host:port address, like "localhost:22"
Addr string `json:"addr"`
// AddrNetwork is the type of a network socket, like "tcp" or "unix"
AddrNetwork string `json:"network,omitempty"`
// Path is a socket file path, like '/var/path/to/socket' in "unix:///var/path/to/socket"
Path string `json:"path,omitempty"`
}
// IsLocal returns true if this is a local address
func (a *NetAddr) IsLocal() bool {
host, _, err := net.SplitHostPort(a.Addr)
if err != nil {
return false
}
return IsLocalhost(host)
}
// IsLoopback returns true if this is a loopback address
func (a *NetAddr) IsLoopback() bool {
return IsLoopback(a.Addr)
}
// IsEmpty returns true if address is empty
func (a *NetAddr) IsEmpty() bool {
return a.Addr == "" && a.AddrNetwork == "" && a.Path == ""
}
// FullAddress returns full address including network and address (tcp://0.0.0.0:1243)
func (a *NetAddr) FullAddress() string {
return fmt.Sprintf("%v://%v", a.AddrNetwork, a.Addr)
}
// String returns address without network (0.0.0.0:1234)
func (a *NetAddr) String() string {
return a.Addr
}
// Network returns the scheme for this network address (tcp or unix)
func (a *NetAddr) Network() string {
return a.AddrNetwork
}
// MarshalYAML defines how a network address should be marshalled to a string
func (a *NetAddr) MarshalYAML() (interface{}, error) {
url := url.URL{Scheme: a.AddrNetwork, Host: a.Addr, Path: a.Path}
return strings.TrimLeft(url.String(), "/"), nil
}
// UnmarshalYAML defines how a string can be unmarshalled into a network address
func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error {
var addr string
err := unmarshal(&addr)
if err != nil {
return err
}
parsedAddr, err := ParseAddr(addr)
if err != nil {
return err
}
*a = *parsedAddr
return nil
}
func (a *NetAddr) Set(s string) error {
v, err := ParseAddr(s)
if err != nil {
return err
}
a.Addr = v.Addr
a.AddrNetwork = v.AddrNetwork
return nil
}
// ParseAddr takes strings like "tcp://host:port/path" and returns
// *NetAddr or an error
func ParseAddr(a string) (*NetAddr, error) {
if !strings.Contains(a, "://") {
host, port, err := net.SplitHostPort(a)
if err != nil {
return nil, trace.BadParameter("invalid network address: '%v', expecting host:port", a)
}
return &NetAddr{Addr: fmt.Sprintf("%v:%v", host, port), AddrNetwork: "tcp"}, nil
}
u, err := url.Parse(a)
if err != nil {
return nil, fmt.Errorf("failed to parse '%v':%v", a, err)
}
switch u.Scheme {
case "tcp":
return &NetAddr{Addr: u.Host, AddrNetwork: u.Scheme, Path: u.Path}, nil
case "unix":
return &NetAddr{Addr: u.Path, AddrNetwork: u.Scheme}, nil
default:
return nil, trace.BadParameter("'%v': unsupported scheme: '%v'", a, u.Scheme)
}
}
// MustParseAddr parses the provided string into NetAddr or panics on an error
func MustParseAddr(a string) *NetAddr {
addr, err := ParseAddr(a)
if err != nil {
panic(fmt.Sprintf("failed to parse %v: %v", a, err))
}
return addr
}
// ParseHostPortAddr takes strings like "host:port" and returns
// *NetAddr or an error
//
// If defaultPort == -1 it expects 'hostport' string to have it
func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error) {
host, port, err := net.SplitHostPort(hostport)
if err != nil {
if defaultPort > 0 {
host, port, err = net.SplitHostPort(
net.JoinHostPort(hostport, strconv.Itoa(defaultPort)))
}
if err != nil {
return nil, trace.Errorf("failed to parse '%v': %v", hostport, err)
}
}
return ParseAddr(fmt.Sprintf("tcp://%s", net.JoinHostPort(host, port)))
}
func NewNetAddrVal(defaultVal NetAddr, val *NetAddr) *NetAddrVal {
*val = defaultVal
return (*NetAddrVal)(val)
}
// NetAddrVal can be used with flag package
type NetAddrVal NetAddr
func (a *NetAddrVal) Set(s string) error {
v, err := ParseAddr(s)
if err != nil {
return err
}
a.Addr = v.Addr
a.AddrNetwork = v.AddrNetwork
return nil
}
func (a *NetAddrVal) String() string {
return ((*NetAddr)(a)).FullAddress()
}
func (a *NetAddrVal) Get() interface{} {
return NetAddr(*a)
}
// NetAddrList is a list of NetAddrs that supports
// helper methods for parsing from CLI tools
type NetAddrList []NetAddr
// Addresses returns a slice of strings converted from the addresses
func (nl *NetAddrList) Addresses() []string {
var ns []string
for _, n := range *nl {
ns = append(ns, n.FullAddress())
}
return ns
}
// Set is called by CLI tools
func (nl *NetAddrList) Set(s string) error {
v, err := ParseAddr(s)
if err != nil {
return err
}
*nl = append(*nl, *v)
return nil
}
// String returns debug-friendly representation of the tool
func (nl *NetAddrList) String() string {
var ns []string
for _, n := range *nl {
ns = append(ns, n.FullAddress())
}
return strings.Join(ns, " ")
}
// ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1)
// and replaces it with the IP taken from replaceWith, preserving the original port
//
// Both addresses are in "host:port" format
// The function returns the original value if it encounters any problems with parsing
func ReplaceLocalhost(addr, replaceWith string) string {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
if IsLocalhost(host) {
host, _, err = net.SplitHostPort(replaceWith)
if err != nil {
return addr
}
addr = net.JoinHostPort(host, port)
}
return addr
}
// IsLocalhost returns true if this is a local hostname or ip
func IsLocalhost(host string) bool {
if host == "localhost" {
return true
}
ip := net.ParseIP(host)
return ip.IsLoopback() || ip.IsUnspecified()
}
// IsLoopback returns 'true' if a given hostname resolves to local
// host's loopback interface
func IsLoopback(host string) bool {
if strings.Contains(host, ":") {
var err error
host, _, err = net.SplitHostPort(host)
if err != nil {
return false
}
}
ips, err := net.LookupIP(host)
if err != nil {
return false
}
for _, ip := range ips {
if ip.IsLoopback() {
return true
}
}
return false
}
// GuessIP tries to guess an IP address this machine is reachable at on the
// internal network, always picking IPv4 from the internal address space
//
// If no internal IPs are found, it returns 127.0.0.1 but it never returns
// an address from the public IP space
func GuessHostIP() (ip net.IP, err error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, trace.Wrap(err)
}
adrs := make([]net.Addr, 0)
for _, iface := range ifaces {
ifadrs, err := iface.Addrs()
if err != nil {
log.Warn(err)
} else {
adrs = append(adrs, ifadrs...)
}
}
return guessHostIP(adrs), nil
}
func guessHostIP(addrs []net.Addr) (ip net.IP) {
// collect the list of all IPv4s
var ips []net.IP
for _, addr := range addrs {
var ipAddr net.IP
a, ok := addr.(*net.IPAddr)
if ok {
ipAddr = a.IP
} else {
in, ok := addr.(*net.IPNet)
if ok {
ipAddr = in.IP
} else {
continue
}
}
if ipAddr.To4() == nil || ipAddr.IsLoopback() || ipAddr.IsMulticast() {
continue
}
ips = append(ips, ipAddr)
}
for i := range ips {
switch ips[i][12] {
// our first pick would be "10.x.x.x" IPs:
case 10:
return ips[i]
// our 2nd pick would be "192.x.x.x"
case 192:
ip = ips[i]
// our 3rd pick would be "172.x.x.x"
case 172:
if ip == nil {
ip = ips[i]
}
}
}
if ip == nil {
if len(ips) > 0 {
return ips[0]
}
// fallback to loopback
ip = net.IPv4(127, 0, 0, 1)
}
return ip
}