Update github.com/vishvananda/netlink to v1.1.0

Latest version allows to set a VRF device as master and not only
a bridge one.

Signed-off-by: Federico Paolinelli <fpaoline@redhat.com>
This commit is contained in:
Federico Paolinelli
2020-09-04 16:33:07 +02:00
parent 8d0d8a9547
commit 362f5d626a
271 changed files with 25100 additions and 90453 deletions

1
vendor/github.com/vishvananda/netlink/.gitignore generated vendored Normal file
View File

@ -0,0 +1 @@
.idea/

View File

@ -2,6 +2,7 @@ language: go
go:
- "1.10.x"
- "1.11.x"
- "1.12.x"
before_script:
# make sure we keep path in tact when we sudo
- sudo sed -i -e 's/^Defaults\tsecure_path.*$//' /etc/sudoers
@ -15,3 +16,4 @@ before_script:
- sudo modprobe sch_hfsc
install:
- go get github.com/vishvananda/netns
go_import_path: github.com/vishvananda/netlink

View File

@ -15,39 +15,62 @@ import (
const IFA_FLAGS = 0x8
// AddrAdd will add an IP address to a link device.
//
// Equivalent to: `ip addr add $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func AddrAdd(link Link, addr *Addr) error {
return pkgHandle.AddrAdd(link, addr)
}
// AddrAdd will add an IP address to a link device.
//
// Equivalent to: `ip addr add $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func (h *Handle) AddrAdd(link Link, addr *Addr) error {
req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
return h.addrHandle(link, addr, req)
}
// AddrReplace will replace (or, if not present, add) an IP address on a link device.
//
// Equivalent to: `ip addr replace $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func AddrReplace(link Link, addr *Addr) error {
return pkgHandle.AddrReplace(link, addr)
}
// AddrReplace will replace (or, if not present, add) an IP address on a link device.
//
// Equivalent to: `ip addr replace $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func (h *Handle) AddrReplace(link Link, addr *Addr) error {
req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_REPLACE|unix.NLM_F_ACK)
return h.addrHandle(link, addr, req)
}
// AddrDel will delete an IP address from a link device.
//
// Equivalent to: `ip addr del $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func AddrDel(link Link, addr *Addr) error {
return pkgHandle.AddrDel(link, addr)
}
// AddrDel will delete an IP address from a link device.
// Equivalent to: `ip addr del $addr dev $link`
//
// If `addr` is an IPv4 address and the broadcast address is not given, it
// will be automatically computed based on the IP mask if /30 or larger.
func (h *Handle) AddrDel(link Link, addr *Addr) error {
req := h.newNetlinkRequest(unix.RTM_DELADDR, unix.NLM_F_ACK)
return h.addrHandle(link, addr, req)
@ -108,14 +131,20 @@ func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error
}
if family == FAMILY_V4 {
if addr.Broadcast == nil {
// Automatically set the broadcast address if it is unset and the
// subnet is large enough to sensibly have one (/30 or larger).
// See: RFC 3021
if addr.Broadcast == nil && prefixlen < 31 {
calcBroadcast := make(net.IP, masklen/8)
for i := range localAddrData {
calcBroadcast[i] = localAddrData[i] | ^mask[i]
}
addr.Broadcast = calcBroadcast
}
req.AddData(nl.NewRtAttr(unix.IFA_BROADCAST, addr.Broadcast))
if addr.Broadcast != nil {
req.AddData(nl.NewRtAttr(unix.IFA_BROADCAST, addr.Broadcast))
}
if addr.Label != "" {
labelData := nl.NewRtAttr(unix.IFA_LABEL, nl.ZeroTerminated(addr.Label))
@ -270,21 +299,22 @@ type AddrUpdate struct {
// AddrSubscribe takes a chan down which notifications will be sent
// when addresses change. Close the 'done' chan to stop subscription.
func AddrSubscribe(ch chan<- AddrUpdate, done <-chan struct{}) error {
return addrSubscribeAt(netns.None(), netns.None(), ch, done, nil, false)
return addrSubscribeAt(netns.None(), netns.None(), ch, done, nil, false, 0)
}
// AddrSubscribeAt works like AddrSubscribe plus it allows the caller
// to choose the network namespace in which to subscribe (ns).
func AddrSubscribeAt(ns netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}) error {
return addrSubscribeAt(ns, netns.None(), ch, done, nil, false)
return addrSubscribeAt(ns, netns.None(), ch, done, nil, false, 0)
}
// AddrSubscribeOptions contains a set of options to use with
// AddrSubscribeWithOptions.
type AddrSubscribeOptions struct {
Namespace *netns.NsHandle
ErrorCallback func(error)
ListExisting bool
Namespace *netns.NsHandle
ErrorCallback func(error)
ListExisting bool
ReceiveBufferSize int
}
// AddrSubscribeWithOptions work like AddrSubscribe but enable to
@ -295,10 +325,10 @@ func AddrSubscribeWithOptions(ch chan<- AddrUpdate, done <-chan struct{}, option
none := netns.None()
options.Namespace = &none
}
return addrSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting)
return addrSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting, options.ReceiveBufferSize)
}
func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error {
func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}, cberr func(error), listExisting bool, rcvbuf int) error {
s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_IPV4_IFADDR, unix.RTNLGRP_IPV6_IFADDR)
if err != nil {
return err
@ -309,6 +339,12 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
s.Close()
}()
}
if rcvbuf != 0 {
err = pkgHandle.SetSocketReceiveBufferSize(rcvbuf, false)
if err != nil {
return err
}
}
if listExisting {
req := pkgHandle.newNetlinkRequest(unix.RTM_GETADDR,
unix.NLM_F_DUMP)
@ -321,13 +357,19 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
go func() {
defer close(ch)
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
if cberr != nil {
cberr(err)
}
return
}
if from.Pid != nl.PidKernel {
if cberr != nil {
cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel))
}
continue
}
for _, m := range msgs {
if m.Header.Type == unix.NLMSG_DONE {
continue
@ -339,16 +381,17 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
continue
}
if cberr != nil {
cberr(syscall.Errno(-error))
cberr(fmt.Errorf("error message: %v",
syscall.Errno(-error)))
}
return
continue
}
msgType := m.Header.Type
if msgType != unix.RTM_NEWADDR && msgType != unix.RTM_DELADDR {
if cberr != nil {
cberr(fmt.Errorf("bad message type: %d", msgType))
}
return
continue
}
addr, _, ifindex, err := parseAddr(m.Data)
@ -356,7 +399,7 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
if cberr != nil {
cberr(fmt.Errorf("could not parse address: %v", err))
}
return
continue
}
ch <- AddrUpdate{LinkAddress: *addr.IPNet,

View File

@ -108,8 +108,5 @@ func (h *Handle) bridgeVlanModify(cmd int, link Link, vid uint16, pvid, untagged
br.AddRtAttr(nl.IFLA_BRIDGE_VLAN_INFO, vlanInfo.Serialize())
req.AddData(br)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil {
return err
}
return nil
return err
}

View File

@ -41,7 +41,7 @@ type GnetStatsQueue struct {
Overlimits uint32 // number of enqueues over the limit
}
// ClassStatistics representaion based on generic networking statisticsfor netlink.
// ClassStatistics representation based on generic networking statistics for netlink.
// See Documentation/networking/gen_stats.txt in Linux source code for more details.
type ClassStatistics struct {
Basic *GnetStatsBasic
@ -127,7 +127,7 @@ func (class *GenericClass) Attrs() *ClassAttrs {
return &class.ClassAttrs
}
// Type retrun the class type
// Type return the class type
func (class *GenericClass) Type() string {
return class.ClassType
}
@ -178,7 +178,7 @@ func (hfsc *HfscClass) SetUL(m1 uint32, d uint32, m2 uint32) {
hfsc.Usc = ServiceCurve{m1: m1 / 8, d: d, m2: m2 / 8}
}
// SetLS implemtens the LS from the tc CLI
// SetLS implements the LS from the tc CLI
func (hfsc *HfscClass) SetLS(m1 uint32, d uint32, m2 uint32) {
hfsc.Fsc = ServiceCurve{m1: m1 / 8, d: d, m2: m2 / 8}
}

View File

@ -22,11 +22,7 @@ const (
// https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink.h -> #define NFNL_SUBSYS_CTNETLINK_EXP 2
ConntrackExpectTable = 2
)
const (
// For Parsing Mark
TCP_PROTO = 6
UDP_PROTO = 17
)
const (
// backward compatibility with golang 1.6 which does not have io.SeekCurrent
seekCurrent = 1
@ -223,6 +219,10 @@ func parseBERaw16(r *bytes.Reader, v *uint16) {
binary.Read(r, binary.BigEndian, v)
}
func parseBERaw32(r *bytes.Reader, v *uint32) {
binary.Read(r, binary.BigEndian, v)
}
func parseBERaw64(r *bytes.Reader, v *uint64) {
binary.Read(r, binary.BigEndian, v)
}
@ -241,9 +241,13 @@ func parseByteAndPacketCounters(r *bytes.Reader) (bytes, packets uint64) {
return
}
func parseConnectionMark(r *bytes.Reader) (mark uint32) {
parseBERaw32(r, &mark)
return
}
func parseRawData(data []byte) *ConntrackFlow {
s := &ConntrackFlow{}
var proto uint8
// First there is the Nfgenmsg header
// consume only the family field
reader := bytes.NewReader(data)
@ -263,7 +267,7 @@ func parseRawData(data []byte) *ConntrackFlow {
switch t {
case nl.CTA_TUPLE_ORIG:
if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP {
proto = parseIpTuple(reader, &s.Forward)
parseIpTuple(reader, &s.Forward)
}
case nl.CTA_TUPLE_REPLY:
if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP {
@ -277,19 +281,11 @@ func parseRawData(data []byte) *ConntrackFlow {
case nl.CTA_COUNTERS_REPLY:
s.Reverse.Bytes, s.Reverse.Packets = parseByteAndPacketCounters(reader)
}
}
}
if proto == TCP_PROTO {
reader.Seek(64, seekCurrent)
_, t, _, v := parseNfAttrTLV(reader)
if t == nl.CTA_MARK {
s.Mark = uint32(v[3])
}
} else if proto == UDP_PROTO {
reader.Seek(16, seekCurrent)
_, t, _, v := parseNfAttrTLV(reader)
if t == nl.CTA_MARK {
s.Mark = uint32(v[3])
} else {
switch t {
case nl.CTA_MARK:
s.Mark = parseConnectionMark(reader)
}
}
}
return s

272
vendor/github.com/vishvananda/netlink/devlink_linux.go generated vendored Normal file
View File

@ -0,0 +1,272 @@
package netlink
import (
"syscall"
"fmt"
"github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
)
// DevlinkDevEswitchAttr represents device's eswitch attributes
type DevlinkDevEswitchAttr struct {
Mode string
InlineMode string
EncapMode string
}
// DevlinkDevAttrs represents device attributes
type DevlinkDevAttrs struct {
Eswitch DevlinkDevEswitchAttr
}
// DevlinkDevice represents device and its attributes
type DevlinkDevice struct {
BusName string
DeviceName string
Attrs DevlinkDevAttrs
}
func parseDevLinkDeviceList(msgs [][]byte) ([]*DevlinkDevice, error) {
devices := make([]*DevlinkDevice, 0, len(msgs))
for _, m := range msgs {
attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:])
if err != nil {
return nil, err
}
dev := &DevlinkDevice{}
if err = dev.parseAttributes(attrs); err != nil {
return nil, err
}
devices = append(devices, dev)
}
return devices, nil
}
func eswitchStringToMode(modeName string) (uint16, error) {
if modeName == "legacy" {
return nl.DEVLINK_ESWITCH_MODE_LEGACY, nil
} else if modeName == "switchdev" {
return nl.DEVLINK_ESWITCH_MODE_SWITCHDEV, nil
} else {
return 0xffff, fmt.Errorf("invalid switchdev mode")
}
}
func parseEswitchMode(mode uint16) string {
var eswitchMode = map[uint16]string{
nl.DEVLINK_ESWITCH_MODE_LEGACY: "legacy",
nl.DEVLINK_ESWITCH_MODE_SWITCHDEV: "switchdev",
}
if eswitchMode[mode] == "" {
return "unknown"
} else {
return eswitchMode[mode]
}
}
func parseEswitchInlineMode(inlinemode uint8) string {
var eswitchInlineMode = map[uint8]string{
nl.DEVLINK_ESWITCH_INLINE_MODE_NONE: "none",
nl.DEVLINK_ESWITCH_INLINE_MODE_LINK: "link",
nl.DEVLINK_ESWITCH_INLINE_MODE_NETWORK: "network",
nl.DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT: "transport",
}
if eswitchInlineMode[inlinemode] == "" {
return "unknown"
} else {
return eswitchInlineMode[inlinemode]
}
}
func parseEswitchEncapMode(encapmode uint8) string {
var eswitchEncapMode = map[uint8]string{
nl.DEVLINK_ESWITCH_ENCAP_MODE_NONE: "disable",
nl.DEVLINK_ESWITCH_ENCAP_MODE_BASIC: "enable",
}
if eswitchEncapMode[encapmode] == "" {
return "unknown"
} else {
return eswitchEncapMode[encapmode]
}
}
func (d *DevlinkDevice) parseAttributes(attrs []syscall.NetlinkRouteAttr) error {
for _, a := range attrs {
switch a.Attr.Type {
case nl.DEVLINK_ATTR_BUS_NAME:
d.BusName = string(a.Value)
case nl.DEVLINK_ATTR_DEV_NAME:
d.DeviceName = string(a.Value)
case nl.DEVLINK_ATTR_ESWITCH_MODE:
d.Attrs.Eswitch.Mode = parseEswitchMode(native.Uint16(a.Value))
case nl.DEVLINK_ATTR_ESWITCH_INLINE_MODE:
d.Attrs.Eswitch.InlineMode = parseEswitchInlineMode(uint8(a.Value[0]))
case nl.DEVLINK_ATTR_ESWITCH_ENCAP_MODE:
d.Attrs.Eswitch.EncapMode = parseEswitchEncapMode(uint8(a.Value[0]))
}
}
return nil
}
func (dev *DevlinkDevice) parseEswitchAttrs(msgs [][]byte) {
m := msgs[0]
attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:])
if err != nil {
return
}
dev.parseAttributes(attrs)
}
func (h *Handle) getEswitchAttrs(family *GenlFamily, dev *DevlinkDevice) {
msg := &nl.Genlmsg{
Command: nl.DEVLINK_CMD_ESWITCH_GET,
Version: nl.GENL_DEVLINK_VERSION,
}
req := h.newNetlinkRequest(int(family.ID), unix.NLM_F_REQUEST|unix.NLM_F_ACK)
req.AddData(msg)
b := make([]byte, len(dev.BusName))
copy(b, dev.BusName)
data := nl.NewRtAttr(nl.DEVLINK_ATTR_BUS_NAME, b)
req.AddData(data)
b = make([]byte, len(dev.DeviceName))
copy(b, dev.DeviceName)
data = nl.NewRtAttr(nl.DEVLINK_ATTR_DEV_NAME, b)
req.AddData(data)
msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil {
return
}
dev.parseEswitchAttrs(msgs)
}
// DevLinkGetDeviceList provides a pointer to devlink devices and nil error,
// otherwise returns an error code.
func (h *Handle) DevLinkGetDeviceList() ([]*DevlinkDevice, error) {
f, err := h.GenlFamilyGet(nl.GENL_DEVLINK_NAME)
if err != nil {
return nil, err
}
msg := &nl.Genlmsg{
Command: nl.DEVLINK_CMD_GET,
Version: nl.GENL_DEVLINK_VERSION,
}
req := h.newNetlinkRequest(int(f.ID),
unix.NLM_F_REQUEST|unix.NLM_F_ACK|unix.NLM_F_DUMP)
req.AddData(msg)
msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil {
return nil, err
}
devices, err := parseDevLinkDeviceList(msgs)
if err != nil {
return nil, err
}
for _, d := range devices {
h.getEswitchAttrs(f, d)
}
return devices, nil
}
// DevLinkGetDeviceList provides a pointer to devlink devices and nil error,
// otherwise returns an error code.
func DevLinkGetDeviceList() ([]*DevlinkDevice, error) {
return pkgHandle.DevLinkGetDeviceList()
}
func parseDevlinkDevice(msgs [][]byte) (*DevlinkDevice, error) {
m := msgs[0]
attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:])
if err != nil {
return nil, err
}
dev := &DevlinkDevice{}
if err = dev.parseAttributes(attrs); err != nil {
return nil, err
}
return dev, nil
}
func (h *Handle) createCmdReq(cmd uint8, bus string, device string) (*GenlFamily, *nl.NetlinkRequest, error) {
f, err := h.GenlFamilyGet(nl.GENL_DEVLINK_NAME)
if err != nil {
return nil, nil, err
}
msg := &nl.Genlmsg{
Command: cmd,
Version: nl.GENL_DEVLINK_VERSION,
}
req := h.newNetlinkRequest(int(f.ID),
unix.NLM_F_REQUEST|unix.NLM_F_ACK)
req.AddData(msg)
b := make([]byte, len(bus)+1)
copy(b, bus)
data := nl.NewRtAttr(nl.DEVLINK_ATTR_BUS_NAME, b)
req.AddData(data)
b = make([]byte, len(device)+1)
copy(b, device)
data = nl.NewRtAttr(nl.DEVLINK_ATTR_DEV_NAME, b)
req.AddData(data)
return f, req, nil
}
// DevlinkGetDeviceByName provides a pointer to devlink device and nil error,
// otherwise returns an error code.
func (h *Handle) DevLinkGetDeviceByName(Bus string, Device string) (*DevlinkDevice, error) {
f, req, err := h.createCmdReq(nl.DEVLINK_CMD_GET, Bus, Device)
if err != nil {
return nil, err
}
respmsg, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil {
return nil, err
}
dev, err := parseDevlinkDevice(respmsg)
if err == nil {
h.getEswitchAttrs(f, dev)
}
return dev, err
}
// DevlinkGetDeviceByName provides a pointer to devlink device and nil error,
// otherwise returns an error code.
func DevLinkGetDeviceByName(Bus string, Device string) (*DevlinkDevice, error) {
return pkgHandle.DevLinkGetDeviceByName(Bus, Device)
}
// DevLinkSetEswitchMode sets eswitch mode if able to set successfully or
// returns an error code.
// Equivalent to: `devlink dev eswitch set $dev mode switchdev`
// Equivalent to: `devlink dev eswitch set $dev mode legacy`
func (h *Handle) DevLinkSetEswitchMode(Dev *DevlinkDevice, NewMode string) error {
mode, err := eswitchStringToMode(NewMode)
if err != nil {
return err
}
_, req, err := h.createCmdReq(nl.DEVLINK_CMD_ESWITCH_SET, Dev.BusName, Dev.DeviceName)
if err != nil {
return err
}
req.AddData(nl.NewRtAttr(nl.DEVLINK_ATTR_ESWITCH_MODE, nl.Uint16Attr(mode)))
_, err = req.Execute(unix.NETLINK_GENERIC, 0)
return err
}
// DevLinkSetEswitchMode sets eswitch mode if able to set successfully or
// returns an error code.
// Equivalent to: `devlink dev eswitch set $dev mode switchdev`
// Equivalent to: `devlink dev eswitch set $dev mode legacy`
func DevLinkSetEswitchMode(Dev *DevlinkDevice, NewMode string) error {
return pkgHandle.DevLinkSetEswitchMode(Dev, NewMode)
}

