Debian Codegraph @

pkg/utils/conntrack.go

raw symbols SCIP
1 // Copyright 2020 CNI authors
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 utils
16
17 import (
18 "fmt"
19 "net"
20
21 "github.com/vishvananda/netlink"
22 "golang.org/x/sys/unix"
23
24 "github.com/containernetworking/plugins/pkg/netlinksafe"
25 )
26
27 // Assigned Internet Protocol Numbers
28 // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
29 const (
30 PROTOCOL_TCP = 6
31 PROTOCOL_UDP = 17
32 PROTOCOL_SCTP = 132
33 )
34
35 // getNetlinkFamily returns the Netlink IP family constant
36 func getNetlinkFamily(isIPv6 bool) netlink.InetFamily {
37 if isIPv6 {
38 return unix.AF_INET6
39 }
40 return unix.AF_INET
41 }
42
43 // DeleteConntrackEntriesForDstIP delete the conntrack entries for the connections
44 // specified by the given destination IP and protocol
45 func DeleteConntrackEntriesForDstIP(dstIP string, protocol uint8) error {
46 ip := net.ParseIP(dstIP)
47 if ip == nil {
48 return fmt.Errorf("error deleting connection tracking state, bad IP %s", ip)
49 }
50 family := getNetlinkFamily(ip.To4() == nil)
51
52 filter := &netlink.ConntrackFilter{}
53 filter.AddIP(netlink.ConntrackOrigDstIP, ip)
54 filter.AddProtocol(protocol)
55
56 _, err := netlinksafe.ConntrackDeleteFilters(netlink.ConntrackTable, family, filter)
57 if err != nil {
58 return fmt.Errorf("error deleting connection tracking state for protocol: %d IP: %s, error: %v", protocol, ip, err)
59 }
60 return nil
61 }
62
63 // DeleteConntrackEntriesForDstPort delete the conntrack entries for the connections specified
64 // by the given destination port, protocol and IP family
65 func DeleteConntrackEntriesForDstPort(port uint16, protocol uint8, family netlink.InetFamily) error {
66 filter := &netlink.ConntrackFilter{}
67 filter.AddProtocol(protocol)
68 filter.AddPort(netlink.ConntrackOrigDstPort, port)
69
70 _, err := netlinksafe.ConntrackDeleteFilters(netlink.ConntrackTable, family, filter)
71 if err != nil {
72 return fmt.Errorf("error deleting connection tracking state for protocol: %d Port: %d, error: %v", protocol, port, err)
73 }
74 return nil
75 }