Debian Codegraph @

pkg/ip/link_linux.go

raw symbols SCIP
1 // Copyright 2015 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 ip
16
17 import (
18 "crypto/rand"
19 "errors"
20 "fmt"
21 "net"
22 "os"
23
24 "github.com/safchain/ethtool"
25 "github.com/vishvananda/netlink"
26
27 "github.com/containernetworking/plugins/pkg/netlinksafe"
28 "github.com/containernetworking/plugins/pkg/ns"
29 "github.com/containernetworking/plugins/pkg/utils/sysctl"
30 )
31
32 var ErrLinkNotFound = errors.New("link not found")
33
34 // makeVethPair is called from within the container's network namespace
35 func makeVethPair(name, peer string, mtu int, mac string, hostNS ns.NetNS) (netlink.Link, error) {
36 linkAttrs := netlink.NewLinkAttrs()
37 linkAttrs.Name = name
38 linkAttrs.MTU = mtu
39
40 veth := &netlink.Veth{
41 LinkAttrs: linkAttrs,
42 PeerName: peer,
43 PeerNamespace: netlink.NsFd(int(hostNS.Fd())),
44 }
45 if mac != "" {
46 m, err := net.ParseMAC(mac)
47 if err != nil {
48 return nil, err
49 }
50 veth.LinkAttrs.HardwareAddr = m
51 }
52 if err := netlink.LinkAdd(veth); err != nil {
53 return nil, err
54 }
55 // Re-fetch the container link to get its creation-time parameters, e.g. index and mac
56 veth2, err := netlinksafe.LinkByName(name)
57 if err != nil {
58 netlink.LinkDel(veth) // try and clean up the link if possible.
59 return nil, err
60 }
61
62 return veth2, nil
63 }
64
65 func peerExists(name string) bool {
66 if _, err := netlinksafe.LinkByName(name); err != nil {
67 return false
68 }
69 return true
70 }
71
72 func makeVeth(name, vethPeerName string, mtu int, mac string, hostNS ns.NetNS) (string, netlink.Link, error) {
73 var peerName string
74 var veth netlink.Link
75 var err error
76 for i := 0; i < 10; i++ {
77 if vethPeerName != "" {
78 peerName = vethPeerName
79 } else {
80 peerName, err = RandomVethName()
81 if err != nil {
82 return peerName, nil, err
83 }
84 }
85
86 veth, err = makeVethPair(name, peerName, mtu, mac, hostNS)
87 switch {
88 case err == nil:
89 return peerName, veth, nil
90
91 case os.IsExist(err):
92 if peerExists(peerName) && vethPeerName == "" {
93 continue
94 }
95 return peerName, veth, fmt.Errorf("container veth name (%q) peer provided (%q) already exists", name, peerName)
96 default:
97 return peerName, veth, fmt.Errorf("failed to make veth pair: %v", err)
98 }
99 }
100
101 // should really never be hit
102 return peerName, nil, fmt.Errorf("failed to find a unique veth name")
103 }
104
105 // RandomVethName returns string "veth" with random prefix (hashed from entropy)
106 func RandomVethName() (string, error) {
107 entropy := make([]byte, 4)
108 _, err := rand.Read(entropy)
109 if err != nil {
110 return "", fmt.Errorf("failed to generate random veth name: %v", err)
111 }
112
113 // NetworkManager (recent versions) will ignore veth devices that start with "veth"
114 return fmt.Sprintf("veth%x", entropy), nil
115 }
116
117 func RenameLink(curName, newName string) error {
118 link, err := netlinksafe.LinkByName(curName)
119 if err == nil {
120 err = netlink.LinkSetName(link, newName)
121 }
122 return err
123 }
124
125 func ifaceFromNetlinkLink(l netlink.Link) net.Interface {
126 a := l.Attrs()
127 return net.Interface{
128 Index: a.Index,
129 MTU: a.MTU,
130 Name: a.Name,
131 HardwareAddr: a.HardwareAddr,
132 Flags: a.Flags,
133 }
134 }
135
136 // SetupVethWithName sets up a pair of virtual ethernet devices.
137 // Call SetupVethWithName from inside the container netns. It will create both veth
138 // devices and move the host-side veth into the provided hostNS namespace.
139 // hostVethName: If hostVethName is not specified, the host-side veth name will use a random string.
140 // On success, SetupVethWithName returns (hostVeth, containerVeth, nil)
141 func SetupVethWithName(contVethName, hostVethName string, mtu int, contVethMac string, hostNS ns.NetNS) (net.Interface, net.Interface, error) {
142 hostVethName, contVeth, err := makeVeth(contVethName, hostVethName, mtu, contVethMac, hostNS)
143 if err != nil {
144 return net.Interface{}, net.Interface{}, err
145 }
146
147 var hostVeth netlink.Link
148 err = hostNS.Do(func(_ ns.NetNS) error {
149 hostVeth, err = netlinksafe.LinkByName(hostVethName)
150 if err != nil {
151 return fmt.Errorf("failed to lookup %q in %q: %v", hostVethName, hostNS.Path(), err)
152 }
153
154 if err = netlink.LinkSetUp(hostVeth); err != nil {
155 return fmt.Errorf("failed to set %q up: %v", hostVethName, err)
156 }
157
158 // we want to own the routes for this interface
159 _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv6/conf/%s/accept_ra", hostVethName), "0")
160 return nil
161 })
162 if err != nil {
163 return net.Interface{}, net.Interface{}, err
164 }
165 return ifaceFromNetlinkLink(hostVeth), ifaceFromNetlinkLink(contVeth), nil
166 }
167
168 // SetupVeth sets up a pair of virtual ethernet devices.
169 // Call SetupVeth from inside the container netns. It will create both veth
170 // devices and move the host-side veth into the provided hostNS namespace.
171 // On success, SetupVeth returns (hostVeth, containerVeth, nil)
172 func SetupVeth(contVethName string, mtu int, contVethMac string, hostNS ns.NetNS) (net.Interface, net.Interface, error) {
173 return SetupVethWithName(contVethName, "", mtu, contVethMac, hostNS)
174 }
175
176 // DelLinkByName removes an interface link.
177 func DelLinkByName(ifName string) error {
178 iface, err := netlinksafe.LinkByName(ifName)
179 if err != nil {
180 if _, ok := err.(netlink.LinkNotFoundError); ok {
181 return ErrLinkNotFound
182 }
183 return fmt.Errorf("failed to lookup %q: %v", ifName, err)
184 }
185
186 if err = netlink.LinkDel(iface); err != nil {
187 return fmt.Errorf("failed to delete %q: %v", ifName, err)
188 }
189
190 return nil
191 }
192
193 // DelLinkByNameAddr remove an interface and returns its addresses
194 func DelLinkByNameAddr(ifName string) ([]*net.IPNet, error) {
195 iface, err := netlinksafe.LinkByName(ifName)
196 if err != nil {
197 if _, ok := err.(netlink.LinkNotFoundError); ok {
198 return nil, ErrLinkNotFound
199 }
200 return nil, fmt.Errorf("failed to lookup %q: %v", ifName, err)
201 }
202
203 addrs, err := netlinksafe.AddrList(iface, netlink.FAMILY_ALL)
204 if err != nil {
205 return nil, fmt.Errorf("failed to get IP addresses for %q: %v", ifName, err)
206 }
207
208 if err = netlink.LinkDel(iface); err != nil {
209 return nil, fmt.Errorf("failed to delete %q: %v", ifName, err)
210 }
211
212 out := []*net.IPNet{}
213 for _, addr := range addrs {
214 if addr.IP.IsGlobalUnicast() {
215 out = append(out, addr.IPNet)
216 }
217 }
218
219 return out, nil
220 }
221
222 // GetVethPeerIfindex returns the veth link object, the peer ifindex of the
223 // veth, or an error. This peer ifindex will only be valid in the peer's
224 // network namespace.
225 func GetVethPeerIfindex(ifName string) (netlink.Link, int, error) {
226 link, err := netlinksafe.LinkByName(ifName)
227 if err != nil {
228 return nil, -1, fmt.Errorf("could not look up %q: %v", ifName, err)
229 }
230 if _, ok := link.(*netlink.Veth); !ok {
231 return nil, -1, fmt.Errorf("interface %q was not a veth interface", ifName)
232 }
233
234 // veth supports IFLA_LINK (what vishvananda/netlink calls ParentIndex)
235 // on 4.1 and higher kernels
236 peerIndex := link.Attrs().ParentIndex
237 if peerIndex <= 0 {
238 // Fall back to ethtool for 4.0 and earlier kernels
239 e, err := ethtool.NewEthtool()
240 if err != nil {
241 return nil, -1, fmt.Errorf("failed to initialize ethtool: %v", err)
242 }
243 defer e.Close()
244
245 stats, err := e.Stats(link.Attrs().Name)
246 if err != nil {
247 return nil, -1, fmt.Errorf("failed to request ethtool stats: %v", err)
248 }
249 n, ok := stats["peer_ifindex"]
250 if !ok {
251 return nil, -1, fmt.Errorf("failed to find 'peer_ifindex' in ethtool stats")
252 }
253 if n > 32767 || n == 0 {
254 return nil, -1, fmt.Errorf("invalid 'peer_ifindex' %d", n)
255 }
256 peerIndex = int(n)
257 }
258
259 return link, peerIndex, nil
260 }