View File

@ -2,6 +2,7 @@ package netlink
import (
"fmt"
"net"
)
type Filter interface {
@ -135,6 +136,27 @@ func (action *BpfAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
type ConnmarkAction struct {
ActionAttrs
Zone uint16
}
func (action *ConnmarkAction) Type() string {
return "connmark"
}
func (action *ConnmarkAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewConnmarkAction() *ConnmarkAction {
return &ConnmarkAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type MirredAct uint8
func (a MirredAct) String() string {
@ -182,49 +204,59 @@ func NewMirredAction(redirIndex int) *MirredAction {
}
}
// Sel of the U32 filters that contains multiple TcU32Key. This is the copy
// and the frontend representation of nl.TcU32Sel. It is serialized into canonical
// nl.TcU32Sel with the appropriate endianness.
type TcU32Sel struct {
Flags uint8
Offshift uint8
Nkeys uint8
Pad uint8
Offmask uint16
Off uint16
Offoff int16
Hoff int16
Hmask uint32
Keys []TcU32Key
type TunnelKeyAct int8
const (
TCA_TUNNEL_KEY_SET TunnelKeyAct = 1 // set tunnel key
TCA_TUNNEL_KEY_UNSET TunnelKeyAct = 2 // unset tunnel key
)
type TunnelKeyAction struct {
ActionAttrs
Action TunnelKeyAct
SrcAddr net.IP
DstAddr net.IP
KeyID uint32
}
// TcU32Key contained of Sel in the U32 filters. This is the copy and the frontend
// representation of nl.TcU32Key. It is serialized into chanonical nl.TcU32Sel
// with the appropriate endianness.
type TcU32Key struct {
Mask uint32
Val uint32
Off int32
OffMask int32
func (action *TunnelKeyAction) Type() string {
return "tunnel_key"
}
// U32 filters on many packet related properties
type U32 struct {
FilterAttrs
ClassId uint32
Divisor uint32 // Divisor MUST be power of 2.
Hash uint32
RedirIndex int
Sel *TcU32Sel
Actions []Action
func (action *TunnelKeyAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func (filter *U32) Attrs() *FilterAttrs {
return &filter.FilterAttrs
func NewTunnelKeyAction() *TunnelKeyAction {
return &TunnelKeyAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
func (filter *U32) Type() string {
return "u32"
type SkbEditAction struct {
ActionAttrs
QueueMapping *uint16
PType *uint16
Priority *uint32
Mark *uint32
}
func (action *SkbEditAction) Type() string {
return "skbedit"
}
func (action *SkbEditAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewSkbEditAction() *SkbEditAction {
return &SkbEditAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
// MatchAll filters match all packets
@ -264,6 +296,8 @@ type BpfFilter struct {
Fd int
Name string
DirectAction bool
Id int
Tag string
}
func (filter *BpfFilter) Type() string {

View File

@ -3,10 +3,11 @@ package netlink
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net"
"syscall"
"unsafe"
"github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
@ -20,6 +21,35 @@ const (
TC_U32_EAT = nl.TC_U32_EAT
)
// Sel of the U32 filters that contains multiple TcU32Key. This is the type
// alias and the frontend representation of nl.TcU32Sel. It is serialized into
// canonical nl.TcU32Sel with the appropriate endianness.
type TcU32Sel = nl.TcU32Sel
// TcU32Key contained of Sel in the U32 filters. This is the type alias and the
// frontend representation of nl.TcU32Key. It is serialized into chanonical
// nl.TcU32Sel with the appropriate endianness.
type TcU32Key = nl.TcU32Key
// U32 filters on many packet related properties
type U32 struct {
FilterAttrs
ClassId uint32
Divisor uint32 // Divisor MUST be power of 2.
Hash uint32
RedirIndex int
Sel *TcU32Sel
Actions []Action
}
func (filter *U32) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *U32) Type() string {
return "u32"
}
// Fw filter filters on firewall marks
// NOTE: this is in filter_linux because it refers to nl.TcPolice which
// is defined in nl/tc_linux.go
@ -123,8 +153,24 @@ func FilterAdd(filter Filter) error {
// FilterAdd will add a filter to the system.
// Equivalent to: `tc filter add $filter`
func (h *Handle) FilterAdd(filter Filter) error {
return h.filterModify(filter, unix.NLM_F_CREATE|unix.NLM_F_EXCL)
}
// FilterReplace will replace a filter.
// Equivalent to: `tc filter replace $filter`
func FilterReplace(filter Filter) error {
return pkgHandle.FilterReplace(filter)
}
// FilterReplace will replace a filter.
// Equivalent to: `tc filter replace $filter`
func (h *Handle) FilterReplace(filter Filter) error {
return h.filterModify(filter, unix.NLM_F_CREATE)
}
func (h *Handle) filterModify(filter Filter, flags int) error {
native = nl.NativeEndian()
req := h.newNetlinkRequest(unix.RTM_NEWTFILTER, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
req := h.newNetlinkRequest(unix.RTM_NEWTFILTER, flags|unix.NLM_F_ACK)
base := filter.Attrs()
msg := &nl.TcMsg{
Family: nl.FAMILY_ALL,
@ -140,8 +186,7 @@ func (h *Handle) FilterAdd(filter Filter) error {
switch filter := filter.(type) {
case *U32:
// Convert TcU32Sel into nl.TcU32Sel as it is without copy.
sel := (*nl.TcU32Sel)(unsafe.Pointer(filter.Sel))
sel := filter.Sel
if sel == nil {
// match all
sel = &nl.TcU32Sel{
@ -385,6 +430,63 @@ func EncodeActions(attr *nl.RtAttr, actions []Action) error {
}
toTcGen(action.Attrs(), &mirred.TcGen)
aopts.AddRtAttr(nl.TCA_MIRRED_PARMS, mirred.Serialize())
case *TunnelKeyAction:
table := attr.AddRtAttr(tabIndex, nil)
tabIndex++
table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("tunnel_key"))
aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil)
tun := nl.TcTunnelKey{
Action: int32(action.Action),
}
toTcGen(action.Attrs(), &tun.TcGen)
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_PARMS, tun.Serialize())
if action.Action == TCA_TUNNEL_KEY_SET {
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_KEY_ID, htonl(action.KeyID))
if v4 := action.SrcAddr.To4(); v4 != nil {
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV4_SRC, v4[:])
} else if v6 := action.SrcAddr.To16(); v6 != nil {
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV6_SRC, v6[:])
} else {
return fmt.Errorf("invalid src addr %s for tunnel_key action", action.SrcAddr)
}
if v4 := action.DstAddr.To4(); v4 != nil {
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV4_DST, v4[:])
} else if v6 := action.DstAddr.To16(); v6 != nil {
aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV6_DST, v6[:])
} else {
return fmt.Errorf("invalid dst addr %s for tunnel_key action", action.DstAddr)
}
}
case *SkbEditAction:
table := attr.AddRtAttr(tabIndex, nil)
tabIndex++
table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("skbedit"))
aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil)
skbedit := nl.TcSkbEdit{}
toTcGen(action.Attrs(), &skbedit.TcGen)
aopts.AddRtAttr(nl.TCA_SKBEDIT_PARMS, skbedit.Serialize())
if action.QueueMapping != nil {
aopts.AddRtAttr(nl.TCA_SKBEDIT_QUEUE_MAPPING, nl.Uint16Attr(*action.QueueMapping))
}
if action.Priority != nil {
aopts.AddRtAttr(nl.TCA_SKBEDIT_PRIORITY, nl.Uint32Attr(*action.Priority))
}
if action.PType != nil {
aopts.AddRtAttr(nl.TCA_SKBEDIT_PTYPE, nl.Uint16Attr(*action.PType))
}
if action.Mark != nil {
aopts.AddRtAttr(nl.TCA_SKBEDIT_MARK, nl.Uint32Attr(*action.Mark))
}
case *ConnmarkAction:
table := attr.AddRtAttr(tabIndex, nil)
tabIndex++
table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("connmark"))
aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil)
connmark := nl.TcConnmark{
Zone: action.Zone,
}
toTcGen(action.Attrs(), &connmark.TcGen)
aopts.AddRtAttr(nl.TCA_CONNMARK_PARMS, connmark.Serialize())
case *BpfAction:
table := attr.AddRtAttr(tabIndex, nil)
tabIndex++
@ -428,8 +530,14 @@ func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) {
action = &MirredAction{}
case "bpf":
action = &BpfAction{}
case "connmark":
action = &ConnmarkAction{}
case "gact":
action = &GenericAction{}
case "tunnel_key":
action = &TunnelKeyAction{}
case "skbedit":
action = &SkbEditAction{}
default:
break nextattr
}
@ -444,11 +552,46 @@ func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) {
switch adatum.Attr.Type {
case nl.TCA_MIRRED_PARMS:
mirred := *nl.DeserializeTcMirred(adatum.Value)
toAttrs(&mirred.TcGen, action.Attrs())
action.(*MirredAction).ActionAttrs = ActionAttrs{}
toAttrs(&mirred.TcGen, action.Attrs())
action.(*MirredAction).Ifindex = int(mirred.Ifindex)
action.(*MirredAction).MirredAction = MirredAct(mirred.Eaction)
}
case "tunnel_key":
switch adatum.Attr.Type {
case nl.TCA_TUNNEL_KEY_PARMS:
tun := *nl.DeserializeTunnelKey(adatum.Value)
action.(*TunnelKeyAction).ActionAttrs = ActionAttrs{}
toAttrs(&tun.TcGen, action.Attrs())
action.(*TunnelKeyAction).Action = TunnelKeyAct(tun.Action)
case nl.TCA_TUNNEL_KEY_ENC_KEY_ID:
action.(*TunnelKeyAction).KeyID = networkOrder.Uint32(adatum.Value[0:4])
case nl.TCA_TUNNEL_KEY_ENC_IPV6_SRC:
case nl.TCA_TUNNEL_KEY_ENC_IPV4_SRC:
action.(*TunnelKeyAction).SrcAddr = net.IP(adatum.Value[:])
case nl.TCA_TUNNEL_KEY_ENC_IPV6_DST:
case nl.TCA_TUNNEL_KEY_ENC_IPV4_DST:
action.(*TunnelKeyAction).DstAddr = net.IP(adatum.Value[:])
}
case "skbedit":
switch adatum.Attr.Type {
case nl.TCA_SKBEDIT_PARMS:
skbedit := *nl.DeserializeSkbEdit(adatum.Value)
action.(*SkbEditAction).ActionAttrs = ActionAttrs{}
toAttrs(&skbedit.TcGen, action.Attrs())
case nl.TCA_SKBEDIT_MARK:
mark := native.Uint32(adatum.Value[0:4])
action.(*SkbEditAction).Mark = &mark
case nl.TCA_SKBEDIT_PRIORITY:
priority := native.Uint32(adatum.Value[0:4])
action.(*SkbEditAction).Priority = &priority
case nl.TCA_SKBEDIT_PTYPE:
ptype := native.Uint16(adatum.Value[0:2])
action.(*SkbEditAction).PType = &ptype
case nl.TCA_SKBEDIT_QUEUE_MAPPING:
mapping := native.Uint16(adatum.Value[0:2])
action.(*SkbEditAction).QueueMapping = &mapping
}
case "bpf":
switch adatum.Attr.Type {
case nl.TCA_ACT_BPF_PARMS:
@ -459,6 +602,14 @@ func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) {
case nl.TCA_ACT_BPF_NAME:
action.(*BpfAction).Name = string(adatum.Value[:len(adatum.Value)-1])
}
case "connmark":
switch adatum.Attr.Type {
case nl.TCA_CONNMARK_PARMS:
connmark := *nl.DeserializeTcConnmark(adatum.Value)
action.(*ConnmarkAction).ActionAttrs = ActionAttrs{}
toAttrs(&connmark.TcGen, action.Attrs())
action.(*ConnmarkAction).Zone = connmark.Zone
}
case "gact":
switch adatum.Attr.Type {
case nl.TCA_GACT_PARMS:
@ -483,7 +634,7 @@ func parseU32Data(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error)
case nl.TCA_U32_SEL:
detailed = true
sel := nl.DeserializeTcU32Sel(datum.Value)
u32.Sel = (*TcU32Sel)(unsafe.Pointer(sel))
u32.Sel = sel
if native != networkOrder {
// Handle the endianness of attributes
u32.Sel.Offmask = native.Uint16(htons(sel.Offmask))
@ -564,6 +715,10 @@ func parseBpfData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error)
if (flags & nl.TCA_BPF_FLAG_ACT_DIRECT) != 0 {
bpf.DirectAction = true
}
case nl.TCA_BPF_ID:
bpf.Id = int(native.Uint32(datum.Value[0:4]))
case nl.TCA_BPF_TAG:
bpf.Tag = hex.EncodeToString(datum.Value[:len(datum.Value)-1])
}
}
return detailed, nil

View File

@ -90,11 +90,7 @@ func (h *Handle) FouAdd(f Fou) error {
req.AddRawData(raw)
_, err = req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil {
return err
}
return nil
return err
}
func FouDel(f Fou) error {

View File

@ -157,6 +157,9 @@ func (h *Handle) GenlFamilyGet(name string) (*GenlFamily, error) {
return nil, err
}
families, err := parseFamilies(msgs)
if err != nil {
return nil, err
}
if len(families) != 1 {
return nil, fmt.Errorf("invalid response for GENL_CTRL_CMD_GETFAMILY")
}

8
vendor/github.com/vishvananda/netlink/go.mod generated vendored Normal file
View File

@ -0,0 +1,8 @@
module github.com/vishvananda/netlink
go 1.12
require (
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444
)

4
vendor/github.com/vishvananda/netlink/go.sum generated vendored Normal file
View File

@ -0,0 +1,4 @@
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df h1:OviZH7qLw/7ZovXvuNyL3XQl8UFofeikI1NW1Gypu7k=
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444 h1:/d2cWp6PSamH4jDPFLyO150psQdqvtoNX8Zjg3AQ31g=
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@ -91,7 +91,7 @@ func (h *Handle) GetSocketReceiveBufferSize() ([]int, error) {
return results, nil
}
// NewHandle returns a netlink handle on the network namespace
// NewHandleAt returns a netlink handle on the network namespace
// specified by ns. If ns=netns.None(), current network namespace
// will be assumed
func NewHandleAt(ns netns.NsHandle, nlFamilies ...int) (*Handle, error) {

View File

@ -73,10 +73,18 @@ func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
return ErrNotImplemented
}
func (h *Handle) LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
return ErrNotImplemented
}
func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
return ErrNotImplemented
}
func (h *Handle) LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
return ErrNotImplemented
}
func (h *Handle) LinkSetMaster(link Link, master *Bridge) error {
return ErrNotImplemented
}
@ -149,6 +157,10 @@ func (h *Handle) LinkSetTxQLen(link Link, qlen int) error {
return ErrNotImplemented
}
func (h *Handle) LinkSetGroup(link Link, group int) error {
return ErrNotImplemented
}
func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error {
return ErrNotImplemented
}

View File

@ -56,18 +56,10 @@ type ethtoolSset struct {
data [1]uint32
}
// ethtoolGstrings is string set for data tagging
type ethtoolGstrings struct {
cmd uint32
stringSet uint32
length uint32
data [32]byte
}
type ethtoolStats struct {
cmd uint32
nStats uint32
data [1]uint64
// Followed by nStats * []uint64.
}
// newIocltSlaveReq returns filled IfreqSlave with proper interface names

View File

@ -4,6 +4,7 @@ import (
"fmt"
"net"
"os"
"strconv"
)
// Link represents a link device from netlink. Shared link attributes
@ -41,7 +42,16 @@ type LinkAttrs struct {
NetNsID int
NumTxQueues int
NumRxQueues int
GSOMaxSize uint32
GSOMaxSegs uint32
Vfs []VfInfo // virtual functions available on link
Group uint32
Slave LinkSlave
}
// LinkSlave represents a slave device.
type LinkSlave interface {
SlaveType() string
}
// VfInfo represents configuration of virtual function
@ -50,9 +60,11 @@ type VfInfo struct {
Mac net.HardwareAddr
Vlan int
Qos int
TxRate int
TxRate int // IFLA_VF_TX_RATE Max TxRate
Spoofchk bool
LinkState uint32
MaxTxRate uint32 // IFLA_VF_RATE Max TxRate
MinTxRate uint32 // IFLA_VF_RATE Min TxRate
}
// LinkOperState represents the values of the IFLA_OPERSTATE link
@ -249,7 +261,8 @@ func (bridge *Bridge) Type() string {
// Vlan links have ParentIndex set in their Attrs()
type Vlan struct {
LinkAttrs
VlanId int
VlanId int
VlanProtocol VlanProtocol
}
func (vlan *Vlan) Attrs() *LinkAttrs {
@ -308,6 +321,8 @@ type Tuntap struct {
NonPersist bool
Queues int
Fds []*os.File
Owner uint32
Group uint32
}
func (tuntap *Tuntap) Attrs() *LinkAttrs {
@ -321,7 +336,8 @@ func (tuntap *Tuntap) Type() string {
// Veth devices must specify PeerName on create
type Veth struct {
LinkAttrs
PeerName string // veth on create only
PeerName string // veth on create only
PeerHardwareAddr net.HardwareAddr
}
func (veth *Veth) Attrs() *LinkAttrs {
@ -390,9 +406,18 @@ const (
IPVLAN_MODE_MAX
)
type IPVlanFlag uint16
const (
IPVLAN_FLAG_BRIDGE IPVlanFlag = iota
IPVLAN_FLAG_PRIVATE
IPVLAN_FLAG_VEPA
)
type IPVlan struct {
LinkAttrs
Mode IPVlanMode
Flag IPVlanFlag
}
func (ipvlan *IPVlan) Attrs() *LinkAttrs {
@ -403,6 +428,43 @@ func (ipvlan *IPVlan) Type() string {
return "ipvlan"
}
// VlanProtocol type
type VlanProtocol int
func (p VlanProtocol) String() string {
s, ok := VlanProtocolToString[p]
if !ok {
return fmt.Sprintf("VlanProtocol(%d)", p)
}
return s
}
// StringToVlanProtocol returns vlan protocol, or unknown is the s is invalid.
func StringToVlanProtocol(s string) VlanProtocol {
mode, ok := StringToVlanProtocolMap[s]
if !ok {
return VLAN_PROTOCOL_UNKNOWN
}
return mode
}
// VlanProtocol possible values
const (
VLAN_PROTOCOL_UNKNOWN VlanProtocol = 0
VLAN_PROTOCOL_8021Q VlanProtocol = 0x8100
VLAN_PROTOCOL_8021AD VlanProtocol = 0x88A8
)
var VlanProtocolToString = map[VlanProtocol]string{
VLAN_PROTOCOL_8021Q: "802.1q",
VLAN_PROTOCOL_8021AD: "802.1ad",
}
var StringToVlanProtocolMap = map[string]VlanProtocol{
"802.1q": VLAN_PROTOCOL_8021Q,
"802.1ad": VLAN_PROTOCOL_8021AD,
}
// BondMode type
type BondMode int
@ -414,7 +476,7 @@ func (b BondMode) String() string {
return s
}
// StringToBondMode returns bond mode, or uknonw is the s is invalid.
// StringToBondMode returns bond mode, or unknown is the s is invalid.
func StringToBondMode(s string) BondMode {
mode, ok := StringToBondModeMap[s]
if !ok {
@ -505,7 +567,7 @@ func (b BondXmitHashPolicy) String() string {
return s
}
// StringToBondXmitHashPolicy returns bond lacp arte, or uknonw is the s is invalid.
// StringToBondXmitHashPolicy returns bond lacp arte, or unknown is the s is invalid.
func StringToBondXmitHashPolicy(s string) BondXmitHashPolicy {
lacp, ok := StringToBondXmitHashPolicyMap[s]
if !ok {
@ -550,7 +612,7 @@ func (b BondLacpRate) String() string {
return s
}
// StringToBondLacpRate returns bond lacp arte, or uknonw is the s is invalid.
// StringToBondLacpRate returns bond lacp arte, or unknown is the s is invalid.
func StringToBondLacpRate(s string) BondLacpRate {
lacp, ok := StringToBondLacpRateMap[s]
if !ok {
@ -694,6 +756,67 @@ func (bond *Bond) Type() string {
return "bond"
}
// BondSlaveState represents the values of the IFLA_BOND_SLAVE_STATE bond slave
// attribute, which contains the state of the bond slave.
type BondSlaveState uint8
const (
BondStateActive = iota // Link is active.
BondStateBackup // Link is backup.
)
func (s BondSlaveState) String() string {
switch s {
case BondStateActive:
return "ACTIVE"
case BondStateBackup:
return "BACKUP"
default:
return strconv.Itoa(int(s))
}
}
// BondSlaveState represents the values of the IFLA_BOND_SLAVE_MII_STATUS bond slave
// attribute, which contains the status of MII link monitoring
type BondSlaveMiiStatus uint8
const (
BondLinkUp = iota // link is up and running.
BondLinkFail // link has just gone down.
BondLinkDown // link has been down for too long time.
BondLinkBack // link is going back.
)
func (s BondSlaveMiiStatus) String() string {
switch s {
case BondLinkUp:
return "UP"
case BondLinkFail:
return "GOING_DOWN"
case BondLinkDown:
return "DOWN"
case BondLinkBack:
return "GOING_BACK"
default:
return strconv.Itoa(int(s))
}
}
type BondSlave struct {
State BondSlaveState
MiiStatus BondSlaveMiiStatus
LinkFailureCount uint32
PermHardwareAddr net.HardwareAddr
QueueId uint16
AggregatorId uint16
AdActorOperPortState uint8
AdPartnerOperPortState uint16
}
func (b *BondSlave) SlaveType() string {
return "bond"
}
// Gretap devices must specify LocalIP and RemoteIP on create
type Gretap struct {
LinkAttrs
@ -748,6 +871,27 @@ func (iptun *Iptun) Type() string {
return "ipip"
}
type Ip6tnl struct {
LinkAttrs
Link uint32
Local net.IP
Remote net.IP
Ttl uint8
Tos uint8
EncapLimit uint8
Flags uint32
Proto uint8
FlowInfo uint32
}
func (ip6tnl *Ip6tnl) Attrs() *LinkAttrs {
return &ip6tnl.LinkAttrs
}
func (ip6tnl *Ip6tnl) Type() string {
return "ip6tnl"
}
type Sittun struct {
LinkAttrs
Link uint32
@ -848,11 +992,68 @@ func (gtp *GTP) Type() string {
return "gtp"
}
// Virtual XFRM Interfaces
// Named "xfrmi" to prevent confusion with XFRM objects
type Xfrmi struct {
LinkAttrs
Ifid uint32
}
func (xfrm *Xfrmi) Attrs() *LinkAttrs {
return &xfrm.LinkAttrs
}
func (xfrm *Xfrmi) Type() string {
return "xfrm"
}
// IPoIB interface
type IPoIBMode uint16
func (m *IPoIBMode) String() string {
str, ok := iPoIBModeToString[*m]
if !ok {
return fmt.Sprintf("mode(%d)", *m)
}
return str
}
const (
IPOIB_MODE_DATAGRAM = iota
IPOIB_MODE_CONNECTED
)
var iPoIBModeToString = map[IPoIBMode]string{
IPOIB_MODE_DATAGRAM: "datagram",
IPOIB_MODE_CONNECTED: "connected",
}
var StringToIPoIBMode = map[string]IPoIBMode{
"datagram": IPOIB_MODE_DATAGRAM,
"connected": IPOIB_MODE_CONNECTED,
}
type IPoIB struct {
LinkAttrs
Pkey uint16
Mode IPoIBMode
Umcast uint16
}
func (ipoib *IPoIB) Attrs() *LinkAttrs {
return &ipoib.LinkAttrs
}
func (ipoib *IPoIB) Type() string {
return "ipoib"
}
// iproute2 supported devices;
// vlan | veth | vcan | dummy | ifb | macvlan | macvtap |
// bridge | bond | ipoib | ip6tnl | ipip | sit | vxlan |
// gre | gretap | ip6gre | ip6gretap | vti | vti6 | nlmon |
// bond_slave | ipvlan
// bond_slave | ipvlan | xfrm
// LinkNotFoundError wraps the various not found errors when
// getting/reading links. This is intended for better error

View File

@ -4,8 +4,10 @@ import (
"bytes"
"encoding/binary"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"syscall"
"unsafe"
@ -17,7 +19,7 @@ import (
const (
SizeofLinkStats32 = 0x5c
SizeofLinkStats64 = 0xd8
SizeofLinkStats64 = 0xb8
)
const (
@ -32,6 +34,12 @@ const (
TUNTAP_MULTI_QUEUE_DEFAULTS TuntapFlag = TUNTAP_MULTI_QUEUE | TUNTAP_NO_PI
)
const (
VF_LINK_STATE_AUTO uint32 = 0
VF_LINK_STATE_ENABLE uint32 = 1
VF_LINK_STATE_DISABLE uint32 = 2
)
var lookupByDump = false
var macvlanModes = [...]uint32{
@ -465,6 +473,37 @@ func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
return err
}
// LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link.
// Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos`
func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
return pkgHandle.LinkSetVfVlanQos(link, vf, vlan, qos)
}
// LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link.
// Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos`
func (h *Handle) LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfVlan{
Vf: uint32(vf),
Vlan: uint32(vlan),
Qos: uint32(qos),
}
nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
// LinkSetVfTxRate sets the tx rate of a vf for the link.
// Equivalent to: `ip link set $link vf $vf rate $rate`
func LinkSetVfTxRate(link Link, vf, rate int) error {
@ -495,13 +534,74 @@ func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
return err
}
// LinkSetVfRate sets the min and max tx rate of a vf for the link.
// Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate`
func LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
return pkgHandle.LinkSetVfRate(link, vf, minRate, maxRate)
}
// LinkSetVfRate sets the min and max tx rate of a vf for the link.
// Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate`
func (h *Handle) LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfRate{
Vf: uint32(vf),
MinTxRate: uint32(minRate),
MaxTxRate: uint32(maxRate),
}
info.AddRtAttr(nl.IFLA_VF_RATE, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
// LinkSetVfState enables/disables virtual link state on a vf.
// Equivalent to: `ip link set $link vf $vf state $state`
func LinkSetVfState(link Link, vf int, state uint32) error {
return pkgHandle.LinkSetVfState(link, vf, state)
}
// LinkSetVfState enables/disables virtual link state on a vf.
// Equivalent to: `ip link set $link vf $vf state $state`
func (h *Handle) LinkSetVfState(link Link, vf int, state uint32) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
vfmsg := nl.VfLinkState{
Vf: uint32(vf),
LinkState: state,
}
info.AddRtAttr(nl.IFLA_VF_LINK_STATE, vfmsg.Serialize())
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
// LinkSetVfSpoofchk enables/disables spoof check on a vf for the link.
// Equivalent to: `ip link set $link vf $vf spoofchk $check`
func LinkSetVfSpoofchk(link Link, vf int, check bool) error {
return pkgHandle.LinkSetVfSpoofchk(link, vf, check)
}
// LinkSetVfSpookfchk enables/disables spoof check on a vf for the link.
// LinkSetVfSpoofchk enables/disables spoof check on a vf for the link.
// Equivalent to: `ip link set $link vf $vf spoofchk $check`
func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error {
var setting uint32
@ -581,7 +681,7 @@ func (h *Handle) LinkSetVfGUID(link Link, vf int, vfGuid net.HardwareAddr, guidT
var guid uint64
buf := bytes.NewBuffer(vfGuid)
err = binary.Read(buf, binary.LittleEndian, &guid)
err = binary.Read(buf, binary.BigEndian, &guid)
if err != nil {
return err
}
@ -609,13 +709,13 @@ func (h *Handle) LinkSetVfGUID(link Link, vf int, vfGuid net.HardwareAddr, guidT
// LinkSetMaster sets the master of the link device.
// Equivalent to: `ip link set $link master $master`
func LinkSetMaster(link Link, master *Bridge) error {
func LinkSetMaster(link Link, master Link) error {
return pkgHandle.LinkSetMaster(link, master)
}
// LinkSetMaster sets the master of the link device.
// Equivalent to: `ip link set $link master $master`
func (h *Handle) LinkSetMaster(link Link, master *Bridge) error {
func (h *Handle) LinkSetMaster(link Link, master Link) error {
index := 0
if master != nil {
masterBase := master.Attrs()
@ -1086,8 +1186,8 @@ func (h *Handle) linkModify(link Link, flags int) error {
native.PutUint32(b, uint32(base.ParentIndex))
data := nl.NewRtAttr(unix.IFLA_LINK, b)
req.AddData(data)
} else if link.Type() == "ipvlan" {
return fmt.Errorf("Can't create ipvlan link without ParentIndex")
} else if link.Type() == "ipvlan" || link.Type() == "ipoib" {
return fmt.Errorf("Can't create %s link without ParentIndex", link.Type())
}
nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(base.Name))
@ -1118,14 +1218,29 @@ func (h *Handle) linkModify(link Link, flags int) error {
req.AddData(rxqueues)
}
if base.GSOMaxSegs > 0 {
gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SEGS, nl.Uint32Attr(base.GSOMaxSegs))
req.AddData(gsoAttr)
}
if base.GSOMaxSize > 0 {
gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SIZE, nl.Uint32Attr(base.GSOMaxSize))
req.AddData(gsoAttr)
}
if base.Group > 0 {
groupAttr := nl.NewRtAttr(unix.IFLA_GROUP, nl.Uint32Attr(base.Group))
req.AddData(groupAttr)
}
if base.Namespace != nil {
var attr *nl.RtAttr
switch base.Namespace.(type) {
switch ns := base.Namespace.(type) {
case NsPid:
val := nl.Uint32Attr(uint32(base.Namespace.(NsPid)))
val := nl.Uint32Attr(uint32(ns))
attr = nl.NewRtAttr(unix.IFLA_NET_NS_PID, val)
case NsFd:
val := nl.Uint32Attr(uint32(base.Namespace.(NsFd)))
val := nl.Uint32Attr(uint32(ns))
attr = nl.NewRtAttr(unix.IFLA_NET_NS_FD, val)
}
@ -1145,6 +1260,10 @@ func (h *Handle) linkModify(link Link, flags int) error {
native.PutUint16(b, uint16(link.VlanId))
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
data.AddRtAttr(nl.IFLA_VLAN_ID, b)
if link.VlanProtocol != VLAN_PROTOCOL_UNKNOWN {
data.AddRtAttr(nl.IFLA_VLAN_PROTOCOL, htons(uint16(link.VlanProtocol)))
}
case *Veth:
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
peer := data.AddRtAttr(nl.VETH_INFO_PEER, nil)
@ -1156,7 +1275,9 @@ func (h *Handle) linkModify(link Link, flags int) error {
if base.MTU > 0 {
peer.AddRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
}
if link.PeerHardwareAddr != nil {
peer.AddRtAttr(unix.IFLA_ADDRESS, []byte(link.PeerHardwareAddr))
}
case *Vxlan:
addVxlanAttrs(link, linkInfo)
case *Bond:
@ -1164,6 +1285,7 @@ func (h *Handle) linkModify(link Link, flags int) error {
case *IPVlan:
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
data.AddRtAttr(nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(link.Mode)))
data.AddRtAttr(nl.IFLA_IPVLAN_FLAG, nl.Uint16Attr(uint16(link.Flag)))
case *Macvlan:
if link.Mode != MACVLAN_MODE_DEFAULT {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
@ -1178,6 +1300,8 @@ func (h *Handle) linkModify(link Link, flags int) error {
addGretapAttrs(link, linkInfo)
case *Iptun:
addIptunAttrs(link, linkInfo)
case *Ip6tnl:
addIp6tnlAttrs(link, linkInfo)
case *Sittun:
addSittunAttrs(link, linkInfo)
case *Gretun:
@ -1190,6 +1314,10 @@ func (h *Handle) linkModify(link Link, flags int) error {
addBridgeAttrs(link, linkInfo)
case *GTP:
addGTPAttrs(link, linkInfo)
case *Xfrmi:
addXfrmiAttrs(link, linkInfo)
case *IPoIB:
addIPoIBAttrs(link, linkInfo)
}
req.AddData(linkInfo)
@ -1386,10 +1514,12 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
base.Promisc = 1
}
var (
link Link
stats32 []byte
stats64 []byte
linkType string
link Link
stats32 *LinkStatistics32
stats64 *LinkStatistics64
linkType string
linkSlave LinkSlave
slaveType string
)
for _, attr := range attrs {
switch attr.Attr.Type {
@ -1429,6 +1559,8 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
link = &Gretap{}
case "ipip":
link = &Iptun{}
case "ip6tnl":
link = &Ip6tnl{}
case "sit":
link = &Sittun{}
case "gre":
@ -1441,6 +1573,12 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
link = &Vrf{}
case "gtp":
link = &GTP{}
case "xfrm":
link = &Xfrmi{}
case "tun":
link = &Tuntap{}
case "ipoib":
link = &IPoIB{}
default:
link = &GenericLink{LinkType: linkType}
}
@ -1468,6 +1606,8 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
parseGretapData(link, data)
case "ipip":
parseIptunData(link, data)
case "ip6tnl":
parseIp6tnlData(link, data)
case "sit":
parseSittunData(link, data)
case "gre":
@ -1482,6 +1622,27 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
parseBridgeData(link, data)
case "gtp":
parseGTPData(link, data)
case "xfrm":
parseXfrmiData(link, data)
case "tun":
parseTuntapData(link, data)
case "ipoib":
parseIPoIBData(link, data)
}
case nl.IFLA_INFO_SLAVE_KIND:
slaveType = string(info.Value[:len(info.Value)-1])
switch slaveType {
case "bond":
linkSlave = &BondSlave{}
}
case nl.IFLA_INFO_SLAVE_DATA:
switch slaveType {
case "bond":
data, err := nl.ParseRouteAttr(info.Value)
if err != nil {
return nil, err
}
parseBondSlaveData(linkSlave, data)
}
}
}
@ -1508,9 +1669,15 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
case unix.IFLA_IFALIAS:
base.Alias = string(attr.Value[:len(attr.Value)-1])
case unix.IFLA_STATS:
stats32 = attr.Value[:]
stats32 = new(LinkStatistics32)
if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats32); err != nil {
return nil, err
}
case unix.IFLA_STATS64:
stats64 = attr.Value[:]
stats64 = new(LinkStatistics64)
if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats64); err != nil {
return nil, err
}
case unix.IFLA_XDP:
xdp, err := parseLinkXdp(attr.Value[:])
if err != nil {
@ -1531,6 +1698,10 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
base.OperState = LinkOperState(uint8(attr.Value[0]))
case unix.IFLA_LINK_NETNSID:
base.NetNsID = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_GSO_MAX_SIZE:
base.GSOMaxSize = native.Uint32(attr.Value[0:4])
case unix.IFLA_GSO_MAX_SEGS:
base.GSOMaxSegs = native.Uint32(attr.Value[0:4])
case unix.IFLA_VFINFO_LIST:
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
@ -1541,13 +1712,19 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
return nil, err
}
base.Vfs = vfs
case unix.IFLA_NUM_TX_QUEUES:
base.NumTxQueues = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_NUM_RX_QUEUES:
base.NumRxQueues = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_GROUP:
base.Group = native.Uint32(attr.Value[0:4])
}
}
if stats64 != nil {
base.Statistics = parseLinkStats64(stats64)
base.Statistics = (*LinkStatistics)(stats64)
} else if stats32 != nil {
base.Statistics = parseLinkStats32(stats32)
base.Statistics = (*LinkStatistics)(stats32.to64())
}
// Links that don't have IFLA_INFO_KIND are hardware devices
@ -1555,10 +1732,59 @@ func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
link = &Device{}
}
*link.Attrs() = base
link.Attrs().Slave = linkSlave
// If the tuntap attributes are not updated by netlink due to
// an older driver, use sysfs
if link != nil && linkType == "tun" {
tuntap := link.(*Tuntap)
if tuntap.Mode == 0 {
ifname := tuntap.Attrs().Name
if flags, err := readSysPropAsInt64(ifname, "tun_flags"); err == nil {
if flags&unix.IFF_TUN != 0 {
tuntap.Mode = unix.IFF_TUN
} else if flags&unix.IFF_TAP != 0 {
tuntap.Mode = unix.IFF_TAP
}
tuntap.NonPersist = false
if flags&unix.IFF_PERSIST == 0 {
tuntap.NonPersist = true
}
}
// The sysfs interface for owner/group returns -1 for root user, instead of returning 0.
// So explicitly check for negative value, before assigning the owner uid/gid.
if owner, err := readSysPropAsInt64(ifname, "owner"); err == nil && owner > 0 {
tuntap.Owner = uint32(owner)
}
if group, err := readSysPropAsInt64(ifname, "group"); err == nil && group > 0 {
tuntap.Group = uint32(group)
}
}
}
return link, nil
}
func readSysPropAsInt64(ifname, prop string) (int64, error) {
fname := fmt.Sprintf("/sys/class/net/%s/%s", ifname, prop)
contents, err := ioutil.ReadFile(fname)
if err != nil {
return 0, err
}
num, err := strconv.ParseInt(strings.TrimSpace(string(contents)), 0, 64)
if err == nil {
return num, nil
}
return 0, err
}
// LinkList gets a list of link devices.
// Equivalent to: `ip link show`
func LinkList() ([]Link, error) {
@ -1655,13 +1881,19 @@ func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-c
go func() {
defer close(ch)
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
if cberr != nil {
cberr(err)
}
return
}
if from.Pid != nl.PidKernel {
if cberr != nil {
cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel))
}
continue
}
for _, m := range msgs {
if m.Header.Type == unix.NLMSG_DONE {
continue
@ -1804,12 +2036,43 @@ func (h *Handle) LinkSetTxQLen(link Link, qlen int) error {
return err
}
// LinkSetGroup sets the link group id which can be used to perform mass actions
// with iproute2 as well use it as a reference in nft filters.
// Equivalent to: `ip link set $link group $id`
func LinkSetGroup(link Link, group int) error {
return pkgHandle.LinkSetGroup(link, group)
}
// LinkSetGroup sets the link group id which can be used to perform mass actions
// with iproute2 as well use it as a reference in nft filters.
// Equivalent to: `ip link set $link group $id`
func (h *Handle) LinkSetGroup(link Link, group int) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(group))
data := nl.NewRtAttr(unix.IFLA_GROUP, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) {
vlan := link.(*Vlan)
for _, datum := range data {
switch datum.Attr.Type {
case nl.IFLA_VLAN_ID:
vlan.VlanId = int(native.Uint16(datum.Value[0:2]))
case nl.IFLA_VLAN_PROTOCOL:
vlan.VlanProtocol = VlanProtocol(int(ntohs(datum.Value[0:2])))
}
}
}
@ -1891,7 +2154,7 @@ func parseBondData(link Link, data []syscall.NetlinkRouteAttr) {
case nl.IFLA_BOND_ARP_INTERVAL:
bond.ArpInterval = int(native.Uint32(data[i].Value[0:4]))
case nl.IFLA_BOND_ARP_IP_TARGET:
// TODO: implement
bond.ArpIpTargets = parseBondArpIpTargets(data[i].Value)
case nl.IFLA_BOND_ARP_VALIDATE:
bond.ArpValidate = BondArpValidate(native.Uint32(data[i].Value[0:4]))
case nl.IFLA_BOND_ARP_ALL_TARGETS:
@ -1934,12 +2197,75 @@ func parseBondData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
func parseBondArpIpTargets(value []byte) []net.IP {
data, err := nl.ParseRouteAttr(value)
if err != nil {
return nil
}
targets := []net.IP{}
for i := range data {
target := net.IP(data[i].Value)
if ip := target.To4(); ip != nil {
targets = append(targets, ip)
continue
}
if ip := target.To16(); ip != nil {
targets = append(targets, ip)
}
}
return targets
}
func addBondSlaveAttrs(bondSlave *BondSlave, linkInfo *nl.RtAttr) {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil)
data.AddRtAttr(nl.IFLA_BOND_SLAVE_STATE, nl.Uint8Attr(uint8(bondSlave.State)))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_MII_STATUS, nl.Uint8Attr(uint8(bondSlave.MiiStatus)))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT, nl.Uint32Attr(bondSlave.LinkFailureCount))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(bondSlave.QueueId))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID, nl.Uint16Attr(bondSlave.AggregatorId))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE, nl.Uint8Attr(bondSlave.AdActorOperPortState))
data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE, nl.Uint16Attr(bondSlave.AdPartnerOperPortState))
if mac := bondSlave.PermHardwareAddr; mac != nil {
data.AddRtAttr(nl.IFLA_BOND_SLAVE_PERM_HWADDR, []byte(mac))
}
}
func parseBondSlaveData(slave LinkSlave, data []syscall.NetlinkRouteAttr) {
bondSlave := slave.(*BondSlave)
for i := range data {
switch data[i].Attr.Type {
case nl.IFLA_BOND_SLAVE_STATE:
bondSlave.State = BondSlaveState(data[i].Value[0])
case nl.IFLA_BOND_SLAVE_MII_STATUS:
bondSlave.MiiStatus = BondSlaveMiiStatus(data[i].Value[0])
case nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT:
bondSlave.LinkFailureCount = native.Uint32(data[i].Value[0:4])
case nl.IFLA_BOND_SLAVE_PERM_HWADDR:
bondSlave.PermHardwareAddr = net.HardwareAddr(data[i].Value[0:6])
case nl.IFLA_BOND_SLAVE_QUEUE_ID:
bondSlave.QueueId = native.Uint16(data[i].Value[0:2])
case nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID:
bondSlave.AggregatorId = native.Uint16(data[i].Value[0:2])
case nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE:
bondSlave.AdActorOperPortState = uint8(data[i].Value[0])
case nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE:
bondSlave.AdPartnerOperPortState = native.Uint16(data[i].Value[0:2])
}
}
}
func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
ipv := link.(*IPVlan)
for _, datum := range data {
if datum.Attr.Type == nl.IFLA_IPVLAN_MODE {
switch datum.Attr.Type {
case nl.IFLA_IPVLAN_MODE:
ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4]))
return
case nl.IFLA_IPVLAN_FLAG:
ipv.Flag = IPVlanFlag(native.Uint32(datum.Value[0:4]))
}
}
}
@ -2081,9 +2407,7 @@ func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) {
case nl.IFLA_GRE_ENCAP_FLAGS:
gre.EncapFlags = native.Uint16(datum.Value[0:2])
case nl.IFLA_GRE_COLLECT_METADATA:
if len(datum.Value) > 0 {
gre.FlowBased = int8(datum.Value[0]) != 0
}
gre.FlowBased = true
}
}
}
@ -2165,14 +2489,6 @@ func parseGretunData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
func parseLinkStats32(data []byte) *LinkStatistics {
return (*LinkStatistics)((*LinkStatistics32)(unsafe.Pointer(&data[0:SizeofLinkStats32][0])).to64())
}
func parseLinkStats64(data []byte) *LinkStatistics {
return (*LinkStatistics)((*LinkStatistics64)(unsafe.Pointer(&data[0:SizeofLinkStats64][0])))
}
func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) {
attrs := nl.NewRtAttr(unix.IFLA_XDP|unix.NLA_F_NESTED, nil)
b := make([]byte, 4)
@ -2266,6 +2582,55 @@ func parseIptunData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
func addIp6tnlAttrs(ip6tnl *Ip6tnl, linkInfo *nl.RtAttr) {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
if ip6tnl.Link != 0 {
data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(ip6tnl.Link))
}
ip := ip6tnl.Local.To16()
if ip != nil {
data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip))
}
ip = ip6tnl.Remote.To16()
if ip != nil {
data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip))
}
data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(ip6tnl.Ttl))
data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(ip6tnl.Tos))
data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_LIMIT, nl.Uint8Attr(ip6tnl.EncapLimit))
data.AddRtAttr(nl.IFLA_IPTUN_FLAGS, nl.Uint32Attr(ip6tnl.Flags))
data.AddRtAttr(nl.IFLA_IPTUN_PROTO, nl.Uint8Attr(ip6tnl.Proto))
data.AddRtAttr(nl.IFLA_IPTUN_FLOWINFO, nl.Uint32Attr(ip6tnl.FlowInfo))
}
func parseIp6tnlData(link Link, data []syscall.NetlinkRouteAttr) {
ip6tnl := link.(*Ip6tnl)
for _, datum := range data {
switch datum.Attr.Type {
case nl.IFLA_IPTUN_LOCAL:
ip6tnl.Local = net.IP(datum.Value[:16])
case nl.IFLA_IPTUN_REMOTE:
ip6tnl.Remote = net.IP(datum.Value[:16])
case nl.IFLA_IPTUN_TTL:
ip6tnl.Ttl = uint8(datum.Value[0])
case nl.IFLA_IPTUN_TOS:
ip6tnl.Tos = uint8(datum.Value[0])
case nl.IFLA_IPTUN_ENCAP_LIMIT:
ip6tnl.EncapLimit = uint8(datum.Value[0])
case nl.IFLA_IPTUN_FLAGS:
ip6tnl.Flags = native.Uint32(datum.Value[:4])
case nl.IFLA_IPTUN_PROTO:
ip6tnl.Proto = uint8(datum.Value[0])
case nl.IFLA_IPTUN_FLOWINFO:
ip6tnl.FlowInfo = native.Uint32(datum.Value[:4])
}
}
}
func addSittunAttrs(sittun *Sittun, linkInfo *nl.RtAttr) {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
@ -2483,11 +2848,34 @@ func parseVfInfo(data []syscall.NetlinkRouteAttr, id int) VfInfo {
case nl.IFLA_VF_LINK_STATE:
ls := nl.DeserializeVfLinkState(element.Value[:])
vf.LinkState = ls.LinkState
case nl.IFLA_VF_RATE:
vfr := nl.DeserializeVfRate(element.Value[:])
vf.MaxTxRate = vfr.MaxTxRate
vf.MinTxRate = vfr.MinTxRate
}
}
return vf
}
func addXfrmiAttrs(xfrmi *Xfrmi, linkInfo *nl.RtAttr) {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
data.AddRtAttr(nl.IFLA_XFRM_LINK, nl.Uint32Attr(uint32(xfrmi.ParentIndex)))
data.AddRtAttr(nl.IFLA_XFRM_IF_ID, nl.Uint32Attr(xfrmi.Ifid))
}
func parseXfrmiData(link Link, data []syscall.NetlinkRouteAttr) {
xfrmi := link.(*Xfrmi)
for _, datum := range data {
switch datum.Attr.Type {
case nl.IFLA_XFRM_LINK:
xfrmi.ParentIndex = int(native.Uint32(datum.Value))
case nl.IFLA_XFRM_IF_ID:
xfrmi.Ifid = native.Uint32(datum.Value)
}
}
}
// LinkSetBondSlave add slave to bond link via ioctl interface.
func LinkSetBondSlave(link Link, master *Bond) error {
fd, err := getSocketUDP()
@ -2505,6 +2893,52 @@ func LinkSetBondSlave(link Link, master *Bond) error {
return nil
}
// LinkSetBondSlaveQueueId modify bond slave queue-id.
func (h *Handle) LinkSetBondSlaveQueueId(link Link, queueId uint16) error {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil)
data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil)
data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(queueId))
req.AddData(linkInfo)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
// LinkSetBondSlaveQueueId modify bond slave queue-id.
func LinkSetBondSlaveQueueId(link Link, queueId uint16) error {
return pkgHandle.LinkSetBondSlaveQueueId(link, queueId)
}
func vethStatsSerialize(stats ethtoolStats) ([]byte, error) {
statsSize := int(unsafe.Sizeof(stats)) + int(stats.nStats)*int(unsafe.Sizeof(uint64(0)))
b := make([]byte, 0, statsSize)
buf := bytes.NewBuffer(b)
err := binary.Write(buf, nl.NativeEndian(), stats)
return buf.Bytes()[:statsSize], err
}
type vethEthtoolStats struct {
Cmd uint32
NStats uint32
Peer uint64
// Newer kernels have XDP stats in here, but we only care
// to extract the peer ifindex here.
}
func vethStatsDeserialize(b []byte) (vethEthtoolStats, error) {
var stats = vethEthtoolStats{}
err := binary.Read(bytes.NewReader(b), nl.NativeEndian(), &stats)
return stats, err
}
// VethPeerIndex get veth peer index.
func VethPeerIndex(link *Veth) (int, error) {
fd, err := getSocketUDP()
@ -2519,25 +2953,66 @@ func VethPeerIndex(link *Veth) (int, error) {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
gstrings := &ethtoolGstrings{
cmd: ETHTOOL_GSTRINGS,
stringSet: ETH_SS_STATS,
length: sSet.data[0],
stats := ethtoolStats{
cmd: ETHTOOL_GSTATS,
nStats: sSet.data[0],
}
ifreq.Data = uintptr(unsafe.Pointer(gstrings))
buffer, err := vethStatsSerialize(stats)
if err != nil {
return -1, err
}
ifreq.Data = uintptr(unsafe.Pointer(&buffer[0]))
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
stats := &ethtoolStats{
cmd: ETHTOOL_GSTATS,
nStats: gstrings.length,
vstats, err := vethStatsDeserialize(buffer)
if err != nil {
return -1, err
}
ifreq.Data = uintptr(unsafe.Pointer(stats))
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
return int(stats.data[0]), nil
return int(vstats.Peer), nil
}
func parseTuntapData(link Link, data []syscall.NetlinkRouteAttr) {
tuntap := link.(*Tuntap)
for _, datum := range data {
switch datum.Attr.Type {
case nl.IFLA_TUN_OWNER:
tuntap.Owner = native.Uint32(datum.Value)
case nl.IFLA_TUN_GROUP:
tuntap.Group = native.Uint32(datum.Value)
case nl.IFLA_TUN_TYPE:
tuntap.Mode = TuntapMode(uint8(datum.Value[0]))
case nl.IFLA_TUN_PERSIST:
tuntap.NonPersist = false
if uint8(datum.Value[0]) == 0 {
tuntap.NonPersist = true
}
}
}
}
func parseIPoIBData(link Link, data []syscall.NetlinkRouteAttr) {
ipoib := link.(*IPoIB)
for _, datum := range data {
switch datum.Attr.Type {
case nl.IFLA_IPOIB_PKEY:
ipoib.Pkey = uint16(native.Uint16(datum.Value))
case nl.IFLA_IPOIB_MODE:
ipoib.Mode = IPoIBMode(native.Uint16(datum.Value))
case nl.IFLA_IPOIB_UMCAST:
ipoib.Umcast = uint16(native.Uint16(datum.Value))
}
}
}
func addIPoIBAttrs(ipoib *IPoIB, linkInfo *nl.RtAttr) {
data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil)
data.AddRtAttr(nl.IFLA_IPOIB_PKEY, nl.Uint16Attr(uint16(ipoib.Pkey)))
data.AddRtAttr(nl.IFLA_IPOIB_MODE, nl.Uint16Attr(uint16(ipoib.Mode)))
data.AddRtAttr(nl.IFLA_IPOIB_UMCAST, nl.Uint16Attr(uint16(ipoib.Umcast)))
}

View File

@ -17,6 +17,7 @@ type Neigh struct {
LLIPAddr net.IP //Used in the case of NHRP
Vlan int
VNI int
MasterIndex int
}
// String returns $ip/$hwaddr $label

View File

@ -1,6 +1,7 @@
package netlink
import (
"fmt"
"net"
"syscall"
"unsafe"
@ -20,7 +21,10 @@ const (
NDA_PORT
NDA_VNI
NDA_IFINDEX
NDA_MAX = NDA_IFINDEX
NDA_MASTER
NDA_LINK_NETNSID
NDA_SRC_VNI
NDA_MAX = NDA_SRC_VNI
)
// Neighbor Cache Entry States.
@ -45,6 +49,7 @@ const (
NTF_ROUTER = 0x80
)
// Ndmsg is for adding, removing or receiving information about a neighbor table entry
type Ndmsg struct {
Family uint8
Index uint32
@ -172,45 +177,58 @@ func neighHandle(neigh *Neigh, req *nl.NetlinkRequest) error {
req.AddData(vniData)
}
if neigh.MasterIndex != 0 {
masterData := nl.NewRtAttr(NDA_MASTER, nl.Uint32Attr(uint32(neigh.MasterIndex)))
req.AddData(masterData)
}
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
}
// NeighList gets a list of IP-MAC mappings in the system (ARP table).
// NeighList returns a list of IP-MAC mappings in the system (ARP table).
// Equivalent to: `ip neighbor show`.
// The list can be filtered by link and ip family.
func NeighList(linkIndex, family int) ([]Neigh, error) {
return pkgHandle.NeighList(linkIndex, family)
}
// NeighProxyList gets a list of neighbor proxies in the system.
// NeighProxyList returns a list of neighbor proxies in the system.
// Equivalent to: `ip neighbor show proxy`.
// The list can be filtered by link and ip family.
func NeighProxyList(linkIndex, family int) ([]Neigh, error) {
return pkgHandle.NeighProxyList(linkIndex, family)
}
// NeighList gets a list of IP-MAC mappings in the system (ARP table).
// NeighList returns a list of IP-MAC mappings in the system (ARP table).
// Equivalent to: `ip neighbor show`.
// The list can be filtered by link and ip family.
func (h *Handle) NeighList(linkIndex, family int) ([]Neigh, error) {
return h.neighList(linkIndex, family, 0)
return h.NeighListExecute(Ndmsg{
Family: uint8(family),
Index: uint32(linkIndex),
})
}
// NeighProxyList gets a list of neighbor proxies in the system.
// NeighProxyList returns a list of neighbor proxies in the system.
// Equivalent to: `ip neighbor show proxy`.
// The list can be filtered by link, ip family.
func (h *Handle) NeighProxyList(linkIndex, family int) ([]Neigh, error) {
return h.neighList(linkIndex, family, NTF_PROXY)
}
func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) {
req := h.newNetlinkRequest(unix.RTM_GETNEIGH, unix.NLM_F_DUMP)
msg := Ndmsg{
return h.NeighListExecute(Ndmsg{
Family: uint8(family),
Index: uint32(linkIndex),
Flags: uint8(flags),
}
Flags: NTF_PROXY,
})
}
// NeighListExecute returns a list of neighbour entries filtered by link, ip family, flag and state.
func NeighListExecute(msg Ndmsg) ([]Neigh, error) {
return pkgHandle.NeighListExecute(msg)
}
// NeighListExecute returns a list of neighbour entries filtered by link, ip family, flag and state.
func (h *Handle) NeighListExecute(msg Ndmsg) ([]Neigh, error) {
req := h.newNetlinkRequest(unix.RTM_GETNEIGH, unix.NLM_F_DUMP)
req.AddData(&msg)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNEIGH)
@ -221,7 +239,7 @@ func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) {
var res []Neigh
for _, m := range msgs {
ndm := deserializeNdmsg(m)
if linkIndex != 0 && int(ndm.Index) != linkIndex {
if msg.Index != 0 && ndm.Index != msg.Index {
// Ignore messages from other interfaces
continue
}
@ -253,14 +271,6 @@ func NeighDeserialize(m []byte) (*Neigh, error) {
return nil, err
}
// This should be cached for perfomance
// once per table dump
link, err := LinkByIndex(neigh.LinkIndex)
if err != nil {
return nil, err
}
encapType := link.Attrs().EncapType
for _, attr := range attrs {
switch attr.Attr.Type {
case NDA_DST:
@ -270,13 +280,16 @@ func NeighDeserialize(m []byte) (*Neigh, error) {
// #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len))
// #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0))
attrLen := attr.Attr.Len - unix.SizeofRtAttr
if attrLen == 4 && (encapType == "ipip" ||
encapType == "sit" ||
encapType == "gre") {
if attrLen == 4 {
neigh.LLIPAddr = net.IP(attr.Value)
} else if attrLen == 16 &&
encapType == "tunnel6" {
neigh.IP = net.IP(attr.Value)
} else if attrLen == 16 {
// Can be IPv6 or FireWire HWAddr
link, err := LinkByIndex(neigh.LinkIndex)
if err == nil && link.Attrs().EncapType == "tunnel6" {
neigh.IP = net.IP(attr.Value)
} else {
neigh.HardwareAddr = net.HardwareAddr(attr.Value)
}
} else {
neigh.HardwareAddr = net.HardwareAddr(attr.Value)
}
@ -284,6 +297,8 @@ func NeighDeserialize(m []byte) (*Neigh, error) {
neigh.Vlan = int(native.Uint16(attr.Value[0:2]))
case NDA_VNI:
neigh.VNI = int(native.Uint32(attr.Value[0:4]))
case NDA_MASTER:
neigh.MasterIndex = int(native.Uint32(attr.Value[0:4]))
}
}
@ -323,6 +338,16 @@ func NeighSubscribeWithOptions(ch chan<- NeighUpdate, done <-chan struct{}, opti
func neighSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- NeighUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error {
s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_NEIGH)
makeRequest := func(family int) error {
req := pkgHandle.newNetlinkRequest(unix.RTM_GETNEIGH,
unix.NLM_F_DUMP)
infmsg := nl.NewIfInfomsg(family)
req.AddData(infmsg)
if err := s.Send(req); err != nil {
return err
}
return nil
}
if err != nil {
return err
}
@ -333,26 +358,41 @@ func neighSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- NeighUpdate, done <
}()
}
if listExisting {
req := pkgHandle.newNetlinkRequest(unix.RTM_GETNEIGH,
unix.NLM_F_DUMP)
infmsg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(infmsg)
if err := s.Send(req); err != nil {
if err := makeRequest(unix.AF_UNSPEC); err != nil {
return err
}
// We have to wait for NLMSG_DONE before making AF_BRIDGE request
}
go func() {
defer close(ch)
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
if cberr != nil {
cberr(err)
}
return
}
if from.Pid != nl.PidKernel {
if cberr != nil {
cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel))
}
continue
}
for _, m := range msgs {
if m.Header.Type == unix.NLMSG_DONE {
if listExisting {
// This will be called after handling AF_UNSPEC
// list request, we have to wait for NLMSG_DONE
// before making another request
if err := makeRequest(unix.AF_BRIDGE); err != nil {
if cberr != nil {
cberr(err)
}
return
}
listExisting = false
}
continue
}
if m.Header.Type == unix.NLMSG_ERROR {

View File

@ -48,10 +48,18 @@ func LinkSetVfVlan(link Link, vf, vlan int) error {
return ErrNotImplemented
}
func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error {
return ErrNotImplemented
}
func LinkSetVfTxRate(link Link, vf, rate int) error {
return ErrNotImplemented
}
func LinkSetVfRate(link Link, vf, minRate, maxRate int) error {
return ErrNotImplemented
}
func LinkSetNoMaster(link Link) error {
return ErrNotImplemented
}
@ -152,6 +160,10 @@ func AddrAdd(link Link, addr *Addr) error {
return ErrNotImplemented
}
func AddrReplace(link Link, addr *Addr) error {
return ErrNotImplemented
}
func AddrDel(link Link, addr *Addr) error {
return ErrNotImplemented
}

View File

@ -51,14 +51,14 @@ func SetNetNsIdByPid(pid, nsid int) error {
return pkgHandle.SetNetNsIdByPid(pid, nsid)
}
// GetNetNsIdByPid looks up the network namespace ID for a given fd.
// GetNetNsIdByFd looks up the network namespace ID for a given fd.
// fd must be an open file descriptor to a namespace file.
// Returns -1 if the namespace does not have an ID set.
func (h *Handle) GetNetNsIdByFd(fd int) (int, error) {
return h.getNetNsId(NETNSA_FD, uint32(fd))
}
// GetNetNsIdByPid looks up the network namespace ID for a given fd.
// GetNetNsIdByFd looks up the network namespace ID for a given fd.
// fd must be an open file descriptor to a namespace file.
// Returns -1 if the namespace does not have an ID set.
func GetNetNsIdByFd(fd int) (int, error) {

View File

@ -79,11 +79,14 @@ const (
CTA_TUPLE_ORIG = 1
CTA_TUPLE_REPLY = 2
CTA_STATUS = 3
CTA_PROTOINFO = 4
CTA_TIMEOUT = 7
CTA_MARK = 8
CTA_COUNTERS_ORIG = 9
CTA_COUNTERS_REPLY = 10
CTA_PROTOINFO = 4
CTA_USE = 11
CTA_ID = 12
CTA_TIMESTAMP = 20
)
// enum ctattr_tuple {
@ -180,6 +183,14 @@ const (
CTA_COUNTERS_BYTES = 2
)
// enum CTA TIMESTAMP TLVs
// CTA_TIMESTAMP_START /* 64bit value */
// CTA_TIMESTAMP_STOP /* 64bit value */
const (
CTA_TIMESTAMP_START = 1
CTA_TIMESTAMP_STOP = 2
)
// /* General form of address family dependent message.
// */
// struct nfgenmsg {

View File

@ -0,0 +1,40 @@
package nl
// All the following constants are coming from:
// https://github.com/torvalds/linux/blob/master/include/uapi/linux/devlink.h
const (
GENL_DEVLINK_VERSION = 1
GENL_DEVLINK_NAME = "devlink"
)
const (
DEVLINK_CMD_GET = 1
DEVLINK_CMD_ESWITCH_GET = 29
DEVLINK_CMD_ESWITCH_SET = 30
)
const (
DEVLINK_ATTR_BUS_NAME = 1
DEVLINK_ATTR_DEV_NAME = 2
DEVLINK_ATTR_ESWITCH_MODE = 25
DEVLINK_ATTR_ESWITCH_INLINE_MODE = 26
DEVLINK_ATTR_ESWITCH_ENCAP_MODE = 62
)
const (
DEVLINK_ESWITCH_MODE_LEGACY = 0
DEVLINK_ESWITCH_MODE_SWITCHDEV = 1
)
const (
DEVLINK_ESWITCH_INLINE_MODE_NONE = 0
DEVLINK_ESWITCH_INLINE_MODE_LINK = 1
DEVLINK_ESWITCH_INLINE_MODE_NETWORK = 2
DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT = 3
)
const (
DEVLINK_ESWITCH_ENCAP_MODE_NONE = 0
DEVLINK_ESWITCH_ENCAP_MODE_BASIC = 1
)

View File

@ -13,7 +13,9 @@ const (
IFLA_INFO_KIND
IFLA_INFO_DATA
IFLA_INFO_XSTATS
IFLA_INFO_MAX = IFLA_INFO_XSTATS
IFLA_INFO_SLAVE_KIND
IFLA_INFO_SLAVE_DATA
IFLA_INFO_MAX = IFLA_INFO_SLAVE_DATA
)
const (
@ -87,7 +89,8 @@ const (
const (
IFLA_IPVLAN_UNSPEC = iota
IFLA_IPVLAN_MODE
IFLA_IPVLAN_MAX = IFLA_IPVLAN_MODE
IFLA_IPVLAN_FLAG
IFLA_IPVLAN_MAX = IFLA_IPVLAN_FLAG
)
const (
@ -164,6 +167,8 @@ const (
IFLA_BOND_SLAVE_PERM_HWADDR
IFLA_BOND_SLAVE_QUEUE_ID
IFLA_BOND_SLAVE_AD_AGGREGATOR_ID
IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE
IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE
)
const (
@ -573,3 +578,33 @@ const (
GTP_ROLE_GGSN = iota
GTP_ROLE_SGSN
)
const (
IFLA_XFRM_UNSPEC = iota
IFLA_XFRM_LINK
IFLA_XFRM_IF_ID
IFLA_XFRM_MAX = iota - 1
)
const (
IFLA_TUN_UNSPEC = iota
IFLA_TUN_OWNER
IFLA_TUN_GROUP
IFLA_TUN_TYPE
IFLA_TUN_PI
IFLA_TUN_VNET_HDR
IFLA_TUN_PERSIST
IFLA_TUN_MULTI_QUEUE
IFLA_TUN_NUM_QUEUES
IFLA_TUN_NUM_DISABLED_QUEUES
IFLA_TUN_MAX = IFLA_TUN_NUM_DISABLED_QUEUES
)
const (
IFLA_IPOIB_UNSPEC = iota
IFLA_IPOIB_PKEY
IFLA_IPOIB_MODE
IFLA_IPOIB_UMCAST
IFLA_IPOIB_MAX = IFLA_IPOIB_UMCAST
)

View File

@ -21,11 +21,13 @@ const (
FAMILY_ALL = unix.AF_UNSPEC
FAMILY_V4 = unix.AF_INET
FAMILY_V6 = unix.AF_INET6
FAMILY_MPLS = AF_MPLS
FAMILY_MPLS = unix.AF_MPLS
// Arbitrary set value (greater than default 4k) to allow receiving
// from kernel more verbose messages e.g. for statistics,
// tc rules or filters, or other more memory requiring data.
RECEIVE_BUFFER_SIZE = 65536
// Kernel netlink pid
PidKernel uint32 = 0
)
// SupportedNlFamilies contains the list of netlink families this netlink package supports
@ -46,7 +48,7 @@ func GetIPFamily(ip net.IP) int {
var nativeEndian binary.ByteOrder
// Get native endianness for the system
// NativeEndian gets native endianness for the system
func NativeEndian() binary.ByteOrder {
if nativeEndian == nil {
var x uint32 = 0x01020304
@ -420,10 +422,13 @@ func (req *NetlinkRequest) Execute(sockType int, resType uint16) ([][]byte, erro
done:
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
return nil, err
}
if from.Pid != PidKernel {
return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, PidKernel)
}
for _, m := range msgs {
if m.Header.Seq != req.Seq {
if sharedSocket {
@ -432,7 +437,7 @@ done:
return nil, fmt.Errorf("Wrong Seq nr %d, expected %d", m.Header.Seq, req.Seq)
}
if m.Header.Pid != pid {
return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid)
continue
}
if m.Header.Type == unix.NLMSG_DONE {
break done
@ -617,21 +622,31 @@ func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
return nil
}
func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, *unix.SockaddrNetlink, error) {
fd := int(atomic.LoadInt32(&s.fd))
if fd < 0 {
return nil, fmt.Errorf("Receive called on a closed socket")
return nil, nil, fmt.Errorf("Receive called on a closed socket")
}
rb := make([]byte, RECEIVE_BUFFER_SIZE)
nr, _, err := unix.Recvfrom(fd, rb, 0)
var fromAddr *unix.SockaddrNetlink
var rb [RECEIVE_BUFFER_SIZE]byte
nr, from, err := unix.Recvfrom(fd, rb[:], 0)
if err != nil {
return nil, err
return nil, nil, err
}
fromAddr, ok := from.(*unix.SockaddrNetlink)
if !ok {
return nil, nil, fmt.Errorf("Error converting to netlink sockaddr")
}
if nr < unix.NLMSG_HDRLEN {
return nil, fmt.Errorf("Got short response from netlink")
return nil, nil, fmt.Errorf("Got short response from netlink")
}
rb = rb[:nr]
return syscall.ParseNetlinkMessage(rb)
rb2 := make([]byte, nr)
copy(rb2, rb[:nr])
nl, err := syscall.ParseNetlinkMessage(rb2)
if err != nil {
return nil, nil, err
}
return nl, fromAddr, nil
}
// SetSendTimeout allows to set a send timeout on the socket

View File

@ -9,8 +9,10 @@ const (
)
const (
RDMA_NLDEV_CMD_GET = 1
RDMA_NLDEV_CMD_SET = 2
RDMA_NLDEV_CMD_GET = 1
RDMA_NLDEV_CMD_SET = 2
RDMA_NLDEV_CMD_SYS_GET = 6
RDMA_NLDEV_CMD_SYS_SET = 7
)
const (
@ -28,4 +30,6 @@ const (
RDMA_NLDEV_ATTR_PORT_STATE = 12
RDMA_NLDEV_ATTR_PORT_PHYS_STATE = 13
RDMA_NLDEV_ATTR_DEV_NODE_TYPE = 14
RDMA_NLDEV_SYS_ATTR_NETNS_MODE = 66
RDMA_NLDEV_NET_NS_FD = 68
)

View File

@ -42,16 +42,6 @@ const (
TCPDIAG_NOCOOKIE = 0xFFFFFFFF /* TCPDIAG_NOCOOKIE in net/ipv4/tcp_diag.h*/
)
const (
AF_MPLS = 28
)
const (
RTA_NEWDST = 0x13
RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16
)
// RTA_ENCAP subtype
const (
MPLS_IPTUNNEL_UNSPEC = iota

View File

@ -89,7 +89,10 @@ const (
SizeofTcU32Key = 0x10
SizeofTcU32Sel = 0x10 // without keys
SizeofTcGen = 0x14
SizeofTcConnmark = SizeofTcGen + 0x04
SizeofTcMirred = SizeofTcGen + 0x08
SizeofTcTunnelKey = SizeofTcGen + 0x04
SizeofTcSkbEdit = SizeofTcGen
SizeofTcPolice = 2*SizeofTcRateSpec + 0x20
)
@ -647,11 +650,47 @@ const (
TCA_BPF_FD
TCA_BPF_NAME
TCA_BPF_FLAGS
TCA_BPF_MAX = TCA_BPF_FLAGS
TCA_BPF_FLAGS_GEN
TCA_BPF_TAG
TCA_BPF_ID
TCA_BPF_MAX = TCA_BPF_ID
)
type TcBpf TcGen
const (
TCA_ACT_CONNMARK = 14
)
const (
TCA_CONNMARK_UNSPEC = iota
TCA_CONNMARK_PARMS
TCA_CONNMARK_TM
TCA_CONNMARK_MAX = TCA_CONNMARK_TM
)
// struct tc_connmark {
// tc_gen;
// __u16 zone;
// };
type TcConnmark struct {
TcGen
Zone uint16
}
func (msg *TcConnmark) Len() int {
return SizeofTcConnmark
}
func DeserializeTcConnmark(b []byte) *TcConnmark {
return (*TcConnmark)(unsafe.Pointer(&b[0:SizeofTcConnmark][0]))
}
func (x *TcConnmark) Serialize() []byte {
return (*(*[SizeofTcConnmark]byte)(unsafe.Pointer(x)))[:]
}
const (
TCA_ACT_MIRRED = 8
)
@ -687,6 +726,63 @@ func (x *TcMirred) Serialize() []byte {
return (*(*[SizeofTcMirred]byte)(unsafe.Pointer(x)))[:]
}
const (
TCA_TUNNEL_KEY_UNSPEC = iota
TCA_TUNNEL_KEY_TM
TCA_TUNNEL_KEY_PARMS
TCA_TUNNEL_KEY_ENC_IPV4_SRC
TCA_TUNNEL_KEY_ENC_IPV4_DST
TCA_TUNNEL_KEY_ENC_IPV6_SRC
TCA_TUNNEL_KEY_ENC_IPV6_DST
TCA_TUNNEL_KEY_ENC_KEY_ID
TCA_TUNNEL_KEY_MAX = TCA_TUNNEL_KEY_ENC_KEY_ID
)
type TcTunnelKey struct {
TcGen
Action int32
}
func (x *TcTunnelKey) Len() int {
return SizeofTcTunnelKey
}
func DeserializeTunnelKey(b []byte) *TcTunnelKey {
return (*TcTunnelKey)(unsafe.Pointer(&b[0:SizeofTcTunnelKey][0]))
}
func (x *TcTunnelKey) Serialize() []byte {
return (*(*[SizeofTcTunnelKey]byte)(unsafe.Pointer(x)))[:]
}
const (
TCA_SKBEDIT_UNSPEC = iota
TCA_SKBEDIT_TM
TCA_SKBEDIT_PARMS
TCA_SKBEDIT_PRIORITY
TCA_SKBEDIT_QUEUE_MAPPING
TCA_SKBEDIT_MARK
TCA_SKBEDIT_PAD
TCA_SKBEDIT_PTYPE
TCA_SKBEDIT_MAX = TCA_SKBEDIT_MARK
)
type TcSkbEdit struct {
TcGen
}
func (x *TcSkbEdit) Len() int {
return SizeofTcSkbEdit
}
func DeserializeSkbEdit(b []byte) *TcSkbEdit {
return (*TcSkbEdit)(unsafe.Pointer(&b[0:SizeofTcSkbEdit][0]))
}
func (x *TcSkbEdit) Serialize() []byte {
return (*(*[SizeofTcSkbEdit]byte)(unsafe.Pointer(x)))[:]
}
// struct tc_police {
// __u32 index;
// int action;

View File

@ -50,34 +50,44 @@ const (
// Attribute types
const (
/* Netlink message attributes. */
XFRMA_UNSPEC = 0x00
XFRMA_ALG_AUTH = 0x01 /* struct xfrm_algo */
XFRMA_ALG_CRYPT = 0x02 /* struct xfrm_algo */
XFRMA_ALG_COMP = 0x03 /* struct xfrm_algo */
XFRMA_ENCAP = 0x04 /* struct xfrm_algo + struct xfrm_encap_tmpl */
XFRMA_TMPL = 0x05 /* 1 or more struct xfrm_user_tmpl */
XFRMA_SA = 0x06 /* struct xfrm_usersa_info */
XFRMA_POLICY = 0x07 /* struct xfrm_userpolicy_info */
XFRMA_SEC_CTX = 0x08 /* struct xfrm_sec_ctx */
XFRMA_LTIME_VAL = 0x09
XFRMA_REPLAY_VAL = 0x0a
XFRMA_REPLAY_THRESH = 0x0b
XFRMA_ETIMER_THRESH = 0x0c
XFRMA_SRCADDR = 0x0d /* xfrm_address_t */
XFRMA_COADDR = 0x0e /* xfrm_address_t */
XFRMA_LASTUSED = 0x0f /* unsigned long */
XFRMA_POLICY_TYPE = 0x10 /* struct xfrm_userpolicy_type */
XFRMA_MIGRATE = 0x11
XFRMA_ALG_AEAD = 0x12 /* struct xfrm_algo_aead */
XFRMA_KMADDRESS = 0x13 /* struct xfrm_user_kmaddress */
XFRMA_ALG_AUTH_TRUNC = 0x14 /* struct xfrm_algo_auth */
XFRMA_MARK = 0x15 /* struct xfrm_mark */
XFRMA_TFCPAD = 0x16 /* __u32 */
XFRMA_REPLAY_ESN_VAL = 0x17 /* struct xfrm_replay_esn */
XFRMA_SA_EXTRA_FLAGS = 0x18 /* __u32 */
XFRMA_MAX = 0x18
XFRMA_UNSPEC = iota
XFRMA_ALG_AUTH /* struct xfrm_algo */
XFRMA_ALG_CRYPT /* struct xfrm_algo */
XFRMA_ALG_COMP /* struct xfrm_algo */
XFRMA_ENCAP /* struct xfrm_algo + struct xfrm_encap_tmpl */
XFRMA_TMPL /* 1 or more struct xfrm_user_tmpl */
XFRMA_SA /* struct xfrm_usersa_info */
XFRMA_POLICY /* struct xfrm_userpolicy_info */
XFRMA_SEC_CTX /* struct xfrm_sec_ctx */
XFRMA_LTIME_VAL
XFRMA_REPLAY_VAL
XFRMA_REPLAY_THRESH
XFRMA_ETIMER_THRESH
XFRMA_SRCADDR /* xfrm_address_t */
XFRMA_COADDR /* xfrm_address_t */
XFRMA_LASTUSED /* unsigned long */
XFRMA_POLICY_TYPE /* struct xfrm_userpolicy_type */
XFRMA_MIGRATE
XFRMA_ALG_AEAD /* struct xfrm_algo_aead */
XFRMA_KMADDRESS /* struct xfrm_user_kmaddress */
XFRMA_ALG_AUTH_TRUNC /* struct xfrm_algo_auth */
XFRMA_MARK /* struct xfrm_mark */
XFRMA_TFCPAD /* __u32 */
XFRMA_REPLAY_ESN_VAL /* struct xfrm_replay_esn */
XFRMA_SA_EXTRA_FLAGS /* __u32 */
XFRMA_PROTO /* __u8 */
XFRMA_ADDRESS_FILTER /* struct xfrm_address_filter */
XFRMA_PAD
XFRMA_OFFLOAD_DEV /* struct xfrm_state_offload */
XFRMA_SET_MARK /* __u32 */
XFRMA_SET_MARK_MASK /* __u32 */
XFRMA_IF_ID /* __u32 */
XFRMA_MAX = iota - 1
)
const XFRMA_OUTPUT_MARK = XFRMA_SET_MARK
const (
SizeofXfrmAddress = 0x10
SizeofXfrmSelector = 0x38

View File

@ -285,7 +285,7 @@ type Fq struct {
func (fq *Fq) String() string {
return fmt.Sprintf(
"{PacketLimit: %v, FlowPacketLimit: %v, Quantum: %v, InitalQuantum: %v, Pacing: %v, FlowDefaultRate: %v, FlowMaxRate: %v, Buckets: %v, FlowRefillDelay: %v, LowRateTreshold: %v}",
"{PacketLimit: %v, FlowPacketLimit: %v, Quantum: %v, InitialQuantum: %v, Pacing: %v, FlowDefaultRate: %v, FlowMaxRate: %v, Buckets: %v, FlowRefillDelay: %v, LowRateThreshold: %v}",
fq.PacketLimit, fq.FlowPacketLimit, fq.Quantum, fq.InitialQuantum, fq.Pacing, fq.FlowDefaultRate, fq.FlowMaxRate, fq.Buckets, fq.FlowRefillDelay, fq.LowRateThreshold,
)
}

View File

@ -143,3 +143,122 @@ func (h *Handle) RdmaLinkSetName(link *RdmaLink, name string) error {
return execRdmaSetLink(req)
}
func netnsModeToString(mode uint8) string {
switch mode {
case 0:
return "exclusive"
case 1:
return "shared"
default:
return "unknown"
}
}
func executeOneGetRdmaNetnsMode(data []byte) (string, error) {
reader := bytes.NewReader(data)
for reader.Len() >= 4 {
_, attrType, len, value := parseNfAttrTLV(reader)
switch attrType {
case nl.RDMA_NLDEV_SYS_ATTR_NETNS_MODE:
var mode uint8
r := bytes.NewReader(value)
binary.Read(r, nl.NativeEndian(), &mode)
return netnsModeToString(mode), nil
}
if (len % 4) != 0 {
// Skip pad bytes
reader.Seek(int64(4-(len%4)), seekCurrent)
}
}
return "", fmt.Errorf("Invalid netns mode")
}
// RdmaSystemGetNetnsMode gets the net namespace mode for RDMA subsystem
// Returns mode string and error status as nil on success or returns error
// otherwise.
// Equivalent to: `rdma system show netns'
func RdmaSystemGetNetnsMode() (string, error) {
return pkgHandle.RdmaSystemGetNetnsMode()
}
// RdmaSystemGetNetnsMode gets the net namespace mode for RDMA subsystem
// Returns mode string and error status as nil on success or returns error
// otherwise.
// Equivalent to: `rdma system show netns'
func (h *Handle) RdmaSystemGetNetnsMode() (string, error) {
proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SYS_GET)
req := h.newNetlinkRequest(proto, unix.NLM_F_ACK)
msgs, err := req.Execute(unix.NETLINK_RDMA, 0)
if err != nil {
return "", err
}
if len(msgs) == 0 {
return "", fmt.Errorf("No valid response from kernel")
}
return executeOneGetRdmaNetnsMode(msgs[0])
}
func netnsModeStringToUint8(mode string) (uint8, error) {
switch mode {
case "exclusive":
return 0, nil
case "shared":
return 1, nil
default:
return 0, fmt.Errorf("Invalid mode; %q", mode)
}
}
// RdmaSystemSetNetnsMode sets the net namespace mode for RDMA subsystem
// Returns nil on success or appropriate error code.
// Equivalent to: `rdma system set netns { shared | exclusive }'
func RdmaSystemSetNetnsMode(NewMode string) error {
return pkgHandle.RdmaSystemSetNetnsMode(NewMode)
}
// RdmaSystemSetNetnsMode sets the net namespace mode for RDMA subsystem
// Returns nil on success or appropriate error code.
// Equivalent to: `rdma system set netns { shared | exclusive }'
func (h *Handle) RdmaSystemSetNetnsMode(NewMode string) error {
value, err := netnsModeStringToUint8(NewMode)
if err != nil {
return err
}
proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SYS_SET)
req := h.newNetlinkRequest(proto, unix.NLM_F_ACK)
data := nl.NewRtAttr(nl.RDMA_NLDEV_SYS_ATTR_NETNS_MODE, []byte{value})
req.AddData(data)
_, err = req.Execute(unix.NETLINK_RDMA, 0)
return err
}
// RdmaLinkSetNsFd puts the RDMA device into a new network namespace. The
// fd must be an open file descriptor to a network namespace.
// Similar to: `rdma dev set $dev netns $ns`
func RdmaLinkSetNsFd(link *RdmaLink, fd uint32) error {
return pkgHandle.RdmaLinkSetNsFd(link, fd)
}
// RdmaLinkSetNsFd puts the RDMA device into a new network namespace. The
// fd must be an open file descriptor to a network namespace.
// Similar to: `rdma dev set $dev netns $ns`
func (h *Handle) RdmaLinkSetNsFd(link *RdmaLink, fd uint32) error {
proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SET)
req := h.newNetlinkRequest(proto, unix.NLM_F_ACK)
data := nl.NewRtAttr(nl.RDMA_NLDEV_ATTR_DEV_INDEX,
nl.Uint32Attr(link.Attrs.Index))
req.AddData(data)
data = nl.NewRtAttr(nl.RDMA_NLDEV_NET_NS_FD, nl.Uint32Attr(fd))
req.AddData(data)
return execRdmaSetLink(req)
}

View File

@ -261,7 +261,7 @@ func (e *SEG6Encap) Equal(x Encap) bool {
return true
}
// SEG6Local definitions
// SEG6LocalEncap definitions
type SEG6LocalEncap struct {
Flags [nl.SEG6_LOCAL_MAX]bool
Action int
@ -519,18 +519,18 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
if err != nil {
return err
}
rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_NEWDST, buf))
rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_NEWDST, buf))
}
if route.Encap != nil {
buf := make([]byte, 2)
native.PutUint16(buf, uint16(route.Encap.Type()))
rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP_TYPE, buf))
rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_ENCAP_TYPE, buf))
buf, err := route.Encap.Encode()
if err != nil {
return err
}
rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP, buf))
rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_ENCAP, buf))
}
if route.Src != nil {
@ -594,17 +594,17 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
if err != nil {
return err
}
children = append(children, nl.NewRtAttr(nl.RTA_NEWDST, buf))
children = append(children, nl.NewRtAttr(unix.RTA_NEWDST, buf))
}
if nh.Encap != nil {
buf := make([]byte, 2)
native.PutUint16(buf, uint16(nh.Encap.Type()))
rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP_TYPE, buf))
children = append(children, nl.NewRtAttr(unix.RTA_ENCAP_TYPE, buf))
buf, err := nh.Encap.Encode()
if err != nil {
return err
}
children = append(children, nl.NewRtAttr(nl.RTA_ENCAP, buf))
children = append(children, nl.NewRtAttr(unix.RTA_ENCAP, buf))
}
rtnh.Children = children
buf = append(buf, rtnh.Serialize()...)
@ -839,7 +839,7 @@ func deserializeRoute(m []byte) (Route, error) {
switch attr.Attr.Type {
case unix.RTA_GATEWAY:
info.Gw = net.IP(attr.Value)
case nl.RTA_NEWDST:
case unix.RTA_NEWDST:
var d Destination
switch msg.Family {
case nl.FAMILY_MPLS:
@ -849,9 +849,9 @@ func deserializeRoute(m []byte) (Route, error) {
return nil, nil, err
}
info.NewDst = d
case nl.RTA_ENCAP_TYPE:
case unix.RTA_ENCAP_TYPE:
encapType = attr
case nl.RTA_ENCAP:
case unix.RTA_ENCAP:
encap = attr
}
}
@ -880,7 +880,7 @@ func deserializeRoute(m []byte) (Route, error) {
route.MultiPath = append(route.MultiPath, info)
rest = buf
}
case nl.RTA_NEWDST:
case unix.RTA_NEWDST:
var d Destination
switch msg.Family {
case nl.FAMILY_MPLS:
@ -890,9 +890,9 @@ func deserializeRoute(m []byte) (Route, error) {
return route, err
}
route.NewDst = d
case nl.RTA_ENCAP_TYPE:
case unix.RTA_ENCAP_TYPE:
encapType = attr
case nl.RTA_ENCAP:
case unix.RTA_ENCAP:
encap = attr
case unix.RTA_METRICS:
metrics, err := nl.ParseRouteAttr(attr.Value)
@ -1037,13 +1037,19 @@ func routeSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- RouteUpdate, done <
go func() {
defer close(ch)
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
if cberr != nil {
cberr(err)
}
return
}
if from.Pid != nl.PidKernel {
if cberr != nil {
cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel))
}
continue
}
for _, m := range msgs {
if m.Header.Type == unix.NLMSG_DONE {
continue

View File

@ -144,7 +144,7 @@ func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
req.AddData(nl.NewRtAttr(nl.FRA_OIFNAME, []byte(rule.OifName)))
}
if rule.Goto >= 0 {
msg.Type = nl.FR_ACT_NOP
msg.Type = nl.FR_ACT_GOTO
b := make([]byte, 4)
native.PutUint32(b, uint32(rule.Goto))
req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b))

View File

@ -141,10 +141,13 @@ func SocketGet(local, remote net.Addr) (*Socket, error) {
},
})
s.Send(req)
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
return nil, err
}
if from.Pid != nl.PidKernel {
return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)
}
if len(msgs) == 0 {
return nil, errors.New("no message nor error from netlink")
}

