-
Notifications
You must be signed in to change notification settings - Fork 368
/
net.go
426 lines (385 loc) · 11.8 KB
/
net.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// Copyright 2019 Antrea Authors
//
// 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 util
import (
"crypto/rand"
"crypto/sha1" // #nosec G505: not used for security purposes
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"net"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2"
utilnet "k8s.io/utils/net"
"antrea.io/antrea/pkg/util/ip"
)
const (
interfaceNameLength = 15
interfacePrefixLength = 8
interfaceKeyLength = interfaceNameLength - (interfacePrefixLength + 1)
FamilyIPv4 uint8 = 4
FamilyIPv6 uint8 = 6
bridgedUplinkSuffix = "~"
)
func generateInterfaceName(key string, name string, useHead bool) string {
hash := sha1.New() // #nosec G401: not used for security purposes
io.WriteString(hash, key)
interfaceKey := hex.EncodeToString(hash.Sum(nil))
prefix := name
if len(name) > interfacePrefixLength {
// We use Node/Pod name to generate the interface name,
// valid chars for Node/Pod name are ASCII letters from a to z,
// the digits from 0 to 9, and the hyphen (-).
// Hyphen (-) is the only char which will impact command-line interpretation
// if the interface name starts with one, so we remove it here.
if useHead {
prefix = strings.TrimLeft(name[:interfacePrefixLength], "-")
} else {
prefix = strings.TrimLeft(name[len(name)-interfacePrefixLength:], "-")
}
}
return fmt.Sprintf("%s-%s", prefix, interfaceKey[:interfaceKeyLength])
}
// GenerateContainerInterfaceKey generates a unique string for a Pod's
// interface as: container/<Container-ID>.
// We must use ContainerID instead of PodNamespace + PodName because there could
// be more than one container associated with the same Pod at some point.
// For example, when deleting a StatefulSet Pod with 0 second grace period, the
// Pod will be removed from the Kubernetes API very quickly and a new Pod will
// be created immediately, and kubelet may process the deletion of the previous
// Pod and the addition of the new Pod simultaneously.
func GenerateContainerInterfaceKey(containerID string) string {
return fmt.Sprintf("container/%s", containerID)
}
// GenerateNodeTunnelInterfaceKey generates a unique string for a Node's
// tunnel interface as: node/<Node-name>.
func GenerateNodeTunnelInterfaceKey(nodeName string) string {
return fmt.Sprintf("node/%s", nodeName)
}
// GenerateContainerInterfaceName generates a unique interface name using the
// Pod's namespace, name and containerID. The output should be deterministic (so that
// multiple calls to GenerateContainerInterfaceName with the same parameters
// return the same value). The output has the length of interfaceNameLength(15).
// The probability of collision should be neglectable.
func GenerateContainerInterfaceName(podName, podNamespace, containerID string) string {
// Use the podName as the prefix and the containerID as the hashing key.
// podNamespace is not used currently.
return generateInterfaceName(containerID, podName, true)
}
// GenerateNodeTunnelInterfaceName generates a unique interface name for the
// tunnel to the Node, using the Node's name.
func GenerateNodeTunnelInterfaceName(nodeName string) string {
return generateInterfaceName(GenerateNodeTunnelInterfaceKey(nodeName), nodeName, false)
}
type LinkNotFound struct {
error
}
func newLinkNotFoundError(name string) LinkNotFound {
return LinkNotFound{
fmt.Errorf("link %s not found", name),
}
}
func listenUnix(address string) (net.Listener, error) {
return net.Listen("unix", address)
}
func dialUnix(address string) (net.Conn, error) {
return net.Dial("unix", address)
}
// GetIPNetDeviceFromIP returns local IPs/masks and associated device from IP, and ignores the interfaces which have
// names in the ignoredInterfaces.
func GetIPNetDeviceFromIP(localIPs *ip.DualStackIPs, ignoredInterfaces sets.String) (v4IPNet *net.IPNet, v6IPNet *net.IPNet, iface *net.Interface, err error) {
linkList, err := net.Interfaces()
if err != nil {
return nil, nil, nil, err
}
// localIPs includes at most one IPv4 address and one IPv6 address. For each device in linkList, all its addresses
// are compared with IPs in localIPs. If found, the iface is set to the device and v4IPNet, v6IPNet are set to
// the matching addresses.
saveIface := func(current *net.Interface) error {
if iface != nil && iface.Index != current.Index {
return fmt.Errorf("IPs of localIPs should be on the same device")
}
iface = current
return nil
}
for i := range linkList {
link := linkList[i]
if ignoredInterfaces.Has(link.Name) {
continue
}
addrList, err := link.Addrs()
if err != nil {
continue
}
for _, addr := range addrList {
if ipNet, ok := addr.(*net.IPNet); ok {
if ipNet.IP.Equal(localIPs.IPv4) {
if err := saveIface(&link); err != nil {
return nil, nil, nil, err
}
v4IPNet = ipNet
} else if ipNet.IP.Equal(localIPs.IPv6) {
if err := saveIface(&link); err != nil {
return nil, nil, nil, err
}
v6IPNet = ipNet
}
}
}
}
if iface == nil {
return nil, nil, nil, fmt.Errorf("unable to find local IPs and device")
}
return v4IPNet, v6IPNet, iface, nil
}
func GetIPNetDeviceByName(ifaceName string) (v4IPNet *net.IPNet, v6IPNet *net.IPNet, link *net.Interface, err error) {
link, err = net.InterfaceByName(ifaceName)
if err != nil {
return nil, nil, nil, err
}
addrList, err := link.Addrs()
if err != nil {
return nil, nil, nil, err
}
for _, addr := range addrList {
if ipNet, ok := addr.(*net.IPNet); ok {
if ipNet.IP.IsGlobalUnicast() {
if ipNet.IP.To4() != nil {
if v4IPNet == nil {
v4IPNet = ipNet
}
} else if v6IPNet == nil {
v6IPNet = ipNet
}
}
}
}
if v4IPNet != nil || v6IPNet != nil {
return v4IPNet, v6IPNet, link, nil
}
return nil, nil, nil, fmt.Errorf("unable to find local IP and device")
}
func GetIPNetDeviceByCIDRs(cidrsList []string) (v4IPNet, v6IPNet *net.IPNet, link *net.Interface, err error) {
cidrs, err := utilnet.ParseCIDRs(cidrsList)
if err != nil {
return nil, nil, nil, err
}
dualStack, err := utilnet.IsDualStackCIDRs(cidrs)
if err != nil {
return nil, nil, nil, err
}
if len(cidrs) > 1 && !dualStack {
return nil, nil, nil, fmt.Errorf("len of cidrs is %v and they are not configured as dual stack (at least one from each IPFamily)", len(cidrs))
}
if len(cidrs) > 2 {
return nil, nil, nil, fmt.Errorf("length of cidrs is %v more than max allowed of 2", len(cidrs))
}
ifaces, err := net.Interfaces()
if err != nil {
return nil, nil, nil, err
}
for _, i := range ifaces {
addresses, err := i.Addrs()
if err != nil {
return nil, nil, nil, err
}
for _, addr := range addresses {
ipNet, ok := addr.(*net.IPNet)
if !ok || !ipNet.IP.IsGlobalUnicast() {
continue
}
for _, cidr := range cidrs {
if !cidr.Contains(ipNet.IP) {
continue
}
if v4IPNet == nil && ipNet.IP.To4() != nil {
v4IPNet = ipNet
} else if v6IPNet == nil && ipNet.IP.To4() == nil {
v6IPNet = ipNet
}
}
}
if v4IPNet != nil || v6IPNet != nil {
return v4IPNet, v6IPNet, &i, nil
}
}
return nil, nil, nil, fmt.Errorf("unable to find local IP and device")
}
func GetAllIPNetsByName(ifaceName string) ([]*net.IPNet, error) {
ips := []*net.IPNet{}
adapter, err := net.InterfaceByName(ifaceName)
if err != nil {
return nil, err
}
addrs, _ := adapter.Addrs()
for _, addr := range addrs {
if ip, ipNet, err := net.ParseCIDR(addr.String()); err != nil {
klog.Warningf("Unable to parse addr %+v, err=%+v", addr, err)
} else if !ip.IsLinkLocalUnicast() {
ipNet.IP = ip
ips = append(ips, ipNet)
}
}
klog.InfoS("Found IPs on interface", "IPs", ips, "interface", ifaceName)
return ips, nil
}
func GetIPv4Addr(ips []net.IP) net.IP {
for _, ip := range ips {
if ip.To4() != nil {
return ip
}
}
return nil
}
func GetIPWithFamily(ips []net.IP, addrFamily uint8) (net.IP, error) {
if addrFamily == FamilyIPv6 {
for _, ip := range ips {
if ip.To4() == nil {
return ip, nil
}
}
return nil, errors.New("no IP found with IPv6 AddressFamily")
}
for _, ip := range ips {
if ip.To4() != nil {
return ip, nil
}
}
return nil, errors.New("no IP found with IPv4 AddressFamily")
}
// ExtendCIDRWithIP is used for extending an IPNet with an IP.
func ExtendCIDRWithIP(ipNet *net.IPNet, ip net.IP) (*net.IPNet, error) {
cpl := longestCommonPrefixLen(ipNet.IP, ip)
if cpl == 0 {
return nil, fmt.Errorf("invalid common prefix length")
}
_, newIPNet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", ipNet.IP.String(), cpl))
if err != nil {
return nil, err
}
return newIPNet, nil
}
// This is copied from func commonPrefixLen in net/addrselect.go and modified:
// - Replace argument type IP with argument type net.IP.
// - Remove the prefix limit (64 bits) for IPv6.
func longestCommonPrefixLen(a, b net.IP) (cpl int) {
if a4 := a.To4(); a4 != nil {
a = a4
}
if b4 := b.To4(); b4 != nil {
b = b4
}
if len(a) != len(b) {
return 0
}
for len(a) > 0 {
if a[0] == b[0] {
cpl += 8
a = a[1:]
b = b[1:]
continue
}
bits := 8
ab, bb := a[0], b[0]
for {
ab >>= 1
bb >>= 1
bits--
if ab == bb {
cpl += bits
return
}
}
}
return
}
// GetAllNodeAddresses gets all Node IP addresses (not including IPv6 link local address).
func GetAllNodeAddresses(excludeDevices []string) ([]net.IP, []net.IP, error) {
var nodeAddressesIPv4, nodeAddressesIPv6 []net.IP
_, ipv6LinkLocalNet, _ := net.ParseCIDR("fe80::/64")
// Get all interfaces.
interfaces, err := net.Interfaces()
if err != nil {
return nil, nil, err
}
// Transform excludeDevices to a set
excludeDevicesSet := sets.NewString(excludeDevices...)
for _, itf := range interfaces {
// If the device is in excludeDevicesSet, skip it.
if excludeDevicesSet.Has(itf.Name) {
continue
}
// Get all IPs of every interface
addrs, err := itf.Addrs()
if err != nil {
return nil, nil, err
}
for _, addr := range addrs {
ip, _, _ := net.ParseCIDR(addr.String())
if ipv6LinkLocalNet.Contains(ip) {
continue // Skip IPv6 link local address
}
if ip.To4() != nil {
nodeAddressesIPv4 = append(nodeAddressesIPv4, ip)
} else {
nodeAddressesIPv6 = append(nodeAddressesIPv6, ip)
}
}
}
return nodeAddressesIPv4, nodeAddressesIPv6, nil
}
// Copied from github.com/vishvananda/netlink/netlink.go
// NewIPNet generates an IPNet from an ip address using a netmask of 32 or 128.
func NewIPNet(ip net.IP) *net.IPNet {
if ip.To4() != nil {
return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
}
return &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}
}
func PortToUint16(port int) uint16 {
if port > 0 && port <= math.MaxUint16 {
return uint16(port) // lgtm[go/incorrect-integer-conversion]
}
klog.Errorf("Port value %d out-of-bounds", port)
return 0
}
// GenerateUplinkInterfaceName generates the uplink interface name after bridged to OVS
func GenerateUplinkInterfaceName(name string) string {
return name + bridgedUplinkSuffix
}
func GenerateRandomMAC() net.HardwareAddr {
buf := make([]byte, 6)
if _, err := rand.Read(buf); err != nil {
klog.ErrorS(err, "Failed to generate a random MAC")
}
// Set the local bit
buf[0] |= 2
return buf
}
func GetIPNetsByLink(link *net.Interface) ([]*net.IPNet, error) {
addrList, err := link.Addrs()
if err != nil {
return nil, err
}
var addrs []*net.IPNet
for _, a := range addrList {
if ipNet, ok := a.(*net.IPNet); ok {
addrs = append(addrs, ipNet)
}
}
return addrs, nil
}