github.com/imran-kn/cilium-fork@v1.6.9/pkg/bpf/endpoint.go (about) 1 // Copyright 2016-2019 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package bpf 16 17 import ( 18 "fmt" 19 "net" 20 "unsafe" 21 22 "github.com/cilium/cilium/common/types" 23 ) 24 25 // Must be in sync with ENDPOINT_KEY_* in <bpf/lib/common.h> 26 const ( 27 EndpointKeyIPv4 uint8 = 1 28 EndpointKeyIPv6 uint8 = 2 29 ) 30 31 // EndpointKey represents the key value of the endpoints BPF map 32 // 33 // Must be in sync with struct endpoint_key in <bpf/lib/common.h> 34 // +k8s:deepcopy-gen=true 35 type EndpointKey struct { 36 // represents both IPv6 and IPv4 (in the lowest four bytes) 37 IP types.IPv6 `align:"$union0"` 38 Family uint8 `align:"family"` 39 Key uint8 `align:"key"` 40 Pad2 uint16 `align:"pad5"` 41 } 42 43 // GetKeyPtr returns the unsafe pointer to the BPF key 44 func (k *EndpointKey) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) } 45 46 // GetValuePtr returns the unsafe pointer to the BPF key for users that 47 // use EndpointKey as a value in bpf maps 48 func (k *EndpointKey) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(k) } 49 50 // NewEndpointKey returns an EndpointKey based on the provided IP address. The 51 // address family is automatically detected. 52 func NewEndpointKey(ip net.IP) EndpointKey { 53 result := EndpointKey{} 54 55 if ip4 := ip.To4(); ip4 != nil { 56 result.Family = EndpointKeyIPv4 57 copy(result.IP[:], ip4) 58 } else { 59 result.Family = EndpointKeyIPv6 60 copy(result.IP[:], ip) 61 } 62 result.Key = 0 63 64 return result 65 } 66 67 // ToIP converts the EndpointKey into a net.IP structure. 68 func (k EndpointKey) ToIP() net.IP { 69 switch k.Family { 70 case EndpointKeyIPv4: 71 return k.IP[:4] 72 case EndpointKeyIPv6: 73 return k.IP[:] 74 } 75 return nil 76 } 77 78 // String provides a string representation of the EndpointKey. 79 func (k EndpointKey) String() string { 80 if ip := k.ToIP(); ip != nil { 81 return fmt.Sprintf("%s:%d", ip.String(), k.Key) 82 } 83 return "nil" 84 }