View File

@ -54,11 +54,15 @@ func XfrmMonitor(ch chan<- XfrmMsg, done <-chan struct{}, errorChan chan<- error
go func() {
defer close(ch)
for {
msgs, err := s.Receive()
msgs, from, err := s.Receive()
if err != nil {
errorChan <- err
return
}
if from.Pid != nl.PidKernel {
errorChan <- fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)
return
}
for _, m := range msgs {
switch m.Header.Type {
case nl.XFRM_MSG_EXPIRE:

View File

@ -85,11 +85,12 @@ type XfrmPolicy struct {
Index int
Action PolicyAction
Ifindex int
Ifid int
Mark *XfrmMark
Tmpls []XfrmPolicyTmpl
}
func (p XfrmPolicy) String() string {
return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, DstPort: %d, SrcPort: %d, Dir: %s, Priority: %d, Index: %d, Action: %s, Ifindex: %d, Mark: %s, Tmpls: %s}",
p.Dst, p.Src, p.Proto, p.DstPort, p.SrcPort, p.Dir, p.Priority, p.Index, p.Action, p.Ifindex, p.Mark, p.Tmpls)
return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, DstPort: %d, SrcPort: %d, Dir: %s, Priority: %d, Index: %d, Action: %s, Ifindex: %d, Ifid: %d, Mark: %s, Tmpls: %s}",
p.Dst, p.Src, p.Proto, p.DstPort, p.SrcPort, p.Dir, p.Priority, p.Index, p.Action, p.Ifindex, p.Ifid, p.Mark, p.Tmpls)
}

View File

@ -92,6 +92,9 @@ func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error {
req.AddData(out)
}
ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(policy.Ifid)))
req.AddData(ifId)
_, err := req.Execute(unix.NETLINK_XFRM, 0)
return err
}
@ -185,6 +188,9 @@ func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPo
req.AddData(out)
}
ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(policy.Ifid)))
req.AddData(ifId)
resType := nl.XFRM_MSG_NEWPOLICY
if nlProto == nl.XFRM_MSG_DELPOLICY {
resType = 0
@ -248,6 +254,8 @@ func parseXfrmPolicy(m []byte, family int) (*XfrmPolicy, error) {
policy.Mark = new(XfrmMark)
policy.Mark.Value = mark.Value
policy.Mark.Mask = mark.Mask
case nl.XFRMA_IF_ID:
policy.Ifid = int(native.Uint32(attr.Value))
}
}

View File

@ -94,6 +94,8 @@ type XfrmState struct {
Limits XfrmStateLimits
Statistics XfrmStateStats
Mark *XfrmMark
OutputMark int
Ifid int
Auth *XfrmStateAlgo
Crypt *XfrmStateAlgo
Aead *XfrmStateAlgo
@ -102,8 +104,8 @@ type XfrmState struct {
}
func (sa XfrmState) String() string {
return fmt.Sprintf("Dst: %v, Src: %v, Proto: %s, Mode: %s, SPI: 0x%x, ReqID: 0x%x, ReplayWindow: %d, Mark: %v, Auth: %v, Crypt: %v, Aead: %v, Encap: %v, ESN: %t",
sa.Dst, sa.Src, sa.Proto, sa.Mode, sa.Spi, sa.Reqid, sa.ReplayWindow, sa.Mark, sa.Auth, sa.Crypt, sa.Aead, sa.Encap, sa.ESN)
return fmt.Sprintf("Dst: %v, Src: %v, Proto: %s, Mode: %s, SPI: 0x%x, ReqID: 0x%x, ReplayWindow: %d, Mark: %v, OutputMark: %d, Ifid: %d, Auth: %v, Crypt: %v, Aead: %v, Encap: %v, ESN: %t",
sa.Dst, sa.Src, sa.Proto, sa.Mode, sa.Spi, sa.Reqid, sa.ReplayWindow, sa.Mark, sa.OutputMark, sa.Ifid, sa.Auth, sa.Crypt, sa.Aead, sa.Encap, sa.ESN)
}
func (sa XfrmState) Print(stats bool) string {
if !stats {

View File

@ -158,6 +158,13 @@ func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
out := nl.NewRtAttr(nl.XFRMA_REPLAY_ESN_VAL, writeReplayEsn(state.ReplayWindow))
req.AddData(out)
}
if state.OutputMark != 0 {
out := nl.NewRtAttr(nl.XFRMA_OUTPUT_MARK, nl.Uint32Attr(uint32(state.OutputMark)))
req.AddData(out)
}
ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid)))
req.AddData(ifId)
_, err := req.Execute(unix.NETLINK_XFRM, 0)
return err
@ -270,6 +277,9 @@ func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState
req.AddData(out)
}
ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid)))
req.AddData(ifId)
resType := nl.XFRM_MSG_NEWSA
if nlProto == nl.XFRM_MSG_DELSA {
resType = 0
@ -367,6 +377,10 @@ func parseXfrmState(m []byte, family int) (*XfrmState, error) {
state.Mark = new(XfrmMark)
state.Mark.Value = mark.Value
state.Mark.Mask = mark.Mask
case nl.XFRMA_OUTPUT_MARK:
state.OutputMark = int(native.Uint32(attr.Value))
case nl.XFRMA_IF_ID:
state.Ifid = int(native.Uint32(attr.Value))
}
}

View File

@ -37,7 +37,6 @@ func main() {
// Create a new network namespace
newns, _ := netns.New()
netns.Set(newns)
defer newns.Close()
// Do something with the network namespace

5
vendor/github.com/vishvananda/netns/go.mod generated vendored Normal file
View File

@ -0,0 +1,5 @@
module github.com/vishvananda/netns
go 1.12
require golang.org/x/sys v0.0.0-20200217220822-9197077df867

2
vendor/github.com/vishvananda/netns/go.sum generated vendored Normal file
View File

@ -0,0 +1,2 @@
golang.org/x/sys v0.0.0-20200217220822-9197077df867 h1:JoRuNIf+rpHl+VhScRQQvzbHed86tKkqwPMV34T8myw=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@ -10,7 +10,8 @@ package netns
import (
"fmt"
"syscall"
"golang.org/x/sys/unix"
)
// NsHandle is a handle to a network namespace. It can be cast directly
@ -24,11 +25,11 @@ func (ns NsHandle) Equal(other NsHandle) bool {
if ns == other {
return true
}
var s1, s2 syscall.Stat_t
if err := syscall.Fstat(int(ns), &s1); err != nil {
var s1, s2 unix.Stat_t
if err := unix.Fstat(int(ns), &s1); err != nil {
return false
}
if err := syscall.Fstat(int(other), &s2); err != nil {
if err := unix.Fstat(int(other), &s2); err != nil {
return false
}
return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
@ -36,11 +37,11 @@ func (ns NsHandle) Equal(other NsHandle) bool {
// String shows the file descriptor number and its dev and inode.
func (ns NsHandle) String() string {
var s syscall.Stat_t
if ns == -1 {
return "NS(None)"
}
if err := syscall.Fstat(int(ns), &s); err != nil {
var s unix.Stat_t
if err := unix.Fstat(int(ns), &s); err != nil {
return fmt.Sprintf("NS(%d: unknown)", ns)
}
return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
@ -49,11 +50,11 @@ func (ns NsHandle) String() string {
// UniqueId returns a string which uniquely identifies the namespace
// associated with the network handle.
func (ns NsHandle) UniqueId() string {
var s syscall.Stat_t
if ns == -1 {
return "NS(none)"
}
if err := syscall.Fstat(int(ns), &s); err != nil {
var s unix.Stat_t
if err := unix.Fstat(int(ns), &s); err != nil {
return "NS(unknown)"
}
return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino)
@ -67,7 +68,7 @@ func (ns NsHandle) IsOpen() bool {
// Close closes the NsHandle and resets its file descriptor to -1.
// It is not safe to use an NsHandle after Close() is called.
func (ns *NsHandle) Close() error {
if err := syscall.Close(int(*ns)); err != nil {
if err := unix.Close(int(*ns)); err != nil {
return err
}
(*ns) = -1

View File

@ -6,44 +6,30 @@ import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
)
// SYS_SETNS syscall allows changing the namespace of the current process.
var SYS_SETNS = map[string]uintptr{
"386": 346,
"amd64": 308,
"arm64": 268,
"arm": 375,
"mips": 4344,
"mipsle": 4344,
"ppc64": 350,
"ppc64le": 350,
"s390x": 339,
}[runtime.GOARCH]
"golang.org/x/sys/unix"
)
// Deprecated: use syscall pkg instead (go >= 1.5 needed).
const (
CLONE_NEWUTS = 0x04000000 /* New utsname group? */
CLONE_NEWIPC = 0x08000000 /* New ipcs */
CLONE_NEWUSER = 0x10000000 /* New user namespace */
CLONE_NEWPID = 0x20000000 /* New pid namespace */
CLONE_NEWNET = 0x40000000 /* New network namespace */
CLONE_IO = 0x80000000 /* Get io context */
CLONE_NEWUTS = 0x04000000 /* New utsname group? */
CLONE_NEWIPC = 0x08000000 /* New ipcs */
CLONE_NEWUSER = 0x10000000 /* New user namespace */
CLONE_NEWPID = 0x20000000 /* New pid namespace */
CLONE_NEWNET = 0x40000000 /* New network namespace */
CLONE_IO = 0x80000000 /* Get io context */
bindMountPath = "/run/netns" /* Bind mount path for named netns */
)
// Setns sets namespace using syscall. Note that this should be a method
// in syscall but it has not been added.
func Setns(ns NsHandle, nstype int) (err error) {
_, _, e1 := syscall.Syscall(SYS_SETNS, uintptr(ns), uintptr(nstype), 0)
if e1 != 0 {
err = e1
}
return
return unix.Setns(int(ns), nstype)
}
// Set sets the current network namespace to the namespace represented
@ -52,23 +38,67 @@ func Set(ns NsHandle) (err error) {
return Setns(ns, CLONE_NEWNET)
}
// New creates a new network namespace and returns a handle to it.
// New creates a new network namespace, sets it as current and returns
// a handle to it.
func New() (ns NsHandle, err error) {
if err := syscall.Unshare(CLONE_NEWNET); err != nil {
if err := unix.Unshare(CLONE_NEWNET); err != nil {
return -1, err
}
return Get()
}
// NewNamed creates a new named network namespace and returns a handle to it
func NewNamed(name string) (NsHandle, error) {
if _, err := os.Stat(bindMountPath); os.IsNotExist(err) {
err = os.MkdirAll(bindMountPath, 0755)
if err != nil {
return None(), err
}
}
newNs, err := New()
if err != nil {
return None(), err
}
namedPath := path.Join(bindMountPath, name)
f, err := os.OpenFile(namedPath, os.O_CREATE|os.O_EXCL, 0444)
if err != nil {
return None(), err
}
f.Close()
nsPath := fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid())
err = syscall.Mount(nsPath, namedPath, "bind", syscall.MS_BIND, "")
if err != nil {
return None(), err
}
return newNs, nil
}
// DeleteNamed deletes a named network namespace
func DeleteNamed(name string) error {
namedPath := path.Join(bindMountPath, name)
err := syscall.Unmount(namedPath, syscall.MNT_DETACH)
if err != nil {
return err
}
return os.Remove(namedPath)
}
// Get gets a handle to the current threads network namespace.
func Get() (NsHandle, error) {
return GetFromThread(os.Getpid(), syscall.Gettid())
return GetFromThread(os.Getpid(), unix.Gettid())
}
// GetFromPath gets a handle to a network namespace
// identified by the path
func GetFromPath(path string) (NsHandle, error) {
fd, err := syscall.Open(path, syscall.O_RDONLY, 0)
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
return -1, err
}