replace syscall with golang.org/x/sys/unix

This commit is contained in:
Ian Bishop
2017-10-21 07:38:07 +11:00
committed by Vish (Ishaya) Abrams
parent b7fbf1f529
commit 0e3b74dbe2
37 changed files with 605 additions and 585 deletions

View File

@@ -3,7 +3,8 @@ DIRS := \
nl nl
DEPS = \ DEPS = \
github.com/vishvananda/netns github.com/vishvananda/netns \
golang.org/x/sys/unix
uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1))) uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1)))
testdirs = $(call uniq,$(foreach d,$(1),$(dir $(wildcard $(d)/*_test.go)))) testdirs = $(call uniq,$(foreach d,$(1),$(dir $(wildcard $(d)/*_test.go))))

View File

@@ -89,3 +89,4 @@ There are also a few pieces of low level netlink functionality that still
need to be implemented. Routing rules are not in place and some of the need to be implemented. Routing rules are not in place and some of the
more advanced link types. Hopefully there is decent structure and testing more advanced link types. Hopefully there is decent structure and testing
in place to make these fairly straightforward to add. in place to make these fairly straightforward to add.

View File

@@ -4,10 +4,10 @@ import (
"fmt" "fmt"
"net" "net"
"strings" "strings"
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
// IFA_FLAGS is a u32 attribute. // IFA_FLAGS is a u32 attribute.
@@ -22,7 +22,7 @@ func AddrAdd(link Link, addr *Addr) error {
// AddrAdd will add an IP address to a link device. // AddrAdd will add an IP address to a link device.
// Equivalent to: `ip addr add $addr dev $link` // Equivalent to: `ip addr add $addr dev $link`
func (h *Handle) AddrAdd(link Link, addr *Addr) error { func (h *Handle) AddrAdd(link Link, addr *Addr) error {
req := h.newNetlinkRequest(syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
return h.addrHandle(link, addr, req) return h.addrHandle(link, addr, req)
} }
@@ -35,7 +35,7 @@ func AddrReplace(link Link, addr *Addr) error {
// AddrReplace will replace (or, if not present, add) an IP address on a link device. // AddrReplace will replace (or, if not present, add) an IP address on a link device.
// Equivalent to: `ip addr replace $addr dev $link` // Equivalent to: `ip addr replace $addr dev $link`
func (h *Handle) AddrReplace(link Link, addr *Addr) error { func (h *Handle) AddrReplace(link Link, addr *Addr) error {
req := h.newNetlinkRequest(syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_REPLACE|unix.NLM_F_ACK)
return h.addrHandle(link, addr, req) return h.addrHandle(link, addr, req)
} }
@@ -48,7 +48,7 @@ func AddrDel(link Link, addr *Addr) error {
// AddrDel will delete an IP address from a link device. // AddrDel will delete an IP address from a link device.
// Equivalent to: `ip addr del $addr dev $link` // Equivalent to: `ip addr del $addr dev $link`
func (h *Handle) AddrDel(link Link, addr *Addr) error { func (h *Handle) AddrDel(link Link, addr *Addr) error {
req := h.newNetlinkRequest(syscall.RTM_DELADDR, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELADDR, unix.NLM_F_ACK)
return h.addrHandle(link, addr, req) return h.addrHandle(link, addr, req)
} }
@@ -75,7 +75,7 @@ func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error
localAddrData = addr.IP.To16() localAddrData = addr.IP.To16()
} }
localData := nl.NewRtAttr(syscall.IFA_LOCAL, localAddrData) localData := nl.NewRtAttr(unix.IFA_LOCAL, localAddrData)
req.AddData(localData) req.AddData(localData)
var peerAddrData []byte var peerAddrData []byte
if addr.Peer != nil { if addr.Peer != nil {
@@ -88,7 +88,7 @@ func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error
peerAddrData = localAddrData peerAddrData = localAddrData
} }
addressData := nl.NewRtAttr(syscall.IFA_ADDRESS, peerAddrData) addressData := nl.NewRtAttr(unix.IFA_ADDRESS, peerAddrData)
req.AddData(addressData) req.AddData(addressData)
if addr.Flags != 0 { if addr.Flags != 0 {
@@ -109,14 +109,14 @@ func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error
} }
addr.Broadcast = calcBroadcast addr.Broadcast = calcBroadcast
} }
req.AddData(nl.NewRtAttr(syscall.IFA_BROADCAST, addr.Broadcast)) req.AddData(nl.NewRtAttr(unix.IFA_BROADCAST, addr.Broadcast))
if addr.Label != "" { if addr.Label != "" {
labelData := nl.NewRtAttr(syscall.IFA_LABEL, nl.ZeroTerminated(addr.Label)) labelData := nl.NewRtAttr(unix.IFA_LABEL, nl.ZeroTerminated(addr.Label))
req.AddData(labelData) req.AddData(labelData)
} }
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -131,11 +131,11 @@ func AddrList(link Link, family int) ([]Addr, error) {
// Equivalent to: `ip addr show`. // Equivalent to: `ip addr show`.
// The list can be filtered by link and ip family. // The list can be filtered by link and ip family.
func (h *Handle) AddrList(link Link, family int) ([]Addr, error) { func (h *Handle) AddrList(link Link, family int) ([]Addr, error) {
req := h.newNetlinkRequest(syscall.RTM_GETADDR, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETADDR, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(family) msg := nl.NewIfInfomsg(family)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWADDR) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWADDR)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -187,21 +187,21 @@ func parseAddr(m []byte) (addr Addr, family, index int, err error) {
var local, dst *net.IPNet var local, dst *net.IPNet
for _, attr := range attrs { for _, attr := range attrs {
switch attr.Attr.Type { switch attr.Attr.Type {
case syscall.IFA_ADDRESS: case unix.IFA_ADDRESS:
dst = &net.IPNet{ dst = &net.IPNet{
IP: attr.Value, IP: attr.Value,
Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)), Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
} }
addr.Peer = dst addr.Peer = dst
case syscall.IFA_LOCAL: case unix.IFA_LOCAL:
local = &net.IPNet{ local = &net.IPNet{
IP: attr.Value, IP: attr.Value,
Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)), Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
} }
addr.IPNet = local addr.IPNet = local
case syscall.IFA_BROADCAST: case unix.IFA_BROADCAST:
addr.Broadcast = attr.Value addr.Broadcast = attr.Value
case syscall.IFA_LABEL: case unix.IFA_LABEL:
addr.Label = string(attr.Value[:len(attr.Value)-1]) addr.Label = string(attr.Value[:len(attr.Value)-1])
case IFA_FLAGS: case IFA_FLAGS:
addr.Flags = int(native.Uint32(attr.Value[0:4])) addr.Flags = int(native.Uint32(attr.Value[0:4]))
@@ -264,7 +264,7 @@ func AddrSubscribeWithOptions(ch chan<- AddrUpdate, done <-chan struct{}, option
} }
func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}, cberr func(error)) error { func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}, cberr func(error)) error {
s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_IFADDR, syscall.RTNLGRP_IPV6_IFADDR) s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_IPV4_IFADDR, unix.RTNLGRP_IPV6_IFADDR)
if err != nil { if err != nil {
return err return err
} }
@@ -286,7 +286,7 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
} }
for _, m := range msgs { for _, m := range msgs {
msgType := m.Header.Type msgType := m.Header.Type
if msgType != syscall.RTM_NEWADDR && msgType != syscall.RTM_DELADDR { if msgType != unix.RTM_NEWADDR && msgType != unix.RTM_DELADDR {
if cberr != nil { if cberr != nil {
cberr(fmt.Errorf("bad message type: %d", msgType)) cberr(fmt.Errorf("bad message type: %d", msgType))
} }
@@ -303,7 +303,7 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
ch <- AddrUpdate{LinkAddress: *addr.IPNet, ch <- AddrUpdate{LinkAddress: *addr.IPNet,
LinkIndex: ifindex, LinkIndex: ifindex,
NewAddr: msgType == syscall.RTM_NEWADDR, NewAddr: msgType == unix.RTM_NEWADDR,
Flags: addr.Flags, Flags: addr.Flags,
Scope: addr.Scope, Scope: addr.Scope,
PreferedLft: addr.PreferedLft, PreferedLft: addr.PreferedLft,

View File

@@ -5,9 +5,10 @@ package netlink
import ( import (
"net" "net"
"os" "os"
"syscall"
"testing" "testing"
"time" "time"
"golang.org/x/sys/unix"
) )
func TestAddrAdd(t *testing.T) { func TestAddrAdd(t *testing.T) {
@@ -31,27 +32,27 @@ func DoTestAddr(t *testing.T, FunctionUndertest func(Link, *Addr) error) {
}{ }{
{ {
&Addr{IPNet: address}, &Addr{IPNet: address},
&Addr{IPNet: address, Label: "lo", Scope: syscall.RT_SCOPE_UNIVERSE, Flags: syscall.IFA_F_PERMANENT}, &Addr{IPNet: address, Label: "lo", Scope: unix.RT_SCOPE_UNIVERSE, Flags: unix.IFA_F_PERMANENT},
}, },
{ {
&Addr{IPNet: address, Label: "local"}, &Addr{IPNet: address, Label: "local"},
&Addr{IPNet: address, Label: "local", Scope: syscall.RT_SCOPE_UNIVERSE, Flags: syscall.IFA_F_PERMANENT}, &Addr{IPNet: address, Label: "local", Scope: unix.RT_SCOPE_UNIVERSE, Flags: unix.IFA_F_PERMANENT},
}, },
{ {
&Addr{IPNet: address, Flags: syscall.IFA_F_OPTIMISTIC}, &Addr{IPNet: address, Flags: unix.IFA_F_OPTIMISTIC},
&Addr{IPNet: address, Label: "lo", Flags: syscall.IFA_F_OPTIMISTIC | syscall.IFA_F_PERMANENT, Scope: syscall.RT_SCOPE_UNIVERSE}, &Addr{IPNet: address, Label: "lo", Flags: unix.IFA_F_OPTIMISTIC | unix.IFA_F_PERMANENT, Scope: unix.RT_SCOPE_UNIVERSE},
}, },
{ {
&Addr{IPNet: address, Flags: syscall.IFA_F_OPTIMISTIC | syscall.IFA_F_DADFAILED}, &Addr{IPNet: address, Flags: unix.IFA_F_OPTIMISTIC | unix.IFA_F_DADFAILED},
&Addr{IPNet: address, Label: "lo", Flags: syscall.IFA_F_OPTIMISTIC | syscall.IFA_F_DADFAILED | syscall.IFA_F_PERMANENT, Scope: syscall.RT_SCOPE_UNIVERSE}, &Addr{IPNet: address, Label: "lo", Flags: unix.IFA_F_OPTIMISTIC | unix.IFA_F_DADFAILED | unix.IFA_F_PERMANENT, Scope: unix.RT_SCOPE_UNIVERSE},
}, },
{ {
&Addr{IPNet: address, Scope: syscall.RT_SCOPE_NOWHERE}, &Addr{IPNet: address, Scope: unix.RT_SCOPE_NOWHERE},
&Addr{IPNet: address, Label: "lo", Flags: syscall.IFA_F_PERMANENT, Scope: syscall.RT_SCOPE_NOWHERE}, &Addr{IPNet: address, Label: "lo", Flags: unix.IFA_F_PERMANENT, Scope: unix.RT_SCOPE_NOWHERE},
}, },
{ {
&Addr{IPNet: address, Peer: peer}, &Addr{IPNet: address, Peer: peer},
&Addr{IPNet: address, Peer: peer, Label: "lo", Scope: syscall.RT_SCOPE_UNIVERSE, Flags: syscall.IFA_F_PERMANENT}, &Addr{IPNet: address, Peer: peer, Label: "lo", Scope: unix.RT_SCOPE_UNIVERSE, Flags: unix.IFA_F_PERMANENT},
}, },
} }

View File

@@ -2,9 +2,9 @@ package netlink
import ( import (
"fmt" "fmt"
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// BridgeVlanList gets a map of device id to bridge vlan infos. // BridgeVlanList gets a map of device id to bridge vlan infos.
@@ -16,12 +16,12 @@ func BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) {
// BridgeVlanList gets a map of device id to bridge vlan infos. // BridgeVlanList gets a map of device id to bridge vlan infos.
// Equivalent to: `bridge vlan show` // Equivalent to: `bridge vlan show`
func (h *Handle) BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) { func (h *Handle) BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) {
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE) msg := nl.NewIfInfomsg(unix.AF_BRIDGE)
req.AddData(msg) req.AddData(msg)
req.AddData(nl.NewRtAttr(nl.IFLA_EXT_MASK, nl.Uint32Attr(uint32(nl.RTEXT_FILTER_BRVLAN)))) req.AddData(nl.NewRtAttr(nl.IFLA_EXT_MASK, nl.Uint32Attr(uint32(nl.RTEXT_FILTER_BRVLAN))))
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWLINK) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -63,7 +63,7 @@ func BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) err
// BridgeVlanAdd adds a new vlan filter entry // BridgeVlanAdd adds a new vlan filter entry
// Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` // Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]`
func (h *Handle) BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error { func (h *Handle) BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error {
return h.bridgeVlanModify(syscall.RTM_SETLINK, link, vid, pvid, untagged, self, master) return h.bridgeVlanModify(unix.RTM_SETLINK, link, vid, pvid, untagged, self, master)
} }
// BridgeVlanDel adds a new vlan filter entry // BridgeVlanDel adds a new vlan filter entry
@@ -75,15 +75,15 @@ func BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) err
// BridgeVlanDel adds a new vlan filter entry // BridgeVlanDel adds a new vlan filter entry
// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` // Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]`
func (h *Handle) BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error { func (h *Handle) BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error {
return h.bridgeVlanModify(syscall.RTM_DELLINK, link, vid, pvid, untagged, self, master) return h.bridgeVlanModify(unix.RTM_DELLINK, link, vid, pvid, untagged, self, master)
} }
func (h *Handle) bridgeVlanModify(cmd int, link Link, vid uint16, pvid, untagged, self, master bool) error { func (h *Handle) bridgeVlanModify(cmd int, link Link, vid uint16, pvid, untagged, self, master bool) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(cmd, syscall.NLM_F_ACK) req := h.newNetlinkRequest(cmd, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE) msg := nl.NewIfInfomsg(unix.AF_BRIDGE)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -107,7 +107,7 @@ func (h *Handle) bridgeVlanModify(cmd int, link Link, vid uint16, pvid, untagged
} }
nl.NewRtAttrChild(br, nl.IFLA_BRIDGE_VLAN_INFO, vlanInfo.Serialize()) nl.NewRtAttrChild(br, nl.IFLA_BRIDGE_VLAN_INFO, vlanInfo.Serialize())
req.AddData(br) req.AddData(br)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -5,6 +5,7 @@ import (
"syscall" "syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// NOTE: function is in here because it uses other linux functions // NOTE: function is in here because it uses other linux functions
@@ -50,7 +51,7 @@ func ClassDel(class Class) error {
// ClassDel will delete a class from the system. // ClassDel will delete a class from the system.
// Equivalent to: `tc class del $class` // Equivalent to: `tc class del $class`
func (h *Handle) ClassDel(class Class) error { func (h *Handle) ClassDel(class Class) error {
return h.classModify(syscall.RTM_DELTCLASS, 0, class) return h.classModify(unix.RTM_DELTCLASS, 0, class)
} }
// ClassChange will change a class in place // ClassChange will change a class in place
@@ -64,7 +65,7 @@ func ClassChange(class Class) error {
// Equivalent to: `tc class change $class` // Equivalent to: `tc class change $class`
// The parent and handle MUST NOT be changed. // The parent and handle MUST NOT be changed.
func (h *Handle) ClassChange(class Class) error { func (h *Handle) ClassChange(class Class) error {
return h.classModify(syscall.RTM_NEWTCLASS, 0, class) return h.classModify(unix.RTM_NEWTCLASS, 0, class)
} }
// ClassReplace will replace a class to the system. // ClassReplace will replace a class to the system.
@@ -82,7 +83,7 @@ func ClassReplace(class Class) error {
// If a class already exist with this parent/handle pair, the class is changed. // If a class already exist with this parent/handle pair, the class is changed.
// If a class does not already exist with this parent/handle, a new class is created. // If a class does not already exist with this parent/handle, a new class is created.
func (h *Handle) ClassReplace(class Class) error { func (h *Handle) ClassReplace(class Class) error {
return h.classModify(syscall.RTM_NEWTCLASS, syscall.NLM_F_CREATE, class) return h.classModify(unix.RTM_NEWTCLASS, unix.NLM_F_CREATE, class)
} }
// ClassAdd will add a class to the system. // ClassAdd will add a class to the system.
@@ -95,14 +96,14 @@ func ClassAdd(class Class) error {
// Equivalent to: `tc class add $class` // Equivalent to: `tc class add $class`
func (h *Handle) ClassAdd(class Class) error { func (h *Handle) ClassAdd(class Class) error {
return h.classModify( return h.classModify(
syscall.RTM_NEWTCLASS, unix.RTM_NEWTCLASS,
syscall.NLM_F_CREATE|syscall.NLM_F_EXCL, unix.NLM_F_CREATE|unix.NLM_F_EXCL,
class, class,
) )
} }
func (h *Handle) classModify(cmd, flags int, class Class) error { func (h *Handle) classModify(cmd, flags int, class Class) error {
req := h.newNetlinkRequest(cmd, flags|syscall.NLM_F_ACK) req := h.newNetlinkRequest(cmd, flags|unix.NLM_F_ACK)
base := class.Attrs() base := class.Attrs()
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
@@ -112,12 +113,12 @@ func (h *Handle) classModify(cmd, flags int, class Class) error {
} }
req.AddData(msg) req.AddData(msg)
if cmd != syscall.RTM_DELTCLASS { if cmd != unix.RTM_DELTCLASS {
if err := classPayload(req, class); err != nil { if err := classPayload(req, class); err != nil {
return err return err
} }
} }
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -169,7 +170,7 @@ func ClassList(link Link, parent uint32) ([]Class, error) {
// Equivalent to: `tc class show`. // Equivalent to: `tc class show`.
// Generally returns nothing if link and parent are not specified. // Generally returns nothing if link and parent are not specified.
func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) { func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) {
req := h.newNetlinkRequest(syscall.RTM_GETTCLASS, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETTCLASS, unix.NLM_F_DUMP)
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
Parent: parent, Parent: parent,
@@ -181,7 +182,7 @@ func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) {
} }
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTCLASS) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWTCLASS)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -6,9 +6,9 @@ import (
"errors" "errors"
"fmt" "fmt"
"net" "net"
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// ConntrackTableType Conntrack table for the netlink operation // ConntrackTableType Conntrack table for the netlink operation
@@ -85,8 +85,8 @@ func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily)
// conntrack -F [table] Flush table // conntrack -F [table] Flush table
// The flush operation applies to all the family types // The flush operation applies to all the family types
func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error { func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error {
req := h.newConntrackRequest(table, syscall.AF_INET, nl.IPCTNL_MSG_CT_DELETE, syscall.NLM_F_ACK) req := h.newConntrackRequest(table, unix.AF_INET, nl.IPCTNL_MSG_CT_DELETE, unix.NLM_F_ACK)
_, err := req.Execute(syscall.NETLINK_NETFILTER, 0) _, err := req.Execute(unix.NETLINK_NETFILTER, 0)
return err return err
} }
@@ -102,10 +102,10 @@ func (h *Handle) ConntrackDeleteFilter(table ConntrackTableType, family InetFami
for _, dataRaw := range res { for _, dataRaw := range res {
flow := parseRawData(dataRaw) flow := parseRawData(dataRaw)
if match := filter.MatchConntrackFlow(flow); match { if match := filter.MatchConntrackFlow(flow); match {
req2 := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_DELETE, syscall.NLM_F_ACK) req2 := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_DELETE, unix.NLM_F_ACK)
// skip the first 4 byte that are the netfilter header, the newConntrackRequest is adding it already // skip the first 4 byte that are the netfilter header, the newConntrackRequest is adding it already
req2.AddRawData(dataRaw[4:]) req2.AddRawData(dataRaw[4:])
req2.Execute(syscall.NETLINK_NETFILTER, 0) req2.Execute(unix.NETLINK_NETFILTER, 0)
matched++ matched++
} }
} }
@@ -127,8 +127,8 @@ func (h *Handle) newConntrackRequest(table ConntrackTableType, family InetFamily
} }
func (h *Handle) dumpConntrackTable(table ConntrackTableType, family InetFamily) ([][]byte, error) { func (h *Handle) dumpConntrackTable(table ConntrackTableType, family InetFamily) ([][]byte, error) {
req := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_GET, syscall.NLM_F_DUMP) req := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_GET, unix.NLM_F_DUMP)
return req.Execute(syscall.NETLINK_NETFILTER, 0) return req.Execute(unix.NETLINK_NETFILTER, 0)
} }
// The full conntrack flow structure is very complicated and can be found in the file: // The full conntrack flow structure is very complicated and can be found in the file:

View File

@@ -4,10 +4,10 @@ import (
"fmt" "fmt"
"net" "net"
"runtime" "runtime"
"syscall"
"testing" "testing"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
func CheckErrorFail(t *testing.T, err error) { func CheckErrorFail(t *testing.T, err error) {
@@ -76,10 +76,10 @@ func applyFilter(flowList []ConntrackFlow, ipv4Filter *ConntrackFilter, ipv6Filt
func TestConntrackSocket(t *testing.T) { func TestConntrackSocket(t *testing.T) {
skipUnlessRoot(t) skipUnlessRoot(t)
h, err := NewHandle(syscall.NETLINK_NETFILTER) h, err := NewHandle(unix.NETLINK_NETFILTER)
CheckErrorFail(t, err) CheckErrorFail(t, err)
if h.SupportsNetlinkFamily(syscall.NETLINK_NETFILTER) != true { if h.SupportsNetlinkFamily(unix.NETLINK_NETFILTER) != true {
t.Fatal("ERROR not supporting the NETFILTER family") t.Fatal("ERROR not supporting the NETFILTER family")
} }
} }
@@ -104,7 +104,7 @@ func TestConntrackTableList(t *testing.T) {
udpFlowCreateProg(t, 5, 2000, "127.0.0.10", 3000) udpFlowCreateProg(t, 5, 2000, "127.0.0.10", 3000)
// Fetch the conntrack table // Fetch the conntrack table
flows, err := h.ConntrackTableList(ConntrackTable, syscall.AF_INET) flows, err := h.ConntrackTableList(ConntrackTable, unix.AF_INET)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Check that it is able to find the 5 flows created // Check that it is able to find the 5 flows created
@@ -122,7 +122,7 @@ func TestConntrackTableList(t *testing.T) {
} }
// Give a try also to the IPv6 version // Give a try also to the IPv6 version
_, err = h.ConntrackTableList(ConntrackTable, syscall.AF_INET6) _, err = h.ConntrackTableList(ConntrackTable, unix.AF_INET6)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Switch back to the original namespace // Switch back to the original namespace
@@ -145,7 +145,7 @@ func TestConntrackTableFlush(t *testing.T) {
udpFlowCreateProg(t, 5, 3000, "127.0.0.10", 4000) udpFlowCreateProg(t, 5, 3000, "127.0.0.10", 4000)
// Fetch the conntrack table // Fetch the conntrack table
flows, err := h.ConntrackTableList(ConntrackTable, syscall.AF_INET) flows, err := h.ConntrackTableList(ConntrackTable, unix.AF_INET)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Check that it is able to find the 5 flows created // Check that it is able to find the 5 flows created
@@ -167,7 +167,7 @@ func TestConntrackTableFlush(t *testing.T) {
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Fetch again the flows to validate the flush // Fetch again the flows to validate the flush
flows, err = h.ConntrackTableList(ConntrackTable, syscall.AF_INET) flows, err = h.ConntrackTableList(ConntrackTable, unix.AF_INET)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Check if it is still able to find the 5 flows created // Check if it is still able to find the 5 flows created
@@ -205,7 +205,7 @@ func TestConntrackTableDelete(t *testing.T) {
udpFlowCreateProg(t, 5, 7000, "127.0.0.20", 8000) udpFlowCreateProg(t, 5, 7000, "127.0.0.20", 8000)
// Fetch the conntrack table // Fetch the conntrack table
flows, err := h.ConntrackTableList(ConntrackTable, syscall.AF_INET) flows, err := h.ConntrackTableList(ConntrackTable, unix.AF_INET)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Check that it is able to find the 5 flows created for each group // Check that it is able to find the 5 flows created for each group
@@ -235,7 +235,7 @@ func TestConntrackTableDelete(t *testing.T) {
// Flush entries of groupB // Flush entries of groupB
var deleted uint var deleted uint
if deleted, err = h.ConntrackDeleteFilter(ConntrackTable, syscall.AF_INET, filter); err != nil { if deleted, err = h.ConntrackDeleteFilter(ConntrackTable, unix.AF_INET, filter); err != nil {
t.Fatalf("Error during the erase: %s", err) t.Fatalf("Error during the erase: %s", err)
} }
if deleted != 5 { if deleted != 5 {
@@ -243,7 +243,7 @@ func TestConntrackTableDelete(t *testing.T) {
} }
// Check again the table to verify that are gone // Check again the table to verify that are gone
flows, err = h.ConntrackTableList(ConntrackTable, syscall.AF_INET) flows, err = h.ConntrackTableList(ConntrackTable, unix.AF_INET)
CheckErrorFail(t, err) CheckErrorFail(t, err)
// Check if it is able to find the 5 flows of groupA but none of groupB // Check if it is able to find the 5 flows of groupA but none of groupB
@@ -274,7 +274,7 @@ func TestConntrackTableDelete(t *testing.T) {
func TestConntrackFilter(t *testing.T) { func TestConntrackFilter(t *testing.T) {
var flowList []ConntrackFlow var flowList []ConntrackFlow
flowList = append(flowList, ConntrackFlow{ flowList = append(flowList, ConntrackFlow{
FamilyType: syscall.AF_INET, FamilyType: unix.AF_INET,
Forward: ipTuple{ Forward: ipTuple{
SrcIP: net.ParseIP("10.0.0.1"), SrcIP: net.ParseIP("10.0.0.1"),
DstIP: net.ParseIP("20.0.0.1"), DstIP: net.ParseIP("20.0.0.1"),
@@ -289,7 +289,7 @@ func TestConntrackFilter(t *testing.T) {
}, },
}, },
ConntrackFlow{ ConntrackFlow{
FamilyType: syscall.AF_INET, FamilyType: unix.AF_INET,
Forward: ipTuple{ Forward: ipTuple{
SrcIP: net.ParseIP("10.0.0.2"), SrcIP: net.ParseIP("10.0.0.2"),
DstIP: net.ParseIP("20.0.0.2"), DstIP: net.ParseIP("20.0.0.2"),
@@ -304,7 +304,7 @@ func TestConntrackFilter(t *testing.T) {
}, },
}, },
ConntrackFlow{ ConntrackFlow{
FamilyType: syscall.AF_INET6, FamilyType: unix.AF_INET6,
Forward: ipTuple{ Forward: ipTuple{
SrcIP: net.ParseIP("eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee"), SrcIP: net.ParseIP("eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee"),
DstIP: net.ParseIP("dddd:dddd:dddd:dddd:dddd:dddd:dddd:dddd"), DstIP: net.ParseIP("dddd:dddd:dddd:dddd:dddd:dddd:dddd:dddd"),

View File

@@ -17,7 +17,7 @@ type FilterAttrs struct {
Handle uint32 Handle uint32
Parent uint32 Parent uint32
Priority uint16 // lower is higher priority Priority uint16 // lower is higher priority
Protocol uint16 // syscall.ETH_P_* Protocol uint16 // unix.ETH_P_*
} }
func (q FilterAttrs) String() string { func (q FilterAttrs) String() string {

View File

@@ -9,6 +9,7 @@ import (
"unsafe" "unsafe"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// Constants used in TcU32Sel.Flags. // Constants used in TcU32Sel.Flags.
@@ -98,7 +99,7 @@ func FilterDel(filter Filter) error {
// FilterDel will delete a filter from the system. // FilterDel will delete a filter from the system.
// Equivalent to: `tc filter del $filter` // Equivalent to: `tc filter del $filter`
func (h *Handle) FilterDel(filter Filter) error { func (h *Handle) FilterDel(filter Filter) error {
req := h.newNetlinkRequest(syscall.RTM_DELTFILTER, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELTFILTER, unix.NLM_F_ACK)
base := filter.Attrs() base := filter.Attrs()
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
@@ -109,7 +110,7 @@ func (h *Handle) FilterDel(filter Filter) error {
} }
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -123,7 +124,7 @@ func FilterAdd(filter Filter) error {
// Equivalent to: `tc filter add $filter` // Equivalent to: `tc filter add $filter`
func (h *Handle) FilterAdd(filter Filter) error { func (h *Handle) FilterAdd(filter Filter) error {
native = nl.NativeEndian() native = nl.NativeEndian()
req := h.newNetlinkRequest(syscall.RTM_NEWTFILTER, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWTFILTER, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
base := filter.Attrs() base := filter.Attrs()
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
@@ -224,7 +225,7 @@ func (h *Handle) FilterAdd(filter Filter) error {
} }
req.AddData(options) req.AddData(options)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -239,7 +240,7 @@ func FilterList(link Link, parent uint32) ([]Filter, error) {
// Equivalent to: `tc filter show`. // Equivalent to: `tc filter show`.
// Generally returns nothing if link and parent are not specified. // Generally returns nothing if link and parent are not specified.
func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) { func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) {
req := h.newNetlinkRequest(syscall.RTM_GETTFILTER, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETTFILTER, unix.NLM_F_DUMP)
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
Parent: parent, Parent: parent,
@@ -251,7 +252,7 @@ func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) {
} }
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTFILTER) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWTFILTER)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -4,8 +4,9 @@ package netlink
import ( import (
"reflect" "reflect"
"syscall"
"testing" "testing"
"golang.org/x/sys/unix"
) )
func TestFilterAddDel(t *testing.T) { func TestFilterAddDel(t *testing.T) {
@@ -58,7 +59,7 @@ func TestFilterAddDel(t *testing.T) {
LinkIndex: link.Attrs().Index, LinkIndex: link.Attrs().Index,
Parent: MakeHandle(0xffff, 0), Parent: MakeHandle(0xffff, 0),
Priority: 1, Priority: 1,
Protocol: syscall.ETH_P_IP, Protocol: unix.ETH_P_IP,
}, },
RedirIndex: redir.Attrs().Index, RedirIndex: redir.Attrs().Index,
ClassId: classId, ClassId: classId,
@@ -185,7 +186,7 @@ func TestAdvancedFilterAddDel(t *testing.T) {
LinkIndex: index, LinkIndex: index,
Parent: qdiscHandle, Parent: qdiscHandle,
Priority: 1, Priority: 1,
Protocol: syscall.ETH_P_ALL, Protocol: unix.ETH_P_ALL,
}, },
Sel: &TcU32Sel{ Sel: &TcU32Sel{
Keys: u32SelKeys, Keys: u32SelKeys,
@@ -337,7 +338,7 @@ func TestFilterFwAddDel(t *testing.T) {
Parent: MakeHandle(0xffff, 0), Parent: MakeHandle(0xffff, 0),
Handle: MakeHandle(0, 0x6), Handle: MakeHandle(0, 0x6),
Priority: 1, Priority: 1,
Protocol: syscall.ETH_P_IP, Protocol: unix.ETH_P_IP,
} }
fwattrs := FilterFwAttrs{ fwattrs := FilterFwAttrs{
Buffer: 12345, Buffer: 12345,
@@ -476,7 +477,7 @@ func TestFilterU32BpfAddDel(t *testing.T) {
LinkIndex: link.Attrs().Index, LinkIndex: link.Attrs().Index,
Parent: MakeHandle(0xffff, 0), Parent: MakeHandle(0xffff, 0),
Priority: 1, Priority: 1,
Protocol: syscall.ETH_P_ALL, Protocol: unix.ETH_P_ALL,
}, },
ClassId: classId, ClassId: classId,
Actions: []Action{ Actions: []Action{
@@ -594,7 +595,7 @@ func TestFilterClsActBpfAddDel(t *testing.T) {
LinkIndex: link.Attrs().Index, LinkIndex: link.Attrs().Index,
Parent: HANDLE_MIN_EGRESS, Parent: HANDLE_MIN_EGRESS,
Handle: MakeHandle(0, 1), Handle: MakeHandle(0, 1),
Protocol: syscall.ETH_P_ALL, Protocol: unix.ETH_P_ALL,
Priority: 1, Priority: 1,
} }
fd, err := loadSimpleBpf(BPF_PROG_TYPE_SCHED_CLS, 1) fd, err := loadSimpleBpf(BPF_PROG_TYPE_SCHED_CLS, 1)

View File

@@ -5,6 +5,7 @@ import (
"syscall" "syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
type GenlOp struct { type GenlOp struct {
@@ -130,9 +131,9 @@ func (h *Handle) GenlFamilyList() ([]*GenlFamily, error) {
Command: nl.GENL_CTRL_CMD_GETFAMILY, Command: nl.GENL_CTRL_CMD_GETFAMILY,
Version: nl.GENL_CTRL_VERSION, Version: nl.GENL_CTRL_VERSION,
} }
req := h.newNetlinkRequest(nl.GENL_ID_CTRL, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(nl.GENL_ID_CTRL, unix.NLM_F_DUMP)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0) msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -151,7 +152,7 @@ func (h *Handle) GenlFamilyGet(name string) (*GenlFamily, error) {
req := h.newNetlinkRequest(nl.GENL_ID_CTRL, 0) req := h.newNetlinkRequest(nl.GENL_ID_CTRL, 0)
req.AddData(msg) req.AddData(msg)
req.AddData(nl.NewRtAttr(nl.GENL_CTRL_ATTR_FAMILY_NAME, nl.ZeroTerminated(name))) req.AddData(nl.NewRtAttr(nl.GENL_CTRL_ATTR_FAMILY_NAME, nl.ZeroTerminated(name)))
msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0) msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -7,6 +7,7 @@ import (
"syscall" "syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
type PDP struct { type PDP struct {
@@ -82,9 +83,9 @@ func (h *Handle) GTPPDPList() ([]*PDP, error) {
Command: nl.GENL_GTP_CMD_GETPDP, Command: nl.GENL_GTP_CMD_GETPDP,
Version: nl.GENL_GTP_VERSION, Version: nl.GENL_GTP_VERSION,
} }
req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_DUMP) req := h.newNetlinkRequest(int(f.ID), unix.NLM_F_DUMP)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0) msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -96,7 +97,7 @@ func GTPPDPList() ([]*PDP, error) {
} }
func gtpPDPGet(req *nl.NetlinkRequest) (*PDP, error) { func gtpPDPGet(req *nl.NetlinkRequest) (*PDP, error) {
msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0) msgs, err := req.Execute(unix.NETLINK_GENERIC, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -182,7 +183,7 @@ func (h *Handle) GTPPDPAdd(link Link, pdp *PDP) error {
Command: nl.GENL_GTP_CMD_NEWPDP, Command: nl.GENL_GTP_CMD_NEWPDP,
Version: nl.GENL_GTP_VERSION, Version: nl.GENL_GTP_VERSION,
} }
req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(int(f.ID), unix.NLM_F_EXCL|unix.NLM_F_ACK)
req.AddData(msg) req.AddData(msg)
req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version))) req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version)))
req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index)))) req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
@@ -199,7 +200,7 @@ func (h *Handle) GTPPDPAdd(link Link, pdp *PDP) error {
default: default:
return fmt.Errorf("unsupported GTP version: %d", pdp.Version) return fmt.Errorf("unsupported GTP version: %d", pdp.Version)
} }
_, err = req.Execute(syscall.NETLINK_GENERIC, 0) _, err = req.Execute(unix.NETLINK_GENERIC, 0)
return err return err
} }
@@ -216,7 +217,7 @@ func (h *Handle) GTPPDPDel(link Link, pdp *PDP) error {
Command: nl.GENL_GTP_CMD_DELPDP, Command: nl.GENL_GTP_CMD_DELPDP,
Version: nl.GENL_GTP_VERSION, Version: nl.GENL_GTP_VERSION,
} }
req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(int(f.ID), unix.NLM_F_EXCL|unix.NLM_F_ACK)
req.AddData(msg) req.AddData(msg)
req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version))) req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version)))
req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index)))) req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
@@ -229,7 +230,7 @@ func (h *Handle) GTPPDPDel(link Link, pdp *PDP) error {
default: default:
return fmt.Errorf("unsupported GTP version: %d", pdp.Version) return fmt.Errorf("unsupported GTP version: %d", pdp.Version)
} }
_, err = req.Execute(syscall.NETLINK_GENERIC, 0) _, err = req.Execute(unix.NETLINK_GENERIC, 0)
return err return err
} }

View File

@@ -2,11 +2,11 @@ package netlink
import ( import (
"fmt" "fmt"
"syscall"
"time" "time"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
// Empty handle used by the netlink package methods // Empty handle used by the netlink package methods
@@ -43,7 +43,7 @@ func (h *Handle) SetSocketTimeout(to time.Duration) error {
if to < time.Microsecond { if to < time.Microsecond {
return fmt.Errorf("invalid timeout, minimul value is %s", time.Microsecond) return fmt.Errorf("invalid timeout, minimul value is %s", time.Microsecond)
} }
tv := syscall.NsecToTimeval(to.Nanoseconds()) tv := unix.NsecToTimeval(to.Nanoseconds())
for _, sh := range h.sockets { for _, sh := range h.sockets {
if err := sh.Socket.SetSendTimeout(&tv); err != nil { if err := sh.Socket.SetSendTimeout(&tv); err != nil {
return err return err
@@ -59,13 +59,13 @@ func (h *Handle) SetSocketTimeout(to time.Duration) error {
// socket in the netlink handle. The maximum value is capped by // socket in the netlink handle. The maximum value is capped by
// /proc/sys/net/core/rmem_max. // /proc/sys/net/core/rmem_max.
func (h *Handle) SetSocketReceiveBufferSize(size int, force bool) error { func (h *Handle) SetSocketReceiveBufferSize(size int, force bool) error {
opt := syscall.SO_RCVBUF opt := unix.SO_RCVBUF
if force { if force {
opt = syscall.SO_RCVBUFFORCE opt = unix.SO_RCVBUFFORCE
} }
for _, sh := range h.sockets { for _, sh := range h.sockets {
fd := sh.Socket.GetFd() fd := sh.Socket.GetFd()
err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, opt, size) err := unix.SetsockoptInt(fd, unix.SOL_SOCKET, opt, size)
if err != nil { if err != nil {
return err return err
} }
@@ -81,7 +81,7 @@ func (h *Handle) GetSocketReceiveBufferSize() ([]int, error) {
i := 0 i := 0
for _, sh := range h.sockets { for _, sh := range h.sockets {
fd := sh.Socket.GetFd() fd := sh.Socket.GetFd()
size, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF) size, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -134,10 +134,10 @@ func (h *Handle) newNetlinkRequest(proto, flags int) *nl.NetlinkRequest {
return nl.NewNetlinkRequest(proto, flags) return nl.NewNetlinkRequest(proto, flags)
} }
return &nl.NetlinkRequest{ return &nl.NetlinkRequest{
NlMsghdr: syscall.NlMsghdr{ NlMsghdr: unix.NlMsghdr{
Len: uint32(syscall.SizeofNlMsghdr), Len: uint32(unix.SizeofNlMsghdr),
Type: uint16(proto), Type: uint16(proto),
Flags: syscall.NLM_F_REQUEST | uint16(flags), Flags: unix.NLM_F_REQUEST | uint16(flags),
}, },
Sockets: h.sockets, Sockets: h.sockets,
} }

View File

@@ -10,13 +10,13 @@ import (
"net" "net"
"sync" "sync"
"sync/atomic" "sync/atomic"
"syscall"
"testing" "testing"
"time" "time"
"unsafe" "unsafe"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
func TestHandleCreateDelete(t *testing.T) { func TestHandleCreateDelete(t *testing.T) {
@@ -122,13 +122,13 @@ func TestHandleTimeout(t *testing.T) {
defer h.Delete() defer h.Delete()
for _, sh := range h.sockets { for _, sh := range h.sockets {
verifySockTimeVal(t, sh.Socket.GetFd(), syscall.Timeval{Sec: 0, Usec: 0}) verifySockTimeVal(t, sh.Socket.GetFd(), unix.Timeval{Sec: 0, Usec: 0})
} }
h.SetSocketTimeout(2*time.Second + 8*time.Millisecond) h.SetSocketTimeout(2*time.Second + 8*time.Millisecond)
for _, sh := range h.sockets { for _, sh := range h.sockets {
verifySockTimeVal(t, sh.Socket.GetFd(), syscall.Timeval{Sec: 2, Usec: 8000}) verifySockTimeVal(t, sh.Socket.GetFd(), unix.Timeval{Sec: 2, Usec: 8000})
} }
} }
@@ -157,12 +157,12 @@ func TestHandleReceiveBuffer(t *testing.T) {
} }
} }
func verifySockTimeVal(t *testing.T, fd int, tv syscall.Timeval) { func verifySockTimeVal(t *testing.T, fd int, tv unix.Timeval) {
var ( var (
tr syscall.Timeval tr unix.Timeval
v = uint32(0x10) v = uint32(0x10)
) )
_, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(fd), syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, uintptr(unsafe.Pointer(&tr)), uintptr(unsafe.Pointer(&v)), 0) _, _, errno := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(fd), unix.SOL_SOCKET, unix.SO_SNDTIMEO, uintptr(unsafe.Pointer(&tr)), uintptr(unsafe.Pointer(&v)), 0)
if errno != 0 { if errno != 0 {
t.Fatal(errno) t.Fatal(errno)
} }
@@ -171,7 +171,7 @@ func verifySockTimeVal(t *testing.T, fd int, tv syscall.Timeval) {
t.Fatalf("Unexpected timeout value read: %v. Expected: %v", tr, tv) t.Fatalf("Unexpected timeout value read: %v. Expected: %v", tr, tv)
} }
_, _, errno = syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(fd), syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, uintptr(unsafe.Pointer(&tr)), uintptr(unsafe.Pointer(&v)), 0) _, _, errno = unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(fd), unix.SOL_SOCKET, unix.SO_RCVTIMEO, uintptr(unsafe.Pointer(&tr)), uintptr(unsafe.Pointer(&v)), 0)
if errno != 0 { if errno != 0 {
t.Fatal(errno) t.Fatal(errno)
} }

View File

@@ -11,6 +11,7 @@ import (
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
const ( const (
@@ -20,13 +21,13 @@ const (
) )
const ( const (
TUNTAP_MODE_TUN TuntapMode = syscall.IFF_TUN TUNTAP_MODE_TUN TuntapMode = unix.IFF_TUN
TUNTAP_MODE_TAP TuntapMode = syscall.IFF_TAP TUNTAP_MODE_TAP TuntapMode = unix.IFF_TAP
TUNTAP_DEFAULTS TuntapFlag = syscall.IFF_TUN_EXCL | syscall.IFF_ONE_QUEUE TUNTAP_DEFAULTS TuntapFlag = unix.IFF_TUN_EXCL | unix.IFF_ONE_QUEUE
TUNTAP_VNET_HDR TuntapFlag = syscall.IFF_VNET_HDR TUNTAP_VNET_HDR TuntapFlag = unix.IFF_VNET_HDR
TUNTAP_TUN_EXCL TuntapFlag = syscall.IFF_TUN_EXCL TUNTAP_TUN_EXCL TuntapFlag = unix.IFF_TUN_EXCL
TUNTAP_NO_PI TuntapFlag = syscall.IFF_NO_PI TUNTAP_NO_PI TuntapFlag = unix.IFF_NO_PI
TUNTAP_ONE_QUEUE TuntapFlag = syscall.IFF_ONE_QUEUE TUNTAP_ONE_QUEUE TuntapFlag = unix.IFF_ONE_QUEUE
) )
var lookupByDump = false var lookupByDump = false
@@ -61,15 +62,15 @@ func (h *Handle) ensureIndex(link *LinkAttrs) {
func (h *Handle) LinkSetARPOff(link Link) error { func (h *Handle) LinkSetARPOff(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change |= syscall.IFF_NOARP msg.Change |= unix.IFF_NOARP
msg.Flags |= syscall.IFF_NOARP msg.Flags |= unix.IFF_NOARP
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -80,15 +81,15 @@ func LinkSetARPOff(link Link) error {
func (h *Handle) LinkSetARPOn(link Link) error { func (h *Handle) LinkSetARPOn(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change |= syscall.IFF_NOARP msg.Change |= unix.IFF_NOARP
msg.Flags &= ^uint32(syscall.IFF_NOARP) msg.Flags &= ^uint32(unix.IFF_NOARP)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -99,15 +100,15 @@ func LinkSetARPOn(link Link) error {
func (h *Handle) SetPromiscOn(link Link) error { func (h *Handle) SetPromiscOn(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = syscall.IFF_PROMISC msg.Change = unix.IFF_PROMISC
msg.Flags = syscall.IFF_PROMISC msg.Flags = unix.IFF_PROMISC
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -118,7 +119,7 @@ func BridgeSetMcastSnoop(link Link, on bool) error {
func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error { func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error {
bridge := link.(*Bridge) bridge := link.(*Bridge)
bridge.MulticastSnooping = &on bridge.MulticastSnooping = &on
return h.linkModify(bridge, syscall.NLM_F_ACK) return h.linkModify(bridge, unix.NLM_F_ACK)
} }
func SetPromiscOn(link Link) error { func SetPromiscOn(link Link) error {
@@ -128,15 +129,15 @@ func SetPromiscOn(link Link) error {
func (h *Handle) SetPromiscOff(link Link) error { func (h *Handle) SetPromiscOff(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = syscall.IFF_PROMISC msg.Change = unix.IFF_PROMISC
msg.Flags = 0 & ^syscall.IFF_PROMISC msg.Flags = 0 & ^unix.IFF_PROMISC
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -155,15 +156,15 @@ func LinkSetUp(link Link) error {
func (h *Handle) LinkSetUp(link Link) error { func (h *Handle) LinkSetUp(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = syscall.IFF_UP msg.Change = unix.IFF_UP
msg.Flags = syscall.IFF_UP msg.Flags = unix.IFF_UP
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -178,15 +179,15 @@ func LinkSetDown(link Link) error {
func (h *Handle) LinkSetDown(link Link) error { func (h *Handle) LinkSetDown(link Link) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Change = syscall.IFF_UP msg.Change = unix.IFF_UP
msg.Flags = 0 & ^syscall.IFF_UP msg.Flags = 0 & ^unix.IFF_UP
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -201,19 +202,19 @@ func LinkSetMTU(link Link, mtu int) error {
func (h *Handle) LinkSetMTU(link Link, mtu int) error { func (h *Handle) LinkSetMTU(link Link, mtu int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(mtu)) native.PutUint32(b, uint32(mtu))
data := nl.NewRtAttr(syscall.IFLA_MTU, b) data := nl.NewRtAttr(unix.IFLA_MTU, b)
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -228,16 +229,16 @@ func LinkSetName(link Link, name string) error {
func (h *Handle) LinkSetName(link Link, name string) error { func (h *Handle) LinkSetName(link Link, name string) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
data := nl.NewRtAttr(syscall.IFLA_IFNAME, []byte(name)) data := nl.NewRtAttr(unix.IFLA_IFNAME, []byte(name))
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -252,16 +253,16 @@ func LinkSetAlias(link Link, name string) error {
func (h *Handle) LinkSetAlias(link Link, name string) error { func (h *Handle) LinkSetAlias(link Link, name string) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
data := nl.NewRtAttr(syscall.IFLA_IFALIAS, []byte(name)) data := nl.NewRtAttr(unix.IFLA_IFALIAS, []byte(name))
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -276,16 +277,16 @@ func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
data := nl.NewRtAttr(syscall.IFLA_ADDRESS, []byte(hwaddr)) data := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(hwaddr))
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -300,9 +301,9 @@ func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -315,7 +316,7 @@ func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAdd
nl.NewRtAttrChild(info, nl.IFLA_VF_MAC, vfmsg.Serialize()) nl.NewRtAttrChild(info, nl.IFLA_VF_MAC, vfmsg.Serialize())
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -330,9 +331,9 @@ func LinkSetVfVlan(link Link, vf, vlan int) error {
func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error { func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -345,7 +346,7 @@ func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize()) nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize())
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -360,9 +361,9 @@ func LinkSetVfTxRate(link Link, vf, rate int) error {
func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error { func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -375,7 +376,7 @@ func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
nl.NewRtAttrChild(info, nl.IFLA_VF_TX_RATE, vfmsg.Serialize()) nl.NewRtAttrChild(info, nl.IFLA_VF_TX_RATE, vfmsg.Serialize())
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -391,9 +392,9 @@ func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error {
var setting uint32 var setting uint32
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -409,7 +410,7 @@ func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error {
nl.NewRtAttrChild(info, nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize()) nl.NewRtAttrChild(info, nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize())
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -425,9 +426,9 @@ func (h *Handle) LinkSetVfTrust(link Link, vf int, state bool) error {
var setting uint32 var setting uint32
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -443,7 +444,7 @@ func (h *Handle) LinkSetVfTrust(link Link, vf int, state bool) error {
nl.NewRtAttrChild(info, nl.IFLA_VF_TRUST, vfmsg.Serialize()) nl.NewRtAttrChild(info, nl.IFLA_VF_TRUST, vfmsg.Serialize())
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -491,19 +492,19 @@ func LinkSetMasterByIndex(link Link, masterIndex int) error {
func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error { func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(masterIndex)) native.PutUint32(b, uint32(masterIndex))
data := nl.NewRtAttr(syscall.IFLA_MASTER, b) data := nl.NewRtAttr(unix.IFLA_MASTER, b)
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -520,19 +521,19 @@ func LinkSetNsPid(link Link, nspid int) error {
func (h *Handle) LinkSetNsPid(link Link, nspid int) error { func (h *Handle) LinkSetNsPid(link Link, nspid int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(nspid)) native.PutUint32(b, uint32(nspid))
data := nl.NewRtAttr(syscall.IFLA_NET_NS_PID, b) data := nl.NewRtAttr(unix.IFLA_NET_NS_PID, b)
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -549,9 +550,9 @@ func LinkSetNsFd(link Link, fd int) error {
func (h *Handle) LinkSetNsFd(link Link, fd int) error { func (h *Handle) LinkSetNsFd(link Link, fd int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
@@ -561,7 +562,7 @@ func (h *Handle) LinkSetNsFd(link Link, fd int) error {
data := nl.NewRtAttr(nl.IFLA_NET_NS_FD, b) data := nl.NewRtAttr(nl.IFLA_NET_NS_FD, b)
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -576,15 +577,15 @@ func LinkSetXdpFd(link Link, fd int) error {
func LinkSetXdpFdWithFlags(link Link, fd, flags int) error { func LinkSetXdpFdWithFlags(link Link, fd, flags int) error {
base := link.Attrs() base := link.Attrs()
ensureIndex(base) ensureIndex(base)
req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := nl.NewNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
addXdpAttrs(&LinkXdp{Fd: fd, Flags: uint32(flags)}, req) addXdpAttrs(&LinkXdp{Fd: fd, Flags: uint32(flags)}, req)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -777,7 +778,7 @@ func LinkAdd(link Link) error {
// are taken fromt the parameters in the link object. // are taken fromt the parameters in the link object.
// Equivalent to: `ip link add $link` // Equivalent to: `ip link add $link`
func (h *Handle) LinkAdd(link Link) error { func (h *Handle) LinkAdd(link Link) error {
return h.linkModify(link, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) return h.linkModify(link, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
} }
func (h *Handle) linkModify(link Link, flags int) error { func (h *Handle) linkModify(link Link, flags int) error {
@@ -793,7 +794,7 @@ func (h *Handle) linkModify(link Link, flags int) error {
// TODO: support group // TODO: support group
// TODO: multi_queue // TODO: multi_queue
// TODO: support non- persistent // TODO: support non- persistent
if tuntap.Mode < syscall.IFF_TUN || tuntap.Mode > syscall.IFF_TAP { if tuntap.Mode < unix.IFF_TUN || tuntap.Mode > unix.IFF_TAP {
return fmt.Errorf("Tuntap.Mode %v unknown!", tuntap.Mode) return fmt.Errorf("Tuntap.Mode %v unknown!", tuntap.Mode)
} }
file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0) file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
@@ -809,11 +810,11 @@ func (h *Handle) linkModify(link Link, flags int) error {
} }
req.Flags |= uint16(tuntap.Mode) req.Flags |= uint16(tuntap.Mode)
copy(req.Name[:15], base.Name) copy(req.Name[:15], base.Name)
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETIFF), uintptr(unsafe.Pointer(&req))) _, _, errno := unix.Syscall(unix.SYS_IOCTL, file.Fd(), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req)))
if errno != 0 { if errno != 0 {
return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed, errno %v", errno) return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed, errno %v", errno)
} }
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETPERSIST), 1) _, _, errno = unix.Syscall(unix.SYS_IOCTL, file.Fd(), uintptr(unix.TUNSETPERSIST), 1)
if errno != 0 { if errno != 0 {
return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno) return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno)
} }
@@ -827,29 +828,29 @@ func (h *Handle) linkModify(link Link, flags int) error {
return nil return nil
} }
req := h.newNetlinkRequest(syscall.RTM_NEWLINK, flags) req := h.newNetlinkRequest(unix.RTM_NEWLINK, flags)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
// TODO: make it shorter // TODO: make it shorter
if base.Flags&net.FlagUp != 0 { if base.Flags&net.FlagUp != 0 {
msg.Change = syscall.IFF_UP msg.Change = unix.IFF_UP
msg.Flags = syscall.IFF_UP msg.Flags = unix.IFF_UP
} }
if base.Flags&net.FlagBroadcast != 0 { if base.Flags&net.FlagBroadcast != 0 {
msg.Change |= syscall.IFF_BROADCAST msg.Change |= unix.IFF_BROADCAST
msg.Flags |= syscall.IFF_BROADCAST msg.Flags |= unix.IFF_BROADCAST
} }
if base.Flags&net.FlagLoopback != 0 { if base.Flags&net.FlagLoopback != 0 {
msg.Change |= syscall.IFF_LOOPBACK msg.Change |= unix.IFF_LOOPBACK
msg.Flags |= syscall.IFF_LOOPBACK msg.Flags |= unix.IFF_LOOPBACK
} }
if base.Flags&net.FlagPointToPoint != 0 { if base.Flags&net.FlagPointToPoint != 0 {
msg.Change |= syscall.IFF_POINTOPOINT msg.Change |= unix.IFF_POINTOPOINT
msg.Flags |= syscall.IFF_POINTOPOINT msg.Flags |= unix.IFF_POINTOPOINT
} }
if base.Flags&net.FlagMulticast != 0 { if base.Flags&net.FlagMulticast != 0 {
msg.Change |= syscall.IFF_MULTICAST msg.Change |= unix.IFF_MULTICAST
msg.Flags |= syscall.IFF_MULTICAST msg.Flags |= unix.IFF_MULTICAST
} }
if base.Index != 0 { if base.Index != 0 {
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
@@ -860,27 +861,27 @@ func (h *Handle) linkModify(link Link, flags int) error {
if base.ParentIndex != 0 { if base.ParentIndex != 0 {
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(base.ParentIndex)) native.PutUint32(b, uint32(base.ParentIndex))
data := nl.NewRtAttr(syscall.IFLA_LINK, b) data := nl.NewRtAttr(unix.IFLA_LINK, b)
req.AddData(data) req.AddData(data)
} else if link.Type() == "ipvlan" { } else if link.Type() == "ipvlan" {
return fmt.Errorf("Can't create ipvlan link without ParentIndex") return fmt.Errorf("Can't create ipvlan link without ParentIndex")
} }
nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(base.Name)) nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(base.Name))
req.AddData(nameData) req.AddData(nameData)
if base.MTU > 0 { if base.MTU > 0 {
mtu := nl.NewRtAttr(syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) mtu := nl.NewRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
req.AddData(mtu) req.AddData(mtu)
} }
if base.TxQLen >= 0 { if base.TxQLen >= 0 {
qlen := nl.NewRtAttr(syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) qlen := nl.NewRtAttr(unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
req.AddData(qlen) req.AddData(qlen)
} }
if base.HardwareAddr != nil { if base.HardwareAddr != nil {
hwaddr := nl.NewRtAttr(syscall.IFLA_ADDRESS, []byte(base.HardwareAddr)) hwaddr := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(base.HardwareAddr))
req.AddData(hwaddr) req.AddData(hwaddr)
} }
@@ -889,7 +890,7 @@ func (h *Handle) linkModify(link Link, flags int) error {
switch base.Namespace.(type) { switch base.Namespace.(type) {
case NsPid: case NsPid:
val := nl.Uint32Attr(uint32(base.Namespace.(NsPid))) val := nl.Uint32Attr(uint32(base.Namespace.(NsPid)))
attr = nl.NewRtAttr(syscall.IFLA_NET_NS_PID, val) attr = nl.NewRtAttr(unix.IFLA_NET_NS_PID, val)
case NsFd: case NsFd:
val := nl.Uint32Attr(uint32(base.Namespace.(NsFd))) val := nl.Uint32Attr(uint32(base.Namespace.(NsFd)))
attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val) attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val)
@@ -902,7 +903,7 @@ func (h *Handle) linkModify(link Link, flags int) error {
addXdpAttrs(base.Xdp, req) addXdpAttrs(base.Xdp, req)
} }
linkInfo := nl.NewRtAttr(syscall.IFLA_LINKINFO, nil) linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil)
nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))
switch link := link.(type) { switch link := link.(type) {
@@ -914,13 +915,13 @@ func (h *Handle) linkModify(link Link, flags int) error {
case *Veth: case *Veth:
data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil) data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
peer := nl.NewRtAttrChild(data, nl.VETH_INFO_PEER, nil) peer := nl.NewRtAttrChild(data, nl.VETH_INFO_PEER, nil)
nl.NewIfInfomsgChild(peer, syscall.AF_UNSPEC) nl.NewIfInfomsgChild(peer, unix.AF_UNSPEC)
nl.NewRtAttrChild(peer, syscall.IFLA_IFNAME, nl.ZeroTerminated(link.PeerName)) nl.NewRtAttrChild(peer, unix.IFLA_IFNAME, nl.ZeroTerminated(link.PeerName))
if base.TxQLen >= 0 { if base.TxQLen >= 0 {
nl.NewRtAttrChild(peer, syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) nl.NewRtAttrChild(peer, unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
} }
if base.MTU > 0 { if base.MTU > 0 {
nl.NewRtAttrChild(peer, syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) nl.NewRtAttrChild(peer, unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
} }
case *Vxlan: case *Vxlan:
@@ -958,7 +959,7 @@ func (h *Handle) linkModify(link Link, flags int) error {
req.AddData(linkInfo) req.AddData(linkInfo)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil { if err != nil {
return err return err
} }
@@ -988,13 +989,13 @@ func (h *Handle) LinkDel(link Link) error {
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_DELLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -1037,16 +1038,16 @@ func (h *Handle) LinkByName(name string) (Link, error) {
return h.linkByNameDump(name) return h.linkByNameDump(name)
} }
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg) req.AddData(msg)
nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(name)) nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(name))
req.AddData(nameData) req.AddData(nameData)
link, err := execGetLink(req) link, err := execGetLink(req)
if err == syscall.EINVAL { if err == unix.EINVAL {
// older kernels don't support looking up via IFLA_IFNAME // older kernels don't support looking up via IFLA_IFNAME
// so fall back to dumping all links // so fall back to dumping all links
h.lookupByDump = true h.lookupByDump = true
@@ -1069,16 +1070,16 @@ func (h *Handle) LinkByAlias(alias string) (Link, error) {
return h.linkByAliasDump(alias) return h.linkByAliasDump(alias)
} }
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg) req.AddData(msg)
nameData := nl.NewRtAttr(syscall.IFLA_IFALIAS, nl.ZeroTerminated(alias)) nameData := nl.NewRtAttr(unix.IFLA_IFALIAS, nl.ZeroTerminated(alias))
req.AddData(nameData) req.AddData(nameData)
link, err := execGetLink(req) link, err := execGetLink(req)
if err == syscall.EINVAL { if err == unix.EINVAL {
// older kernels don't support looking up via IFLA_IFALIAS // older kernels don't support looking up via IFLA_IFALIAS
// so fall back to dumping all links // so fall back to dumping all links
h.lookupByDump = true h.lookupByDump = true
@@ -1095,9 +1096,9 @@ func LinkByIndex(index int) (Link, error) {
// LinkByIndex finds a link by index and returns a pointer to the object. // LinkByIndex finds a link by index and returns a pointer to the object.
func (h *Handle) LinkByIndex(index int) (Link, error) { func (h *Handle) LinkByIndex(index int) (Link, error) {
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(index) msg.Index = int32(index)
req.AddData(msg) req.AddData(msg)
@@ -1105,10 +1106,10 @@ func (h *Handle) LinkByIndex(index int) (Link, error) {
} }
func execGetLink(req *nl.NetlinkRequest) (Link, error) { func execGetLink(req *nl.NetlinkRequest) (Link, error) {
msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0) msgs, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil { if err != nil {
if errno, ok := err.(syscall.Errno); ok { if errno, ok := err.(syscall.Errno); ok {
if errno == syscall.ENODEV { if errno == unix.ENODEV {
return nil, LinkNotFoundError{fmt.Errorf("Link not found")} return nil, LinkNotFoundError{fmt.Errorf("Link not found")}
} }
} }
@@ -1129,7 +1130,7 @@ func execGetLink(req *nl.NetlinkRequest) (Link, error) {
// linkDeserialize deserializes a raw message received from netlink into // linkDeserialize deserializes a raw message received from netlink into
// a link object. // a link object.
func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) { func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) {
msg := nl.DeserializeIfInfomsg(m) msg := nl.DeserializeIfInfomsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():]) attrs, err := nl.ParseRouteAttr(m[msg.Len():])
@@ -1138,7 +1139,7 @@ func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
} }
base := LinkAttrs{Index: int(msg.Index), RawFlags: msg.Flags, Flags: linkFlags(msg.Flags), EncapType: msg.EncapType()} base := LinkAttrs{Index: int(msg.Index), RawFlags: msg.Flags, Flags: linkFlags(msg.Flags), EncapType: msg.EncapType()}
if msg.Flags&syscall.IFF_PROMISC != 0 { if msg.Flags&unix.IFF_PROMISC != 0 {
base.Promisc = 1 base.Promisc = 1
} }
var ( var (
@@ -1149,7 +1150,7 @@ func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
) )
for _, attr := range attrs { for _, attr := range attrs {
switch attr.Attr.Type { switch attr.Attr.Type {
case syscall.IFLA_LINKINFO: case unix.IFLA_LINKINFO:
infos, err := nl.ParseRouteAttr(attr.Value) infos, err := nl.ParseRouteAttr(attr.Value)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -1229,7 +1230,7 @@ func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
} }
} }
} }
case syscall.IFLA_ADDRESS: case unix.IFLA_ADDRESS:
var nonzero bool var nonzero bool
for _, b := range attr.Value { for _, b := range attr.Value {
if b != 0 { if b != 0 {
@@ -1239,19 +1240,19 @@ func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
if nonzero { if nonzero {
base.HardwareAddr = attr.Value[:] base.HardwareAddr = attr.Value[:]
} }
case syscall.IFLA_IFNAME: case unix.IFLA_IFNAME:
base.Name = string(attr.Value[:len(attr.Value)-1]) base.Name = string(attr.Value[:len(attr.Value)-1])
case syscall.IFLA_MTU: case unix.IFLA_MTU:
base.MTU = int(native.Uint32(attr.Value[0:4])) base.MTU = int(native.Uint32(attr.Value[0:4]))
case syscall.IFLA_LINK: case unix.IFLA_LINK:
base.ParentIndex = int(native.Uint32(attr.Value[0:4])) base.ParentIndex = int(native.Uint32(attr.Value[0:4]))
case syscall.IFLA_MASTER: case unix.IFLA_MASTER:
base.MasterIndex = int(native.Uint32(attr.Value[0:4])) base.MasterIndex = int(native.Uint32(attr.Value[0:4]))
case syscall.IFLA_TXQLEN: case unix.IFLA_TXQLEN:
base.TxQLen = int(native.Uint32(attr.Value[0:4])) base.TxQLen = int(native.Uint32(attr.Value[0:4]))
case syscall.IFLA_IFALIAS: case unix.IFLA_IFALIAS:
base.Alias = string(attr.Value[:len(attr.Value)-1]) base.Alias = string(attr.Value[:len(attr.Value)-1])
case syscall.IFLA_STATS: case unix.IFLA_STATS:
stats32 = attr.Value[:] stats32 = attr.Value[:]
case IFLA_STATS64: case IFLA_STATS64:
stats64 = attr.Value[:] stats64 = attr.Value[:]
@@ -1261,16 +1262,16 @@ func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
return nil, err return nil, err
} }
base.Xdp = xdp base.Xdp = xdp
case syscall.IFLA_PROTINFO | syscall.NLA_F_NESTED: case unix.IFLA_PROTINFO | unix.NLA_F_NESTED:
if hdr != nil && hdr.Type == syscall.RTM_NEWLINK && if hdr != nil && hdr.Type == unix.RTM_NEWLINK &&
msg.Family == syscall.AF_BRIDGE { msg.Family == unix.AF_BRIDGE {
attrs, err := nl.ParseRouteAttr(attr.Value[:]) attrs, err := nl.ParseRouteAttr(attr.Value[:])
if err != nil { if err != nil {
return nil, err return nil, err
} }
base.Protinfo = parseProtinfo(attrs) base.Protinfo = parseProtinfo(attrs)
} }
case syscall.IFLA_OPERSTATE: case unix.IFLA_OPERSTATE:
base.OperState = LinkOperState(uint8(attr.Value[0])) base.OperState = LinkOperState(uint8(attr.Value[0]))
case nl.IFLA_LINK_NETNSID: case nl.IFLA_LINK_NETNSID:
base.NetNsID = int(native.Uint32(attr.Value[0:4])) base.NetNsID = int(native.Uint32(attr.Value[0:4]))
@@ -1303,12 +1304,12 @@ func LinkList() ([]Link, error) {
func (h *Handle) LinkList() ([]Link, error) { func (h *Handle) LinkList() ([]Link, error) {
// NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need // NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need
// to get the message ourselves to parse link type. // to get the message ourselves to parse link type.
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWLINK) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1328,7 +1329,7 @@ func (h *Handle) LinkList() ([]Link, error) {
// LinkUpdate is used to pass information back from LinkSubscribe() // LinkUpdate is used to pass information back from LinkSubscribe()
type LinkUpdate struct { type LinkUpdate struct {
nl.IfInfomsg nl.IfInfomsg
Header syscall.NlMsghdr Header unix.NlMsghdr
Link Link
} }
@@ -1363,7 +1364,7 @@ func LinkSubscribeWithOptions(ch chan<- LinkUpdate, done <-chan struct{}, option
} }
func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}, cberr func(error)) error { func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}, cberr func(error)) error {
s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_LINK) s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_LINK)
if err != nil { if err != nil {
return err return err
} }
@@ -1385,14 +1386,15 @@ func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-c
} }
for _, m := range msgs { for _, m := range msgs {
ifmsg := nl.DeserializeIfInfomsg(m.Data) ifmsg := nl.DeserializeIfInfomsg(m.Data)
link, err := LinkDeserialize(&m.Header, m.Data) header := unix.NlMsghdr(m.Header)
link, err := LinkDeserialize(&header, m.Data)
if err != nil { if err != nil {
if cberr != nil { if cberr != nil {
cberr(err) cberr(err)
} }
return return
} }
ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: m.Header, Link: link} ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: header, Link: link}
} }
} }
}() }()
@@ -1467,16 +1469,16 @@ func (h *Handle) LinkSetBrProxyArpWiFi(link Link, mode bool) error {
func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error { func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE) msg := nl.NewIfInfomsg(unix.AF_BRIDGE)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
br := nl.NewRtAttr(syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED, nil) br := nl.NewRtAttr(unix.IFLA_PROTINFO|unix.NLA_F_NESTED, nil)
nl.NewRtAttrChild(br, attr, boolToByte(mode)) nl.NewRtAttrChild(br, attr, boolToByte(mode))
req.AddData(br) req.AddData(br)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil { if err != nil {
return err return err
} }
@@ -1494,19 +1496,19 @@ func LinkSetTxQLen(link Link, qlen int) error {
func (h *Handle) LinkSetTxQLen(link Link, qlen int) error { func (h *Handle) LinkSetTxQLen(link Link, qlen int) error {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index) msg.Index = int32(base.Index)
req.AddData(msg) req.AddData(msg)
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(qlen)) native.PutUint32(b, uint32(qlen))
data := nl.NewRtAttr(syscall.IFLA_TXQLEN, b) data := nl.NewRtAttr(unix.IFLA_TXQLEN, b)
req.AddData(data) req.AddData(data)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -1675,19 +1677,19 @@ func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) {
// copied from pkg/net_linux.go // copied from pkg/net_linux.go
func linkFlags(rawFlags uint32) net.Flags { func linkFlags(rawFlags uint32) net.Flags {
var f net.Flags var f net.Flags
if rawFlags&syscall.IFF_UP != 0 { if rawFlags&unix.IFF_UP != 0 {
f |= net.FlagUp f |= net.FlagUp
} }
if rawFlags&syscall.IFF_BROADCAST != 0 { if rawFlags&unix.IFF_BROADCAST != 0 {
f |= net.FlagBroadcast f |= net.FlagBroadcast
} }
if rawFlags&syscall.IFF_LOOPBACK != 0 { if rawFlags&unix.IFF_LOOPBACK != 0 {
f |= net.FlagLoopback f |= net.FlagLoopback
} }
if rawFlags&syscall.IFF_POINTOPOINT != 0 { if rawFlags&unix.IFF_POINTOPOINT != 0 {
f |= net.FlagPointToPoint f |= net.FlagPointToPoint
} }
if rawFlags&syscall.IFF_MULTICAST != 0 { if rawFlags&unix.IFF_MULTICAST != 0 {
f |= net.FlagMulticast f |= net.FlagMulticast
} }
return f return f
@@ -1844,7 +1846,7 @@ func parseLinkStats64(data []byte) *LinkStatistics {
} }
func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) { func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) {
attrs := nl.NewRtAttr(nl.IFLA_XDP|syscall.NLA_F_NESTED, nil) attrs := nl.NewRtAttr(nl.IFLA_XDP|unix.NLA_F_NESTED, nil)
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(xdp.Fd)) native.PutUint32(b, uint32(xdp.Fd))
nl.NewRtAttrChild(attrs, nl.IFLA_XDP_FD, b) nl.NewRtAttrChild(attrs, nl.IFLA_XDP_FD, b)

View File

@@ -6,12 +6,12 @@ import (
"bytes" "bytes"
"net" "net"
"os" "os"
"syscall"
"testing" "testing"
"time" "time"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
const ( const (
@@ -981,7 +981,7 @@ func TestLinkSetARP(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if link.Attrs().RawFlags&syscall.IFF_NOARP != uint32(syscall.IFF_NOARP) { if link.Attrs().RawFlags&unix.IFF_NOARP != uint32(unix.IFF_NOARP) {
t.Fatalf("NOARP was not set!") t.Fatalf("NOARP was not set!")
} }
@@ -995,7 +995,7 @@ func TestLinkSetARP(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if link.Attrs().RawFlags&syscall.IFF_NOARP != 0 { if link.Attrs().RawFlags&unix.IFF_NOARP != 0 {
t.Fatalf("NOARP is still set!") t.Fatalf("NOARP is still set!")
} }
} }
@@ -1005,7 +1005,7 @@ func expectLinkUpdate(ch <-chan LinkUpdate, ifaceName string, up bool) bool {
timeout := time.After(time.Minute) timeout := time.After(time.Minute)
select { select {
case update := <-ch: case update := <-ch:
if ifaceName == update.Link.Attrs().Name && (update.IfInfomsg.Flags&syscall.IFF_UP != 0) == up { if ifaceName == update.Link.Attrs().Name && (update.IfInfomsg.Flags&unix.IFF_UP != 0) == up {
return true return true
} }
case <-timeout: case <-timeout:
@@ -1202,7 +1202,7 @@ func TestLinkXdp(t *testing.T) {
if err := LinkSetXdpFd(testXdpLink, fd); err != nil { if err := LinkSetXdpFd(testXdpLink, fd); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := LinkSetXdpFdWithFlags(testXdpLink, fd, nl.XDP_FLAGS_UPDATE_IF_NOEXIST); err != syscall.EBUSY { if err := LinkSetXdpFdWithFlags(testXdpLink, fd, nl.XDP_FLAGS_UPDATE_IF_NOEXIST); err != unix.EBUSY {
t.Fatal(err) t.Fatal(err)
} }
if err := LinkSetXdpFd(testXdpLink, -1); err != nil { if err := LinkSetXdpFd(testXdpLink, -1); err != nil {

View File

@@ -2,10 +2,10 @@ package netlink
import ( import (
"net" "net"
"syscall"
"unsafe" "unsafe"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
const ( const (
@@ -73,7 +73,7 @@ func NeighAdd(neigh *Neigh) error {
// NeighAdd will add an IP to MAC mapping to the ARP table // NeighAdd will add an IP to MAC mapping to the ARP table
// Equivalent to: `ip neigh add ....` // Equivalent to: `ip neigh add ....`
func (h *Handle) NeighAdd(neigh *Neigh) error { func (h *Handle) NeighAdd(neigh *Neigh) error {
return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL) return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_EXCL)
} }
// NeighSet will add or replace an IP to MAC mapping to the ARP table // NeighSet will add or replace an IP to MAC mapping to the ARP table
@@ -85,7 +85,7 @@ func NeighSet(neigh *Neigh) error {
// NeighSet will add or replace an IP to MAC mapping to the ARP table // NeighSet will add or replace an IP to MAC mapping to the ARP table
// Equivalent to: `ip neigh replace....` // Equivalent to: `ip neigh replace....`
func (h *Handle) NeighSet(neigh *Neigh) error { func (h *Handle) NeighSet(neigh *Neigh) error {
return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE) return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_REPLACE)
} }
// NeighAppend will append an entry to FDB // NeighAppend will append an entry to FDB
@@ -97,7 +97,7 @@ func NeighAppend(neigh *Neigh) error {
// NeighAppend will append an entry to FDB // NeighAppend will append an entry to FDB
// Equivalent to: `bridge fdb append...` // Equivalent to: `bridge fdb append...`
func (h *Handle) NeighAppend(neigh *Neigh) error { func (h *Handle) NeighAppend(neigh *Neigh) error {
return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_APPEND) return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_APPEND)
} }
// NeighAppend will append an entry to FDB // NeighAppend will append an entry to FDB
@@ -109,7 +109,7 @@ func neighAdd(neigh *Neigh, mode int) error {
// NeighAppend will append an entry to FDB // NeighAppend will append an entry to FDB
// Equivalent to: `bridge fdb append...` // Equivalent to: `bridge fdb append...`
func (h *Handle) neighAdd(neigh *Neigh, mode int) error { func (h *Handle) neighAdd(neigh *Neigh, mode int) error {
req := h.newNetlinkRequest(syscall.RTM_NEWNEIGH, mode|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWNEIGH, mode|unix.NLM_F_ACK)
return neighHandle(neigh, req) return neighHandle(neigh, req)
} }
@@ -122,7 +122,7 @@ func NeighDel(neigh *Neigh) error {
// NeighDel will delete an IP address from a link device. // NeighDel will delete an IP address from a link device.
// Equivalent to: `ip addr del $addr dev $link` // Equivalent to: `ip addr del $addr dev $link`
func (h *Handle) NeighDel(neigh *Neigh) error { func (h *Handle) NeighDel(neigh *Neigh) error {
req := h.newNetlinkRequest(syscall.RTM_DELNEIGH, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELNEIGH, unix.NLM_F_ACK)
return neighHandle(neigh, req) return neighHandle(neigh, req)
} }
@@ -160,7 +160,7 @@ func neighHandle(neigh *Neigh, req *nl.NetlinkRequest) error {
req.AddData(hwData) req.AddData(hwData)
} }
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -193,7 +193,7 @@ func (h *Handle) NeighProxyList(linkIndex, family int) ([]Neigh, error) {
} }
func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) { func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) {
req := h.newNetlinkRequest(syscall.RTM_GETNEIGH, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETNEIGH, unix.NLM_F_DUMP)
msg := Ndmsg{ msg := Ndmsg{
Family: uint8(family), Family: uint8(family),
Index: uint32(linkIndex), Index: uint32(linkIndex),
@@ -201,7 +201,7 @@ func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) {
} }
req.AddData(&msg) req.AddData(&msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWNEIGH) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNEIGH)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -257,7 +257,7 @@ func NeighDeserialize(m []byte) (*Neigh, error) {
// BUG: Is this a bug in the netlink library? // BUG: Is this a bug in the netlink library?
// #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len)) // #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len))
// #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0)) // #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0))
attrLen := attr.Attr.Len - syscall.SizeofRtAttr attrLen := attr.Attr.Len - unix.SizeofRtAttr
if attrLen == 4 && (encapType == "ipip" || if attrLen == 4 && (encapType == "ipip" ||
encapType == "sit" || encapType == "sit" ||
encapType == "gre") { encapType == "gre") {

View File

@@ -7,10 +7,10 @@ import (
"os" "os"
"runtime" "runtime"
"strings" "strings"
"syscall"
"testing" "testing"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
type tearDownNetlinkTest func() type tearDownNetlinkTest func()
@@ -84,11 +84,11 @@ func setUpNetlinkTestWithKModule(t *testing.T, name string) tearDownNetlinkTest
} }
func remountSysfs() error { func remountSysfs() error {
if err := syscall.Mount("", "/", "none", syscall.MS_SLAVE|syscall.MS_REC, ""); err != nil { if err := unix.Mount("", "/", "none", unix.MS_SLAVE|unix.MS_REC, ""); err != nil {
return err return err
} }
if err := syscall.Unmount("/sys", syscall.MNT_DETACH); err != nil { if err := unix.Unmount("/sys", unix.MNT_DETACH); err != nil {
return err return err
} }
return syscall.Mount("", "/sys", "sysfs", 0, "") return unix.Mount("", "/sys", "sysfs", 0, "")
} }

View File

@@ -1,17 +1,18 @@
package nl package nl
import ( import (
"syscall"
"unsafe" "unsafe"
"golang.org/x/sys/unix"
) )
type IfAddrmsg struct { type IfAddrmsg struct {
syscall.IfAddrmsg unix.IfAddrmsg
} }
func NewIfAddrmsg(family int) *IfAddrmsg { func NewIfAddrmsg(family int) *IfAddrmsg {
return &IfAddrmsg{ return &IfAddrmsg{
IfAddrmsg: syscall.IfAddrmsg{ IfAddrmsg: unix.IfAddrmsg{
Family: uint8(family), Family: uint8(family),
}, },
} }
@@ -35,15 +36,15 @@ func NewIfAddrmsg(family int) *IfAddrmsg {
// SizeofIfAddrmsg = 0x8 // SizeofIfAddrmsg = 0x8
func DeserializeIfAddrmsg(b []byte) *IfAddrmsg { func DeserializeIfAddrmsg(b []byte) *IfAddrmsg {
return (*IfAddrmsg)(unsafe.Pointer(&b[0:syscall.SizeofIfAddrmsg][0])) return (*IfAddrmsg)(unsafe.Pointer(&b[0:unix.SizeofIfAddrmsg][0]))
} }
func (msg *IfAddrmsg) Serialize() []byte { func (msg *IfAddrmsg) Serialize() []byte {
return (*(*[syscall.SizeofIfAddrmsg]byte)(unsafe.Pointer(msg)))[:] return (*(*[unix.SizeofIfAddrmsg]byte)(unsafe.Pointer(msg)))[:]
} }
func (msg *IfAddrmsg) Len() int { func (msg *IfAddrmsg) Len() int {
return syscall.SizeofIfAddrmsg return unix.SizeofIfAddrmsg
} }
// struct ifa_cacheinfo { // struct ifa_cacheinfo {

View File

@@ -4,8 +4,9 @@ import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"syscall"
"testing" "testing"
"golang.org/x/sys/unix"
) )
func (msg *IfAddrmsg) write(b []byte) { func (msg *IfAddrmsg) write(b []byte) {
@@ -18,7 +19,7 @@ func (msg *IfAddrmsg) write(b []byte) {
} }
func (msg *IfAddrmsg) serializeSafe() []byte { func (msg *IfAddrmsg) serializeSafe() []byte {
len := syscall.SizeofIfAddrmsg len := unix.SizeofIfAddrmsg
b := make([]byte, len) b := make([]byte, len)
msg.write(b) msg.write(b)
return b return b
@@ -26,12 +27,12 @@ func (msg *IfAddrmsg) serializeSafe() []byte {
func deserializeIfAddrmsgSafe(b []byte) *IfAddrmsg { func deserializeIfAddrmsgSafe(b []byte) *IfAddrmsg {
var msg = IfAddrmsg{} var msg = IfAddrmsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofIfAddrmsg]), NativeEndian(), &msg) binary.Read(bytes.NewReader(b[0:unix.SizeofIfAddrmsg]), NativeEndian(), &msg)
return &msg return &msg
} }
func TestIfAddrmsgDeserializeSerialize(t *testing.T) { func TestIfAddrmsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofIfAddrmsg) var orig = make([]byte, unix.SizeofIfAddrmsg)
rand.Read(orig) rand.Read(orig)
safemsg := deserializeIfAddrmsgSafe(orig) safemsg := deserializeIfAddrmsgSafe(orig)
msg := DeserializeIfAddrmsg(orig) msg := DeserializeIfAddrmsg(orig)

View File

@@ -1,14 +1,15 @@
package nl package nl
import ( import (
"syscall"
"unsafe" "unsafe"
"golang.org/x/sys/unix"
) )
const ( const (
DEFAULT_CHANGE = 0xFFFFFFFF DEFAULT_CHANGE = 0xFFFFFFFF
// doesn't exist in syscall // doesn't exist in syscall
IFLA_VFINFO_LIST = syscall.IFLA_IFALIAS + 1 + iota IFLA_VFINFO_LIST = unix.IFLA_IFALIAS + 1 + iota
IFLA_STATS64 IFLA_STATS64
IFLA_VF_PORTS IFLA_VF_PORTS
IFLA_PORT_SELF IFLA_PORT_SELF

View File

@@ -13,18 +13,19 @@ import (
"unsafe" "unsafe"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
const ( const (
// Family type definitions // Family type definitions
FAMILY_ALL = syscall.AF_UNSPEC FAMILY_ALL = unix.AF_UNSPEC
FAMILY_V4 = syscall.AF_INET FAMILY_V4 = unix.AF_INET
FAMILY_V6 = syscall.AF_INET6 FAMILY_V6 = unix.AF_INET6
FAMILY_MPLS = AF_MPLS FAMILY_MPLS = AF_MPLS
) )
// SupportedNlFamilies contains the list of netlink families this netlink package supports // SupportedNlFamilies contains the list of netlink families this netlink package supports
var SupportedNlFamilies = []int{syscall.NETLINK_ROUTE, syscall.NETLINK_XFRM, syscall.NETLINK_NETFILTER} var SupportedNlFamilies = []int{unix.NETLINK_ROUTE, unix.NETLINK_XFRM, unix.NETLINK_NETFILTER}
var nextSeqNr uint32 var nextSeqNr uint32
@@ -77,161 +78,161 @@ type NetlinkRequestData interface {
// IfInfomsg is related to links, but it is used for list requests as well // IfInfomsg is related to links, but it is used for list requests as well
type IfInfomsg struct { type IfInfomsg struct {
syscall.IfInfomsg unix.IfInfomsg
} }
// Create an IfInfomsg with family specified // Create an IfInfomsg with family specified
func NewIfInfomsg(family int) *IfInfomsg { func NewIfInfomsg(family int) *IfInfomsg {
return &IfInfomsg{ return &IfInfomsg{
IfInfomsg: syscall.IfInfomsg{ IfInfomsg: unix.IfInfomsg{
Family: uint8(family), Family: uint8(family),
}, },
} }
} }
func DeserializeIfInfomsg(b []byte) *IfInfomsg { func DeserializeIfInfomsg(b []byte) *IfInfomsg {
return (*IfInfomsg)(unsafe.Pointer(&b[0:syscall.SizeofIfInfomsg][0])) return (*IfInfomsg)(unsafe.Pointer(&b[0:unix.SizeofIfInfomsg][0]))
} }
func (msg *IfInfomsg) Serialize() []byte { func (msg *IfInfomsg) Serialize() []byte {
return (*(*[syscall.SizeofIfInfomsg]byte)(unsafe.Pointer(msg)))[:] return (*(*[unix.SizeofIfInfomsg]byte)(unsafe.Pointer(msg)))[:]
} }
func (msg *IfInfomsg) Len() int { func (msg *IfInfomsg) Len() int {
return syscall.SizeofIfInfomsg return unix.SizeofIfInfomsg
} }
func (msg *IfInfomsg) EncapType() string { func (msg *IfInfomsg) EncapType() string {
switch msg.Type { switch msg.Type {
case 0: case 0:
return "generic" return "generic"
case syscall.ARPHRD_ETHER: case unix.ARPHRD_ETHER:
return "ether" return "ether"
case syscall.ARPHRD_EETHER: case unix.ARPHRD_EETHER:
return "eether" return "eether"
case syscall.ARPHRD_AX25: case unix.ARPHRD_AX25:
return "ax25" return "ax25"
case syscall.ARPHRD_PRONET: case unix.ARPHRD_PRONET:
return "pronet" return "pronet"
case syscall.ARPHRD_CHAOS: case unix.ARPHRD_CHAOS:
return "chaos" return "chaos"
case syscall.ARPHRD_IEEE802: case unix.ARPHRD_IEEE802:
return "ieee802" return "ieee802"
case syscall.ARPHRD_ARCNET: case unix.ARPHRD_ARCNET:
return "arcnet" return "arcnet"
case syscall.ARPHRD_APPLETLK: case unix.ARPHRD_APPLETLK:
return "atalk" return "atalk"
case syscall.ARPHRD_DLCI: case unix.ARPHRD_DLCI:
return "dlci" return "dlci"
case syscall.ARPHRD_ATM: case unix.ARPHRD_ATM:
return "atm" return "atm"
case syscall.ARPHRD_METRICOM: case unix.ARPHRD_METRICOM:
return "metricom" return "metricom"
case syscall.ARPHRD_IEEE1394: case unix.ARPHRD_IEEE1394:
return "ieee1394" return "ieee1394"
case syscall.ARPHRD_INFINIBAND: case unix.ARPHRD_INFINIBAND:
return "infiniband" return "infiniband"
case syscall.ARPHRD_SLIP: case unix.ARPHRD_SLIP:
return "slip" return "slip"
case syscall.ARPHRD_CSLIP: case unix.ARPHRD_CSLIP:
return "cslip" return "cslip"
case syscall.ARPHRD_SLIP6: case unix.ARPHRD_SLIP6:
return "slip6" return "slip6"
case syscall.ARPHRD_CSLIP6: case unix.ARPHRD_CSLIP6:
return "cslip6" return "cslip6"
case syscall.ARPHRD_RSRVD: case unix.ARPHRD_RSRVD:
return "rsrvd" return "rsrvd"
case syscall.ARPHRD_ADAPT: case unix.ARPHRD_ADAPT:
return "adapt" return "adapt"
case syscall.ARPHRD_ROSE: case unix.ARPHRD_ROSE:
return "rose" return "rose"
case syscall.ARPHRD_X25: case unix.ARPHRD_X25:
return "x25" return "x25"
case syscall.ARPHRD_HWX25: case unix.ARPHRD_HWX25:
return "hwx25" return "hwx25"
case syscall.ARPHRD_PPP: case unix.ARPHRD_PPP:
return "ppp" return "ppp"
case syscall.ARPHRD_HDLC: case unix.ARPHRD_HDLC:
return "hdlc" return "hdlc"
case syscall.ARPHRD_LAPB: case unix.ARPHRD_LAPB:
return "lapb" return "lapb"
case syscall.ARPHRD_DDCMP: case unix.ARPHRD_DDCMP:
return "ddcmp" return "ddcmp"
case syscall.ARPHRD_RAWHDLC: case unix.ARPHRD_RAWHDLC:
return "rawhdlc" return "rawhdlc"
case syscall.ARPHRD_TUNNEL: case unix.ARPHRD_TUNNEL:
return "ipip" return "ipip"
case syscall.ARPHRD_TUNNEL6: case unix.ARPHRD_TUNNEL6:
return "tunnel6" return "tunnel6"
case syscall.ARPHRD_FRAD: case unix.ARPHRD_FRAD:
return "frad" return "frad"
case syscall.ARPHRD_SKIP: case unix.ARPHRD_SKIP:
return "skip" return "skip"
case syscall.ARPHRD_LOOPBACK: case unix.ARPHRD_LOOPBACK:
return "loopback" return "loopback"
case syscall.ARPHRD_LOCALTLK: case unix.ARPHRD_LOCALTLK:
return "ltalk" return "ltalk"
case syscall.ARPHRD_FDDI: case unix.ARPHRD_FDDI:
return "fddi" return "fddi"
case syscall.ARPHRD_BIF: case unix.ARPHRD_BIF:
return "bif" return "bif"
case syscall.ARPHRD_SIT: case unix.ARPHRD_SIT:
return "sit" return "sit"
case syscall.ARPHRD_IPDDP: case unix.ARPHRD_IPDDP:
return "ip/ddp" return "ip/ddp"
case syscall.ARPHRD_IPGRE: case unix.ARPHRD_IPGRE:
return "gre" return "gre"
case syscall.ARPHRD_PIMREG: case unix.ARPHRD_PIMREG:
return "pimreg" return "pimreg"
case syscall.ARPHRD_HIPPI: case unix.ARPHRD_HIPPI:
return "hippi" return "hippi"
case syscall.ARPHRD_ASH: case unix.ARPHRD_ASH:
return "ash" return "ash"
case syscall.ARPHRD_ECONET: case unix.ARPHRD_ECONET:
return "econet" return "econet"
case syscall.ARPHRD_IRDA: case unix.ARPHRD_IRDA:
return "irda" return "irda"
case syscall.ARPHRD_FCPP: case unix.ARPHRD_FCPP:
return "fcpp" return "fcpp"
case syscall.ARPHRD_FCAL: case unix.ARPHRD_FCAL:
return "fcal" return "fcal"
case syscall.ARPHRD_FCPL: case unix.ARPHRD_FCPL:
return "fcpl" return "fcpl"
case syscall.ARPHRD_FCFABRIC: case unix.ARPHRD_FCFABRIC:
return "fcfb0" return "fcfb0"
case syscall.ARPHRD_FCFABRIC + 1: case unix.ARPHRD_FCFABRIC + 1:
return "fcfb1" return "fcfb1"
case syscall.ARPHRD_FCFABRIC + 2: case unix.ARPHRD_FCFABRIC + 2:
return "fcfb2" return "fcfb2"
case syscall.ARPHRD_FCFABRIC + 3: case unix.ARPHRD_FCFABRIC + 3:
return "fcfb3" return "fcfb3"
case syscall.ARPHRD_FCFABRIC + 4: case unix.ARPHRD_FCFABRIC + 4:
return "fcfb4" return "fcfb4"
case syscall.ARPHRD_FCFABRIC + 5: case unix.ARPHRD_FCFABRIC + 5:
return "fcfb5" return "fcfb5"
case syscall.ARPHRD_FCFABRIC + 6: case unix.ARPHRD_FCFABRIC + 6:
return "fcfb6" return "fcfb6"
case syscall.ARPHRD_FCFABRIC + 7: case unix.ARPHRD_FCFABRIC + 7:
return "fcfb7" return "fcfb7"
case syscall.ARPHRD_FCFABRIC + 8: case unix.ARPHRD_FCFABRIC + 8:
return "fcfb8" return "fcfb8"
case syscall.ARPHRD_FCFABRIC + 9: case unix.ARPHRD_FCFABRIC + 9:
return "fcfb9" return "fcfb9"
case syscall.ARPHRD_FCFABRIC + 10: case unix.ARPHRD_FCFABRIC + 10:
return "fcfb10" return "fcfb10"
case syscall.ARPHRD_FCFABRIC + 11: case unix.ARPHRD_FCFABRIC + 11:
return "fcfb11" return "fcfb11"
case syscall.ARPHRD_FCFABRIC + 12: case unix.ARPHRD_FCFABRIC + 12:
return "fcfb12" return "fcfb12"
case syscall.ARPHRD_IEEE802_TR: case unix.ARPHRD_IEEE802_TR:
return "tr" return "tr"
case syscall.ARPHRD_IEEE80211: case unix.ARPHRD_IEEE80211:
return "ieee802.11" return "ieee802.11"
case syscall.ARPHRD_IEEE80211_PRISM: case unix.ARPHRD_IEEE80211_PRISM:
return "ieee802.11/prism" return "ieee802.11/prism"
case syscall.ARPHRD_IEEE80211_RADIOTAP: case unix.ARPHRD_IEEE80211_RADIOTAP:
return "ieee802.11/radiotap" return "ieee802.11/radiotap"
case syscall.ARPHRD_IEEE802154: case unix.ARPHRD_IEEE802154:
return "ieee802.15.4" return "ieee802.15.4"
case 65534: case 65534:
@@ -243,7 +244,7 @@ func (msg *IfInfomsg) EncapType() string {
} }
func rtaAlignOf(attrlen int) int { func rtaAlignOf(attrlen int) int {
return (attrlen + syscall.RTA_ALIGNTO - 1) & ^(syscall.RTA_ALIGNTO - 1) return (attrlen + unix.RTA_ALIGNTO - 1) & ^(unix.RTA_ALIGNTO - 1)
} }
func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg { func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg {
@@ -254,7 +255,7 @@ func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg {
// Extend RtAttr to handle data and children // Extend RtAttr to handle data and children
type RtAttr struct { type RtAttr struct {
syscall.RtAttr unix.RtAttr
Data []byte Data []byte
children []NetlinkRequestData children []NetlinkRequestData
} }
@@ -262,7 +263,7 @@ type RtAttr struct {
// Create a new Extended RtAttr object // Create a new Extended RtAttr object
func NewRtAttr(attrType int, data []byte) *RtAttr { func NewRtAttr(attrType int, data []byte) *RtAttr {
return &RtAttr{ return &RtAttr{
RtAttr: syscall.RtAttr{ RtAttr: unix.RtAttr{
Type: uint16(attrType), Type: uint16(attrType),
}, },
children: []NetlinkRequestData{}, children: []NetlinkRequestData{},
@@ -279,14 +280,14 @@ func NewRtAttrChild(parent *RtAttr, attrType int, data []byte) *RtAttr {
func (a *RtAttr) Len() int { func (a *RtAttr) Len() int {
if len(a.children) == 0 { if len(a.children) == 0 {
return (syscall.SizeofRtAttr + len(a.Data)) return (unix.SizeofRtAttr + len(a.Data))
} }
l := 0 l := 0
for _, child := range a.children { for _, child := range a.children {
l += rtaAlignOf(child.Len()) l += rtaAlignOf(child.Len())
} }
l += syscall.SizeofRtAttr l += unix.SizeofRtAttr
return rtaAlignOf(l + len(a.Data)) return rtaAlignOf(l + len(a.Data))
} }
@@ -319,7 +320,7 @@ func (a *RtAttr) Serialize() []byte {
} }
type NetlinkRequest struct { type NetlinkRequest struct {
syscall.NlMsghdr unix.NlMsghdr
Data []NetlinkRequestData Data []NetlinkRequestData
RawData []byte RawData []byte
Sockets map[int]*SocketHandle Sockets map[int]*SocketHandle
@@ -327,7 +328,7 @@ type NetlinkRequest struct {
// Serialize the Netlink Request into a byte array // Serialize the Netlink Request into a byte array
func (req *NetlinkRequest) Serialize() []byte { func (req *NetlinkRequest) Serialize() []byte {
length := syscall.SizeofNlMsghdr length := unix.SizeofNlMsghdr
dataBytes := make([][]byte, len(req.Data)) dataBytes := make([][]byte, len(req.Data))
for i, data := range req.Data { for i, data := range req.Data {
dataBytes[i] = data.Serialize() dataBytes[i] = data.Serialize()
@@ -337,8 +338,8 @@ func (req *NetlinkRequest) Serialize() []byte {
req.Len = uint32(length) req.Len = uint32(length)
b := make([]byte, length) b := make([]byte, length)
hdr := (*(*[syscall.SizeofNlMsghdr]byte)(unsafe.Pointer(req)))[:] hdr := (*(*[unix.SizeofNlMsghdr]byte)(unsafe.Pointer(req)))[:]
next := syscall.SizeofNlMsghdr next := unix.SizeofNlMsghdr
copy(b[0:next], hdr) copy(b[0:next], hdr)
for _, data := range dataBytes { for _, data := range dataBytes {
for _, dataByte := range data { for _, dataByte := range data {
@@ -421,10 +422,10 @@ done:
if m.Header.Pid != pid { if m.Header.Pid != pid {
return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid) return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid)
} }
if m.Header.Type == syscall.NLMSG_DONE { if m.Header.Type == unix.NLMSG_DONE {
break done break done
} }
if m.Header.Type == syscall.NLMSG_ERROR { if m.Header.Type == unix.NLMSG_ERROR {
native := NativeEndian() native := NativeEndian()
error := int32(native.Uint32(m.Data[0:4])) error := int32(native.Uint32(m.Data[0:4]))
if error == 0 { if error == 0 {
@@ -436,7 +437,7 @@ done:
continue continue
} }
res = append(res, m.Data) res = append(res, m.Data)
if m.Header.Flags&syscall.NLM_F_MULTI == 0 { if m.Header.Flags&unix.NLM_F_MULTI == 0 {
break done break done
} }
} }
@@ -449,10 +450,10 @@ done:
// the message is serialized // the message is serialized
func NewNetlinkRequest(proto, flags int) *NetlinkRequest { func NewNetlinkRequest(proto, flags int) *NetlinkRequest {
return &NetlinkRequest{ return &NetlinkRequest{
NlMsghdr: syscall.NlMsghdr{ NlMsghdr: unix.NlMsghdr{
Len: uint32(syscall.SizeofNlMsghdr), Len: uint32(unix.SizeofNlMsghdr),
Type: uint16(proto), Type: uint16(proto),
Flags: syscall.NLM_F_REQUEST | uint16(flags), Flags: unix.NLM_F_REQUEST | uint16(flags),
Seq: atomic.AddUint32(&nextSeqNr, 1), Seq: atomic.AddUint32(&nextSeqNr, 1),
}, },
} }
@@ -460,21 +461,21 @@ func NewNetlinkRequest(proto, flags int) *NetlinkRequest {
type NetlinkSocket struct { type NetlinkSocket struct {
fd int32 fd int32
lsa syscall.SockaddrNetlink lsa unix.SockaddrNetlink
sync.Mutex sync.Mutex
} }
func getNetlinkSocket(protocol int) (*NetlinkSocket, error) { func getNetlinkSocket(protocol int) (*NetlinkSocket, error) {
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, protocol) fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW|unix.SOCK_CLOEXEC, protocol)
if err != nil { if err != nil {
return nil, err return nil, err
} }
s := &NetlinkSocket{ s := &NetlinkSocket{
fd: int32(fd), fd: int32(fd),
} }
s.lsa.Family = syscall.AF_NETLINK s.lsa.Family = unix.AF_NETLINK
if err := syscall.Bind(fd, &s.lsa); err != nil { if err := unix.Bind(fd, &s.lsa); err != nil {
syscall.Close(fd) unix.Close(fd)
return nil, err return nil, err
} }
@@ -551,21 +552,21 @@ func executeInNetns(newNs, curNs netns.NsHandle) (func(), error) {
// Returns the netlink socket on which Receive() method can be called // Returns the netlink socket on which Receive() method can be called
// to retrieve the messages from the kernel. // to retrieve the messages from the kernel.
func Subscribe(protocol int, groups ...uint) (*NetlinkSocket, error) { func Subscribe(protocol int, groups ...uint) (*NetlinkSocket, error) {
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, protocol) fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW, protocol)
if err != nil { if err != nil {
return nil, err return nil, err
} }
s := &NetlinkSocket{ s := &NetlinkSocket{
fd: int32(fd), fd: int32(fd),
} }
s.lsa.Family = syscall.AF_NETLINK s.lsa.Family = unix.AF_NETLINK
for _, g := range groups { for _, g := range groups {
s.lsa.Groups |= (1 << (g - 1)) s.lsa.Groups |= (1 << (g - 1))
} }
if err := syscall.Bind(fd, &s.lsa); err != nil { if err := unix.Bind(fd, &s.lsa); err != nil {
syscall.Close(fd) unix.Close(fd)
return nil, err return nil, err
} }
@@ -586,7 +587,7 @@ func SubscribeAt(newNs, curNs netns.NsHandle, protocol int, groups ...uint) (*Ne
func (s *NetlinkSocket) Close() { func (s *NetlinkSocket) Close() {
fd := int(atomic.SwapInt32(&s.fd, -1)) fd := int(atomic.SwapInt32(&s.fd, -1))
syscall.Close(fd) unix.Close(fd)
} }
func (s *NetlinkSocket) GetFd() int { func (s *NetlinkSocket) GetFd() int {
@@ -598,7 +599,7 @@ func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
if fd < 0 { if fd < 0 {
return fmt.Errorf("Send called on a closed socket") return fmt.Errorf("Send called on a closed socket")
} }
if err := syscall.Sendto(fd, request.Serialize(), 0, &s.lsa); err != nil { if err := unix.Sendto(fd, request.Serialize(), 0, &s.lsa); err != nil {
return err return err
} }
return nil return nil
@@ -609,12 +610,12 @@ func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
if fd < 0 { if fd < 0 {
return nil, fmt.Errorf("Receive called on a closed socket") return nil, fmt.Errorf("Receive called on a closed socket")
} }
rb := make([]byte, syscall.Getpagesize()) rb := make([]byte, unix.Getpagesize())
nr, _, err := syscall.Recvfrom(fd, rb, 0) nr, _, err := unix.Recvfrom(fd, rb, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if nr < syscall.NLMSG_HDRLEN { if nr < unix.NLMSG_HDRLEN {
return nil, fmt.Errorf("Got short response from netlink") return nil, fmt.Errorf("Got short response from netlink")
} }
rb = rb[:nr] rb = rb[:nr]
@@ -622,27 +623,27 @@ func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
} }
// SetSendTimeout allows to set a send timeout on the socket // SetSendTimeout allows to set a send timeout on the socket
func (s *NetlinkSocket) SetSendTimeout(timeout *syscall.Timeval) error { func (s *NetlinkSocket) SetSendTimeout(timeout *unix.Timeval) error {
// Set a send timeout of SOCKET_SEND_TIMEOUT, this will allow the Send to periodically unblock and avoid that a routine // Set a send timeout of SOCKET_SEND_TIMEOUT, this will allow the Send to periodically unblock and avoid that a routine
// remains stuck on a send on a closed fd // remains stuck on a send on a closed fd
return syscall.SetsockoptTimeval(int(s.fd), syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, timeout) return unix.SetsockoptTimeval(int(s.fd), unix.SOL_SOCKET, unix.SO_SNDTIMEO, timeout)
} }
// SetReceiveTimeout allows to set a receive timeout on the socket // SetReceiveTimeout allows to set a receive timeout on the socket
func (s *NetlinkSocket) SetReceiveTimeout(timeout *syscall.Timeval) error { func (s *NetlinkSocket) SetReceiveTimeout(timeout *unix.Timeval) error {
// Set a read timeout of SOCKET_READ_TIMEOUT, this will allow the Read to periodically unblock and avoid that a routine // Set a read timeout of SOCKET_READ_TIMEOUT, this will allow the Read to periodically unblock and avoid that a routine
// remains stuck on a recvmsg on a closed fd // remains stuck on a recvmsg on a closed fd
return syscall.SetsockoptTimeval(int(s.fd), syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, timeout) return unix.SetsockoptTimeval(int(s.fd), unix.SOL_SOCKET, unix.SO_RCVTIMEO, timeout)
} }
func (s *NetlinkSocket) GetPid() (uint32, error) { func (s *NetlinkSocket) GetPid() (uint32, error) {
fd := int(atomic.LoadInt32(&s.fd)) fd := int(atomic.LoadInt32(&s.fd))
lsa, err := syscall.Getsockname(fd) lsa, err := unix.Getsockname(fd)
if err != nil { if err != nil {
return 0, err return 0, err
} }
switch v := lsa.(type) { switch v := lsa.(type) {
case *syscall.SockaddrNetlink: case *unix.SockaddrNetlink:
return v.Pid, nil return v.Pid, nil
} }
return 0, fmt.Errorf("Wrong socket type") return 0, fmt.Errorf("Wrong socket type")
@@ -697,24 +698,24 @@ func Uint64Attr(v uint64) []byte {
func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) { func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
var attrs []syscall.NetlinkRouteAttr var attrs []syscall.NetlinkRouteAttr
for len(b) >= syscall.SizeofRtAttr { for len(b) >= unix.SizeofRtAttr {
a, vbuf, alen, err := netlinkRouteAttrAndValue(b) a, vbuf, alen, err := netlinkRouteAttrAndValue(b)
if err != nil { if err != nil {
return nil, err return nil, err
} }
ra := syscall.NetlinkRouteAttr{Attr: *a, Value: vbuf[:int(a.Len)-syscall.SizeofRtAttr]} ra := syscall.NetlinkRouteAttr{Attr: syscall.RtAttr(*a), Value: vbuf[:int(a.Len)-unix.SizeofRtAttr]}
attrs = append(attrs, ra) attrs = append(attrs, ra)
b = b[alen:] b = b[alen:]
} }
return attrs, nil return attrs, nil
} }
func netlinkRouteAttrAndValue(b []byte) (*syscall.RtAttr, []byte, int, error) { func netlinkRouteAttrAndValue(b []byte) (*unix.RtAttr, []byte, int, error) {
a := (*syscall.RtAttr)(unsafe.Pointer(&b[0])) a := (*unix.RtAttr)(unsafe.Pointer(&b[0]))
if int(a.Len) < syscall.SizeofRtAttr || int(a.Len) > len(b) { if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) {
return nil, nil, 0, syscall.EINVAL return nil, nil, 0, unix.EINVAL
} }
return a, b[syscall.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil return a, b[unix.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil
} }
// SocketHandle contains the netlink socket and the associated // SocketHandle contains the netlink socket and the associated

View File

@@ -5,9 +5,10 @@ import (
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"reflect" "reflect"
"syscall"
"testing" "testing"
"time" "time"
"golang.org/x/sys/unix"
) )
type testSerializer interface { type testSerializer interface {
@@ -40,7 +41,7 @@ func (msg *IfInfomsg) write(b []byte) {
} }
func (msg *IfInfomsg) serializeSafe() []byte { func (msg *IfInfomsg) serializeSafe() []byte {
length := syscall.SizeofIfInfomsg length := unix.SizeofIfInfomsg
b := make([]byte, length) b := make([]byte, length)
msg.write(b) msg.write(b)
return b return b
@@ -48,12 +49,12 @@ func (msg *IfInfomsg) serializeSafe() []byte {
func deserializeIfInfomsgSafe(b []byte) *IfInfomsg { func deserializeIfInfomsgSafe(b []byte) *IfInfomsg {
var msg = IfInfomsg{} var msg = IfInfomsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofIfInfomsg]), NativeEndian(), &msg) binary.Read(bytes.NewReader(b[0:unix.SizeofIfInfomsg]), NativeEndian(), &msg)
return &msg return &msg
} }
func TestIfInfomsgDeserializeSerialize(t *testing.T) { func TestIfInfomsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofIfInfomsg) var orig = make([]byte, unix.SizeofIfInfomsg)
rand.Read(orig) rand.Read(orig)
// zero out the pad byte // zero out the pad byte
orig[1] = 0 orig[1] = 0
@@ -63,18 +64,18 @@ func TestIfInfomsgDeserializeSerialize(t *testing.T) {
} }
func TestIfSocketCloses(t *testing.T) { func TestIfSocketCloses(t *testing.T) {
nlSock, err := Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_NEIGH) nlSock, err := Subscribe(unix.NETLINK_ROUTE, unix.RTNLGRP_NEIGH)
if err != nil { if err != nil {
t.Fatalf("Error on creating the socket: %v", err) t.Fatalf("Error on creating the socket: %v", err)
} }
nlSock.SetReceiveTimeout(&syscall.Timeval{Sec: 2, Usec: 0}) nlSock.SetReceiveTimeout(&unix.Timeval{Sec: 2, Usec: 0})
endCh := make(chan error) endCh := make(chan error)
go func(sk *NetlinkSocket, endCh chan error) { go func(sk *NetlinkSocket, endCh chan error) {
endCh <- nil endCh <- nil
for { for {
_, err := sk.Receive() _, err := sk.Receive()
// Receive returned because of a timeout and the FD == -1 means that the socket got closed // Receive returned because of a timeout and the FD == -1 means that the socket got closed
if err == syscall.EAGAIN && nlSock.GetFd() == -1 { if err == unix.EAGAIN && nlSock.GetFd() == -1 {
endCh <- err endCh <- err
return return
} }

View File

@@ -1,65 +1,66 @@
package nl package nl
import ( import (
"syscall"
"unsafe" "unsafe"
"golang.org/x/sys/unix"
) )
type RtMsg struct { type RtMsg struct {
syscall.RtMsg unix.RtMsg
} }
func NewRtMsg() *RtMsg { func NewRtMsg() *RtMsg {
return &RtMsg{ return &RtMsg{
RtMsg: syscall.RtMsg{ RtMsg: unix.RtMsg{
Table: syscall.RT_TABLE_MAIN, Table: unix.RT_TABLE_MAIN,
Scope: syscall.RT_SCOPE_UNIVERSE, Scope: unix.RT_SCOPE_UNIVERSE,
Protocol: syscall.RTPROT_BOOT, Protocol: unix.RTPROT_BOOT,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
}, },
} }
} }
func NewRtDelMsg() *RtMsg { func NewRtDelMsg() *RtMsg {
return &RtMsg{ return &RtMsg{
RtMsg: syscall.RtMsg{ RtMsg: unix.RtMsg{
Table: syscall.RT_TABLE_MAIN, Table: unix.RT_TABLE_MAIN,
Scope: syscall.RT_SCOPE_NOWHERE, Scope: unix.RT_SCOPE_NOWHERE,
}, },
} }
} }
func (msg *RtMsg) Len() int { func (msg *RtMsg) Len() int {
return syscall.SizeofRtMsg return unix.SizeofRtMsg
} }
func DeserializeRtMsg(b []byte) *RtMsg { func DeserializeRtMsg(b []byte) *RtMsg {
return (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0])) return (*RtMsg)(unsafe.Pointer(&b[0:unix.SizeofRtMsg][0]))
} }
func (msg *RtMsg) Serialize() []byte { func (msg *RtMsg) Serialize() []byte {
return (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:] return (*(*[unix.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]
} }
type RtNexthop struct { type RtNexthop struct {
syscall.RtNexthop unix.RtNexthop
Children []NetlinkRequestData Children []NetlinkRequestData
} }
func DeserializeRtNexthop(b []byte) *RtNexthop { func DeserializeRtNexthop(b []byte) *RtNexthop {
return (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0])) return (*RtNexthop)(unsafe.Pointer(&b[0:unix.SizeofRtNexthop][0]))
} }
func (msg *RtNexthop) Len() int { func (msg *RtNexthop) Len() int {
if len(msg.Children) == 0 { if len(msg.Children) == 0 {
return syscall.SizeofRtNexthop return unix.SizeofRtNexthop
} }
l := 0 l := 0
for _, child := range msg.Children { for _, child := range msg.Children {
l += rtaAlignOf(child.Len()) l += rtaAlignOf(child.Len())
} }
l += syscall.SizeofRtNexthop l += unix.SizeofRtNexthop
return rtaAlignOf(l) return rtaAlignOf(l)
} }
@@ -67,8 +68,8 @@ func (msg *RtNexthop) Serialize() []byte {
length := msg.Len() length := msg.Len()
msg.RtNexthop.Len = uint16(length) msg.RtNexthop.Len = uint16(length)
buf := make([]byte, length) buf := make([]byte, length)
copy(buf, (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]) copy(buf, (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:])
next := rtaAlignOf(syscall.SizeofRtNexthop) next := rtaAlignOf(unix.SizeofRtNexthop)
if len(msg.Children) > 0 { if len(msg.Children) > 0 {
for _, child := range msg.Children { for _, child := range msg.Children {
childBuf := child.Serialize() childBuf := child.Serialize()

View File

@@ -4,8 +4,9 @@ import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"syscall"
"testing" "testing"
"golang.org/x/sys/unix"
) )
func (msg *RtMsg) write(b []byte) { func (msg *RtMsg) write(b []byte) {
@@ -22,7 +23,7 @@ func (msg *RtMsg) write(b []byte) {
} }
func (msg *RtMsg) serializeSafe() []byte { func (msg *RtMsg) serializeSafe() []byte {
len := syscall.SizeofRtMsg len := unix.SizeofRtMsg
b := make([]byte, len) b := make([]byte, len)
msg.write(b) msg.write(b)
return b return b
@@ -30,12 +31,12 @@ func (msg *RtMsg) serializeSafe() []byte {
func deserializeRtMsgSafe(b []byte) *RtMsg { func deserializeRtMsgSafe(b []byte) *RtMsg {
var msg = RtMsg{} var msg = RtMsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofRtMsg]), NativeEndian(), &msg) binary.Read(bytes.NewReader(b[0:unix.SizeofRtMsg]), NativeEndian(), &msg)
return &msg return &msg
} }
func TestRtMsgDeserializeSerialize(t *testing.T) { func TestRtMsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofRtMsg) var orig = make([]byte, unix.SizeofRtMsg)
rand.Read(orig) rand.Read(orig)
safemsg := deserializeRtMsgSafe(orig) safemsg := deserializeRtMsgSafe(orig)
msg := DeserializeRtMsg(orig) msg := DeserializeRtMsg(orig)

View File

@@ -5,6 +5,7 @@ import (
"syscall" "syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
func LinkGetProtinfo(link Link) (Protinfo, error) { func LinkGetProtinfo(link Link) (Protinfo, error) {
@@ -15,10 +16,10 @@ func (h *Handle) LinkGetProtinfo(link Link) (Protinfo, error) {
base := link.Attrs() base := link.Attrs()
h.ensureIndex(base) h.ensureIndex(base)
var pi Protinfo var pi Protinfo
req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE) msg := nl.NewIfInfomsg(unix.AF_BRIDGE)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0) msgs, err := req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil { if err != nil {
return pi, err return pi, err
} }
@@ -33,7 +34,7 @@ func (h *Handle) LinkGetProtinfo(link Link) (Protinfo, error) {
return pi, err return pi, err
} }
for _, attr := range attrs { for _, attr := range attrs {
if attr.Attr.Type != syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED { if attr.Attr.Type != unix.IFLA_PROTINFO|unix.NLA_F_NESTED {
continue continue
} }
infos, err := nl.ParseRouteAttr(attr.Value) infos, err := nl.ParseRouteAttr(attr.Value)

View File

@@ -8,6 +8,7 @@ import (
"syscall" "syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// NOTE function is here because it uses other linux functions // NOTE function is here because it uses other linux functions
@@ -84,7 +85,7 @@ func QdiscDel(qdisc Qdisc) error {
// QdiscDel will delete a qdisc from the system. // QdiscDel will delete a qdisc from the system.
// Equivalent to: `tc qdisc del $qdisc` // Equivalent to: `tc qdisc del $qdisc`
func (h *Handle) QdiscDel(qdisc Qdisc) error { func (h *Handle) QdiscDel(qdisc Qdisc) error {
return h.qdiscModify(syscall.RTM_DELQDISC, 0, qdisc) return h.qdiscModify(unix.RTM_DELQDISC, 0, qdisc)
} }
// QdiscChange will change a qdisc in place // QdiscChange will change a qdisc in place
@@ -98,7 +99,7 @@ func QdiscChange(qdisc Qdisc) error {
// Equivalent to: `tc qdisc change $qdisc` // Equivalent to: `tc qdisc change $qdisc`
// The parent and handle MUST NOT be changed. // The parent and handle MUST NOT be changed.
func (h *Handle) QdiscChange(qdisc Qdisc) error { func (h *Handle) QdiscChange(qdisc Qdisc) error {
return h.qdiscModify(syscall.RTM_NEWQDISC, 0, qdisc) return h.qdiscModify(unix.RTM_NEWQDISC, 0, qdisc)
} }
// QdiscReplace will replace a qdisc to the system. // QdiscReplace will replace a qdisc to the system.
@@ -113,8 +114,8 @@ func QdiscReplace(qdisc Qdisc) error {
// The handle MUST change. // The handle MUST change.
func (h *Handle) QdiscReplace(qdisc Qdisc) error { func (h *Handle) QdiscReplace(qdisc Qdisc) error {
return h.qdiscModify( return h.qdiscModify(
syscall.RTM_NEWQDISC, unix.RTM_NEWQDISC,
syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE, unix.NLM_F_CREATE|unix.NLM_F_REPLACE,
qdisc) qdisc)
} }
@@ -128,13 +129,13 @@ func QdiscAdd(qdisc Qdisc) error {
// Equivalent to: `tc qdisc add $qdisc` // Equivalent to: `tc qdisc add $qdisc`
func (h *Handle) QdiscAdd(qdisc Qdisc) error { func (h *Handle) QdiscAdd(qdisc Qdisc) error {
return h.qdiscModify( return h.qdiscModify(
syscall.RTM_NEWQDISC, unix.RTM_NEWQDISC,
syscall.NLM_F_CREATE|syscall.NLM_F_EXCL, unix.NLM_F_CREATE|unix.NLM_F_EXCL,
qdisc) qdisc)
} }
func (h *Handle) qdiscModify(cmd, flags int, qdisc Qdisc) error { func (h *Handle) qdiscModify(cmd, flags int, qdisc Qdisc) error {
req := h.newNetlinkRequest(cmd, flags|syscall.NLM_F_ACK) req := h.newNetlinkRequest(cmd, flags|unix.NLM_F_ACK)
base := qdisc.Attrs() base := qdisc.Attrs()
msg := &nl.TcMsg{ msg := &nl.TcMsg{
Family: nl.FAMILY_ALL, Family: nl.FAMILY_ALL,
@@ -145,13 +146,13 @@ func (h *Handle) qdiscModify(cmd, flags int, qdisc Qdisc) error {
req.AddData(msg) req.AddData(msg)
// When deleting don't bother building the rest of the netlink payload // When deleting don't bother building the rest of the netlink payload
if cmd != syscall.RTM_DELQDISC { if cmd != unix.RTM_DELQDISC {
if err := qdiscPayload(req, qdisc); err != nil { if err := qdiscPayload(req, qdisc); err != nil {
return err return err
} }
} }
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -248,7 +249,7 @@ func QdiscList(link Link) ([]Qdisc, error) {
// Equivalent to: `tc qdisc show`. // Equivalent to: `tc qdisc show`.
// The list can be filtered by link. // The list can be filtered by link.
func (h *Handle) QdiscList(link Link) ([]Qdisc, error) { func (h *Handle) QdiscList(link Link) ([]Qdisc, error) {
req := h.newNetlinkRequest(syscall.RTM_GETQDISC, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETQDISC, unix.NLM_F_DUMP)
index := int32(0) index := int32(0)
if link != nil { if link != nil {
base := link.Attrs() base := link.Attrs()
@@ -261,7 +262,7 @@ func (h *Handle) QdiscList(link Link) ([]Qdisc, error) {
} }
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWQDISC) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWQDISC)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -8,16 +8,17 @@ import (
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
// RtAttr is shared so it is in netlink_linux.go // RtAttr is shared so it is in netlink_linux.go
const ( const (
SCOPE_UNIVERSE Scope = syscall.RT_SCOPE_UNIVERSE SCOPE_UNIVERSE Scope = unix.RT_SCOPE_UNIVERSE
SCOPE_SITE Scope = syscall.RT_SCOPE_SITE SCOPE_SITE Scope = unix.RT_SCOPE_SITE
SCOPE_LINK Scope = syscall.RT_SCOPE_LINK SCOPE_LINK Scope = unix.RT_SCOPE_LINK
SCOPE_HOST Scope = syscall.RT_SCOPE_HOST SCOPE_HOST Scope = unix.RT_SCOPE_HOST
SCOPE_NOWHERE Scope = syscall.RT_SCOPE_NOWHERE SCOPE_NOWHERE Scope = unix.RT_SCOPE_NOWHERE
) )
const ( const (
@@ -34,8 +35,8 @@ const (
) )
const ( const (
FLAG_ONLINK NextHopFlag = syscall.RTNH_F_ONLINK FLAG_ONLINK NextHopFlag = unix.RTNH_F_ONLINK
FLAG_PERVASIVE NextHopFlag = syscall.RTNH_F_PERVASIVE FLAG_PERVASIVE NextHopFlag = unix.RTNH_F_PERVASIVE
) )
var testFlags = []flagString{ var testFlags = []flagString{
@@ -194,8 +195,8 @@ func RouteAdd(route *Route) error {
// RouteAdd will add a route to the system. // RouteAdd will add a route to the system.
// Equivalent to: `ip route add $route` // Equivalent to: `ip route add $route`
func (h *Handle) RouteAdd(route *Route) error { func (h *Handle) RouteAdd(route *Route) error {
flags := syscall.NLM_F_CREATE | syscall.NLM_F_EXCL | syscall.NLM_F_ACK flags := unix.NLM_F_CREATE | unix.NLM_F_EXCL | unix.NLM_F_ACK
req := h.newNetlinkRequest(syscall.RTM_NEWROUTE, flags) req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags)
return h.routeHandle(route, req, nl.NewRtMsg()) return h.routeHandle(route, req, nl.NewRtMsg())
} }
@@ -208,8 +209,8 @@ func RouteReplace(route *Route) error {
// RouteReplace will add a route to the system. // RouteReplace will add a route to the system.
// Equivalent to: `ip route replace $route` // Equivalent to: `ip route replace $route`
func (h *Handle) RouteReplace(route *Route) error { func (h *Handle) RouteReplace(route *Route) error {
flags := syscall.NLM_F_CREATE | syscall.NLM_F_REPLACE | syscall.NLM_F_ACK flags := unix.NLM_F_CREATE | unix.NLM_F_REPLACE | unix.NLM_F_ACK
req := h.newNetlinkRequest(syscall.RTM_NEWROUTE, flags) req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags)
return h.routeHandle(route, req, nl.NewRtMsg()) return h.routeHandle(route, req, nl.NewRtMsg())
} }
@@ -222,7 +223,7 @@ func RouteDel(route *Route) error {
// RouteDel will delete a route from the system. // RouteDel will delete a route from the system.
// Equivalent to: `ip route del $route` // Equivalent to: `ip route del $route`
func (h *Handle) RouteDel(route *Route) error { func (h *Handle) RouteDel(route *Route) error {
req := h.newNetlinkRequest(syscall.RTM_DELROUTE, syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELROUTE, unix.NLM_F_ACK)
return h.routeHandle(route, req, nl.NewRtDelMsg()) return h.routeHandle(route, req, nl.NewRtDelMsg())
} }
@@ -245,12 +246,12 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
} else { } else {
dstData = route.Dst.IP.To16() dstData = route.Dst.IP.To16()
} }
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, dstData))
} else if route.MPLSDst != nil { } else if route.MPLSDst != nil {
family = nl.FAMILY_MPLS family = nl.FAMILY_MPLS
msg.Dst_len = uint8(20) msg.Dst_len = uint8(20)
msg.Type = syscall.RTN_UNICAST msg.Type = unix.RTN_UNICAST
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, nl.EncodeMPLSStack(*route.MPLSDst))) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, nl.EncodeMPLSStack(*route.MPLSDst)))
} }
if route.NewDst != nil { if route.NewDst != nil {
@@ -288,7 +289,7 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
srcData = route.Src.To16() srcData = route.Src.To16()
} }
// The commonly used src ip for routes is actually PREFSRC // The commonly used src ip for routes is actually PREFSRC
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PREFSRC, srcData)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_PREFSRC, srcData))
} }
if route.Gw != nil { if route.Gw != nil {
@@ -303,14 +304,14 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
} else { } else {
gwData = route.Gw.To16() gwData = route.Gw.To16()
} }
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_GATEWAY, gwData)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_GATEWAY, gwData))
} }
if len(route.MultiPath) > 0 { if len(route.MultiPath) > 0 {
buf := []byte{} buf := []byte{}
for _, nh := range route.MultiPath { for _, nh := range route.MultiPath {
rtnh := &nl.RtNexthop{ rtnh := &nl.RtNexthop{
RtNexthop: syscall.RtNexthop{ RtNexthop: unix.RtNexthop{
Hops: uint8(nh.Hops), Hops: uint8(nh.Hops),
Ifindex: int32(nh.LinkIndex), Ifindex: int32(nh.LinkIndex),
Flags: uint8(nh.Flags), Flags: uint8(nh.Flags),
@@ -323,9 +324,9 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
return fmt.Errorf("gateway, source, and destination ip are not the same IP family") return fmt.Errorf("gateway, source, and destination ip are not the same IP family")
} }
if gwFamily == FAMILY_V4 { if gwFamily == FAMILY_V4 {
children = append(children, nl.NewRtAttr(syscall.RTA_GATEWAY, []byte(nh.Gw.To4()))) children = append(children, nl.NewRtAttr(unix.RTA_GATEWAY, []byte(nh.Gw.To4())))
} else { } else {
children = append(children, nl.NewRtAttr(syscall.RTA_GATEWAY, []byte(nh.Gw.To16()))) children = append(children, nl.NewRtAttr(unix.RTA_GATEWAY, []byte(nh.Gw.To16())))
} }
} }
if nh.NewDst != nil { if nh.NewDst != nil {
@@ -351,15 +352,15 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
rtnh.Children = children rtnh.Children = children
buf = append(buf, rtnh.Serialize()...) buf = append(buf, rtnh.Serialize()...)
} }
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_MULTIPATH, buf)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_MULTIPATH, buf))
} }
if route.Table > 0 { if route.Table > 0 {
if route.Table >= 256 { if route.Table >= 256 {
msg.Table = syscall.RT_TABLE_UNSPEC msg.Table = unix.RT_TABLE_UNSPEC
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(route.Table)) native.PutUint32(b, uint32(route.Table))
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_TABLE, b)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_TABLE, b))
} else { } else {
msg.Table = uint8(route.Table) msg.Table = uint8(route.Table)
} }
@@ -368,7 +369,7 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
if route.Priority > 0 { if route.Priority > 0 {
b := make([]byte, 4) b := make([]byte, 4)
native.PutUint32(b, uint32(route.Priority)) native.PutUint32(b, uint32(route.Priority))
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PRIORITY, b)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_PRIORITY, b))
} }
if route.Tos > 0 { if route.Tos > 0 {
msg.Tos = uint8(route.Tos) msg.Tos = uint8(route.Tos)
@@ -394,9 +395,9 @@ func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg
) )
native.PutUint32(b, uint32(route.LinkIndex)) native.PutUint32(b, uint32(route.LinkIndex))
req.AddData(nl.NewRtAttr(syscall.RTA_OIF, b)) req.AddData(nl.NewRtAttr(unix.RTA_OIF, b))
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -429,11 +430,11 @@ func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, e
// RouteListFiltered gets a list of routes in the system filtered with specified rules. // RouteListFiltered gets a list of routes in the system filtered with specified rules.
// All rules must be defined in RouteFilter struct // All rules must be defined in RouteFilter struct
func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) { func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) {
req := h.newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_DUMP)
infmsg := nl.NewIfInfomsg(family) infmsg := nl.NewIfInfomsg(family)
req.AddData(infmsg) req.AddData(infmsg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -441,11 +442,11 @@ func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64)
var res []Route var res []Route
for _, m := range msgs { for _, m := range msgs {
msg := nl.DeserializeRtMsg(m) msg := nl.DeserializeRtMsg(m)
if msg.Flags&syscall.RTM_F_CLONED != 0 { if msg.Flags&unix.RTM_F_CLONED != 0 {
// Ignore cloned routes // Ignore cloned routes
continue continue
} }
if msg.Table != syscall.RT_TABLE_MAIN { if msg.Table != unix.RT_TABLE_MAIN {
if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 { if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 {
// Ignore non-main tables // Ignore non-main tables
continue continue
@@ -457,7 +458,7 @@ func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64)
} }
if filter != nil { if filter != nil {
switch { switch {
case filterMask&RT_FILTER_TABLE != 0 && filter.Table != syscall.RT_TABLE_UNSPEC && route.Table != filter.Table: case filterMask&RT_FILTER_TABLE != 0 && filter.Table != unix.RT_TABLE_UNSPEC && route.Table != filter.Table:
continue continue
case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol: case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol:
continue continue
@@ -508,11 +509,11 @@ func deserializeRoute(m []byte) (Route, error) {
var encap, encapType syscall.NetlinkRouteAttr var encap, encapType syscall.NetlinkRouteAttr
for _, attr := range attrs { for _, attr := range attrs {
switch attr.Attr.Type { switch attr.Attr.Type {
case syscall.RTA_GATEWAY: case unix.RTA_GATEWAY:
route.Gw = net.IP(attr.Value) route.Gw = net.IP(attr.Value)
case syscall.RTA_PREFSRC: case unix.RTA_PREFSRC:
route.Src = net.IP(attr.Value) route.Src = net.IP(attr.Value)
case syscall.RTA_DST: case unix.RTA_DST:
if msg.Family == nl.FAMILY_MPLS { if msg.Family == nl.FAMILY_MPLS {
stack := nl.DecodeMPLSStack(attr.Value) stack := nl.DecodeMPLSStack(attr.Value)
if len(stack) == 0 || len(stack) > 1 { if len(stack) == 0 || len(stack) > 1 {
@@ -525,17 +526,17 @@ func deserializeRoute(m []byte) (Route, error) {
Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)), Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
} }
} }
case syscall.RTA_OIF: case unix.RTA_OIF:
route.LinkIndex = int(native.Uint32(attr.Value[0:4])) route.LinkIndex = int(native.Uint32(attr.Value[0:4]))
case syscall.RTA_IIF: case unix.RTA_IIF:
route.ILinkIndex = int(native.Uint32(attr.Value[0:4])) route.ILinkIndex = int(native.Uint32(attr.Value[0:4]))
case syscall.RTA_PRIORITY: case unix.RTA_PRIORITY:
route.Priority = int(native.Uint32(attr.Value[0:4])) route.Priority = int(native.Uint32(attr.Value[0:4]))
case syscall.RTA_TABLE: case unix.RTA_TABLE:
route.Table = int(native.Uint32(attr.Value[0:4])) route.Table = int(native.Uint32(attr.Value[0:4]))
case syscall.RTA_MULTIPATH: case unix.RTA_MULTIPATH:
parseRtNexthop := func(value []byte) (*NexthopInfo, []byte, error) { parseRtNexthop := func(value []byte) (*NexthopInfo, []byte, error) {
if len(value) < syscall.SizeofRtNexthop { if len(value) < unix.SizeofRtNexthop {
return nil, nil, fmt.Errorf("Lack of bytes") return nil, nil, fmt.Errorf("Lack of bytes")
} }
nh := nl.DeserializeRtNexthop(value) nh := nl.DeserializeRtNexthop(value)
@@ -547,14 +548,14 @@ func deserializeRoute(m []byte) (Route, error) {
Hops: int(nh.RtNexthop.Hops), Hops: int(nh.RtNexthop.Hops),
Flags: int(nh.RtNexthop.Flags), Flags: int(nh.RtNexthop.Flags),
} }
attrs, err := nl.ParseRouteAttr(value[syscall.SizeofRtNexthop:int(nh.RtNexthop.Len)]) attrs, err := nl.ParseRouteAttr(value[unix.SizeofRtNexthop:int(nh.RtNexthop.Len)])
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
var encap, encapType syscall.NetlinkRouteAttr var encap, encapType syscall.NetlinkRouteAttr
for _, attr := range attrs { for _, attr := range attrs {
switch attr.Attr.Type { switch attr.Attr.Type {
case syscall.RTA_GATEWAY: case unix.RTA_GATEWAY:
info.Gw = net.IP(attr.Value) info.Gw = net.IP(attr.Value)
case nl.RTA_NEWDST: case nl.RTA_NEWDST:
var d Destination var d Destination
@@ -639,7 +640,7 @@ func RouteGet(destination net.IP) ([]Route, error) {
// RouteGet gets a route to a specific destination from the host system. // RouteGet gets a route to a specific destination from the host system.
// Equivalent to: 'ip route get'. // Equivalent to: 'ip route get'.
func (h *Handle) RouteGet(destination net.IP) ([]Route, error) { func (h *Handle) RouteGet(destination net.IP) ([]Route, error) {
req := h.newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_REQUEST) req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_REQUEST)
family := nl.GetIPFamily(destination) family := nl.GetIPFamily(destination)
var destinationData []byte var destinationData []byte
var bitlen uint8 var bitlen uint8
@@ -655,10 +656,10 @@ func (h *Handle) RouteGet(destination net.IP) ([]Route, error) {
msg.Dst_len = bitlen msg.Dst_len = bitlen
req.AddData(msg) req.AddData(msg)
rtaDst := nl.NewRtAttr(syscall.RTA_DST, destinationData) rtaDst := nl.NewRtAttr(unix.RTA_DST, destinationData)
req.AddData(rtaDst) req.AddData(rtaDst)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -706,7 +707,7 @@ func RouteSubscribeWithOptions(ch chan<- RouteUpdate, done <-chan struct{}, opti
} }
func routeSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}, cberr func(error)) error { func routeSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}, cberr func(error)) error {
s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_ROUTE, syscall.RTNLGRP_IPV6_ROUTE) s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_IPV4_ROUTE, unix.RTNLGRP_IPV6_ROUTE)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -5,11 +5,11 @@ package netlink
import ( import (
"net" "net"
"strconv" "strconv"
"syscall"
"testing" "testing"
"time" "time"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
func TestRouteAddDel(t *testing.T) { func TestRouteAddDel(t *testing.T) {
@@ -199,13 +199,13 @@ func TestRouteSubscribe(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if !expectRouteUpdate(ch, syscall.RTM_NEWROUTE, dst.IP) { if !expectRouteUpdate(ch, unix.RTM_NEWROUTE, dst.IP) {
t.Fatal("Add update not received as expected") t.Fatal("Add update not received as expected")
} }
if err := RouteDel(&route); err != nil { if err := RouteDel(&route); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !expectRouteUpdate(ch, syscall.RTM_DELROUTE, dst.IP) { if !expectRouteUpdate(ch, unix.RTM_DELROUTE, dst.IP) {
t.Fatal("Del update not received as expected") t.Fatal("Del update not received as expected")
} }
} }
@@ -254,7 +254,7 @@ func TestRouteSubscribeWithOptions(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if !expectRouteUpdate(ch, syscall.RTM_NEWROUTE, dst.IP) { if !expectRouteUpdate(ch, unix.RTM_NEWROUTE, dst.IP) {
t.Fatal("Add update not received as expected") t.Fatal("Add update not received as expected")
} }
} }
@@ -306,13 +306,13 @@ func TestRouteSubscribeAt(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if !expectRouteUpdate(ch, syscall.RTM_NEWROUTE, dst.IP) { if !expectRouteUpdate(ch, unix.RTM_NEWROUTE, dst.IP) {
t.Fatal("Add update not received as expected") t.Fatal("Add update not received as expected")
} }
if err := nh.RouteDel(&route); err != nil { if err := nh.RouteDel(&route); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !expectRouteUpdate(ch, syscall.RTM_DELROUTE, dst.IP) { if !expectRouteUpdate(ch, unix.RTM_DELROUTE, dst.IP) {
t.Fatal("Del update not received as expected") t.Fatal("Del update not received as expected")
} }
} }
@@ -344,10 +344,10 @@ func TestRouteFilterAllTables(t *testing.T) {
LinkIndex: link.Attrs().Index, LinkIndex: link.Attrs().Index,
Dst: dst, Dst: dst,
Src: src, Src: src,
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Priority: 13, Priority: 13,
Table: table, Table: table,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
Tos: 14, Tos: 14,
} }
if err := RouteAdd(&route); err != nil { if err := RouteAdd(&route); err != nil {
@@ -357,9 +357,9 @@ func TestRouteFilterAllTables(t *testing.T) {
routes, err := RouteListFiltered(FAMILY_V4, &Route{ routes, err := RouteListFiltered(FAMILY_V4, &Route{
Dst: dst, Dst: dst,
Src: src, Src: src,
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Table: syscall.RT_TABLE_UNSPEC, Table: unix.RT_TABLE_UNSPEC,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
Tos: 14, Tos: 14,
}, RT_FILTER_DST|RT_FILTER_SRC|RT_FILTER_SCOPE|RT_FILTER_TABLE|RT_FILTER_TYPE|RT_FILTER_TOS) }, RT_FILTER_DST|RT_FILTER_SRC|RT_FILTER_SCOPE|RT_FILTER_TABLE|RT_FILTER_TYPE|RT_FILTER_TOS)
if err != nil { if err != nil {
@@ -370,7 +370,7 @@ func TestRouteFilterAllTables(t *testing.T) {
} }
for _, route := range routes { for _, route := range routes {
if route.Scope != syscall.RT_SCOPE_LINK { if route.Scope != unix.RT_SCOPE_LINK {
t.Fatal("Invalid Scope. Route not added properly") t.Fatal("Invalid Scope. Route not added properly")
} }
if route.Priority != 13 { if route.Priority != 13 {
@@ -379,7 +379,7 @@ func TestRouteFilterAllTables(t *testing.T) {
if !tableIDIn(tables, route.Table) { if !tableIDIn(tables, route.Table) {
t.Fatalf("Invalid Table %d. Route not added properly", route.Table) t.Fatalf("Invalid Table %d. Route not added properly", route.Table)
} }
if route.Type != syscall.RTN_UNICAST { if route.Type != unix.RTN_UNICAST {
t.Fatal("Invalid Type. Route not added properly") t.Fatal("Invalid Type. Route not added properly")
} }
if route.Tos != 14 { if route.Tos != 14 {
@@ -422,10 +422,10 @@ func TestRouteExtraFields(t *testing.T) {
LinkIndex: link.Attrs().Index, LinkIndex: link.Attrs().Index,
Dst: dst, Dst: dst,
Src: src, Src: src,
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Priority: 13, Priority: 13,
Table: syscall.RT_TABLE_MAIN, Table: unix.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
Tos: 14, Tos: 14,
} }
if err := RouteAdd(&route); err != nil { if err := RouteAdd(&route); err != nil {
@@ -434,9 +434,9 @@ func TestRouteExtraFields(t *testing.T) {
routes, err := RouteListFiltered(FAMILY_V4, &Route{ routes, err := RouteListFiltered(FAMILY_V4, &Route{
Dst: dst, Dst: dst,
Src: src, Src: src,
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Table: syscall.RT_TABLE_MAIN, Table: unix.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
Tos: 14, Tos: 14,
}, RT_FILTER_DST|RT_FILTER_SRC|RT_FILTER_SCOPE|RT_FILTER_TABLE|RT_FILTER_TYPE|RT_FILTER_TOS) }, RT_FILTER_DST|RT_FILTER_SRC|RT_FILTER_SCOPE|RT_FILTER_TABLE|RT_FILTER_TYPE|RT_FILTER_TOS)
if err != nil { if err != nil {
@@ -446,16 +446,16 @@ func TestRouteExtraFields(t *testing.T) {
t.Fatal("Route not added properly") t.Fatal("Route not added properly")
} }
if routes[0].Scope != syscall.RT_SCOPE_LINK { if routes[0].Scope != unix.RT_SCOPE_LINK {
t.Fatal("Invalid Scope. Route not added properly") t.Fatal("Invalid Scope. Route not added properly")
} }
if routes[0].Priority != 13 { if routes[0].Priority != 13 {
t.Fatal("Invalid Priority. Route not added properly") t.Fatal("Invalid Priority. Route not added properly")
} }
if routes[0].Table != syscall.RT_TABLE_MAIN { if routes[0].Table != unix.RT_TABLE_MAIN {
t.Fatal("Invalid Scope. Route not added properly") t.Fatal("Invalid Scope. Route not added properly")
} }
if routes[0].Type != syscall.RTN_UNICAST { if routes[0].Type != unix.RTN_UNICAST {
t.Fatal("Invalid Type. Route not added properly") t.Fatal("Invalid Type. Route not added properly")
} }
if routes[0].Tos != 14 { if routes[0].Tos != 14 {
@@ -693,7 +693,7 @@ func TestRouteEqual(t *testing.T) {
}, },
Route{ Route{
LinkIndex: 10, LinkIndex: 10,
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Dst: &net.IPNet{ Dst: &net.IPNet{
IP: net.IPv4(192, 168, 0, 0), IP: net.IPv4(192, 168, 0, 0),
Mask: net.CIDRMask(24, 32), Mask: net.CIDRMask(24, 32),
@@ -707,10 +707,10 @@ func TestRouteEqual(t *testing.T) {
Mask: net.CIDRMask(32, 32), Mask: net.CIDRMask(32, 32),
}, },
Src: net.IPv4(127, 3, 3, 3), Src: net.IPv4(127, 3, 3, 3),
Scope: syscall.RT_SCOPE_LINK, Scope: unix.RT_SCOPE_LINK,
Priority: 13, Priority: 13,
Table: syscall.RT_TABLE_MAIN, Table: unix.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST, Type: unix.RTN_UNICAST,
Tos: 14, Tos: 14,
}, },
Route{ Route{

View File

@@ -3,9 +3,9 @@ package netlink
import ( import (
"fmt" "fmt"
"net" "net"
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
// RuleAdd adds a rule to the system. // RuleAdd adds a rule to the system.
@@ -17,7 +17,7 @@ func RuleAdd(rule *Rule) error {
// RuleAdd adds a rule to the system. // RuleAdd adds a rule to the system.
// Equivalent to: ip rule add // Equivalent to: ip rule add
func (h *Handle) RuleAdd(rule *Rule) error { func (h *Handle) RuleAdd(rule *Rule) error {
req := h.newNetlinkRequest(syscall.RTM_NEWRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_NEWRULE, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
return ruleHandle(rule, req) return ruleHandle(rule, req)
} }
@@ -30,13 +30,13 @@ func RuleDel(rule *Rule) error {
// RuleDel deletes a rule from the system. // RuleDel deletes a rule from the system.
// Equivalent to: ip rule del // Equivalent to: ip rule del
func (h *Handle) RuleDel(rule *Rule) error { func (h *Handle) RuleDel(rule *Rule) error {
req := h.newNetlinkRequest(syscall.RTM_DELRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(unix.RTM_DELRULE, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
return ruleHandle(rule, req) return ruleHandle(rule, req)
} }
func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error { func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
msg := nl.NewRtMsg() msg := nl.NewRtMsg()
msg.Family = syscall.AF_INET msg.Family = unix.AF_INET
if rule.Family != 0 { if rule.Family != 0 {
msg.Family = uint8(rule.Family) msg.Family = uint8(rule.Family)
} }
@@ -49,12 +49,12 @@ func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
msg.Family = uint8(nl.GetIPFamily(rule.Dst.IP)) msg.Family = uint8(nl.GetIPFamily(rule.Dst.IP))
dstFamily = msg.Family dstFamily = msg.Family
var dstData []byte var dstData []byte
if msg.Family == syscall.AF_INET { if msg.Family == unix.AF_INET {
dstData = rule.Dst.IP.To4() dstData = rule.Dst.IP.To4()
} else { } else {
dstData = rule.Dst.IP.To16() dstData = rule.Dst.IP.To16()
} }
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, dstData))
} }
if rule.Src != nil && rule.Src.IP != nil { if rule.Src != nil && rule.Src.IP != nil {
@@ -65,18 +65,18 @@ func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
srcLen, _ := rule.Src.Mask.Size() srcLen, _ := rule.Src.Mask.Size()
msg.Src_len = uint8(srcLen) msg.Src_len = uint8(srcLen)
var srcData []byte var srcData []byte
if msg.Family == syscall.AF_INET { if msg.Family == unix.AF_INET {
srcData = rule.Src.IP.To4() srcData = rule.Src.IP.To4()
} else { } else {
srcData = rule.Src.IP.To16() srcData = rule.Src.IP.To16()
} }
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_SRC, srcData)) rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_SRC, srcData))
} }
if rule.Table >= 0 { if rule.Table >= 0 {
msg.Table = uint8(rule.Table) msg.Table = uint8(rule.Table)
if rule.Table >= 256 { if rule.Table >= 256 {
msg.Table = syscall.RT_TABLE_UNSPEC msg.Table = unix.RT_TABLE_UNSPEC
} }
} }
@@ -142,7 +142,7 @@ func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b)) req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b))
} }
_, err := req.Execute(syscall.NETLINK_ROUTE, 0) _, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err return err
} }
@@ -155,11 +155,11 @@ func RuleList(family int) ([]Rule, error) {
// RuleList lists rules in the system. // RuleList lists rules in the system.
// Equivalent to: ip rule list // Equivalent to: ip rule list
func (h *Handle) RuleList(family int) ([]Rule, error) { func (h *Handle) RuleList(family int) ([]Rule, error) {
req := h.newNetlinkRequest(syscall.RTM_GETRULE, syscall.NLM_F_DUMP|syscall.NLM_F_REQUEST) req := h.newNetlinkRequest(unix.RTM_GETRULE, unix.NLM_F_DUMP|unix.NLM_F_REQUEST)
msg := nl.NewIfInfomsg(family) msg := nl.NewIfInfomsg(family)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWRULE) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWRULE)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -177,7 +177,7 @@ func (h *Handle) RuleList(family int) ([]Rule, error) {
for j := range attrs { for j := range attrs {
switch attrs[j].Attr.Type { switch attrs[j].Attr.Type {
case syscall.RTA_TABLE: case unix.RTA_TABLE:
rule.Table = int(native.Uint32(attrs[j].Value[0:4])) rule.Table = int(native.Uint32(attrs[j].Value[0:4]))
case nl.FRA_SRC: case nl.FRA_SRC:
rule.Src = &net.IPNet{ rule.Src = &net.IPNet{

View File

@@ -4,8 +4,9 @@ package netlink
import ( import (
"net" "net"
"syscall"
"testing" "testing"
"golang.org/x/sys/unix"
) )
func TestRuleAddDel(t *testing.T) { func TestRuleAddDel(t *testing.T) {
@@ -14,13 +15,13 @@ func TestRuleAddDel(t *testing.T) {
srcNet := &net.IPNet{IP: net.IPv4(172, 16, 0, 1), Mask: net.CIDRMask(16, 32)} srcNet := &net.IPNet{IP: net.IPv4(172, 16, 0, 1), Mask: net.CIDRMask(16, 32)}
dstNet := &net.IPNet{IP: net.IPv4(172, 16, 1, 1), Mask: net.CIDRMask(24, 32)} dstNet := &net.IPNet{IP: net.IPv4(172, 16, 1, 1), Mask: net.CIDRMask(24, 32)}
rulesBegin, err := RuleList(syscall.AF_INET) rulesBegin, err := RuleList(unix.AF_INET)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
rule := NewRule() rule := NewRule()
rule.Table = syscall.RT_TABLE_MAIN rule.Table = unix.RT_TABLE_MAIN
rule.Src = srcNet rule.Src = srcNet
rule.Dst = dstNet rule.Dst = dstNet
rule.Priority = 5 rule.Priority = 5
@@ -30,7 +31,7 @@ func TestRuleAddDel(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
rules, err := RuleList(syscall.AF_INET) rules, err := RuleList(unix.AF_INET)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -59,7 +60,7 @@ func TestRuleAddDel(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
rulesEnd, err := RuleList(syscall.AF_INET) rulesEnd, err := RuleList(unix.AF_INET)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -4,9 +4,9 @@ import (
"errors" "errors"
"fmt" "fmt"
"net" "net"
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
const ( const (
@@ -123,15 +123,15 @@ func SocketGet(local, remote net.Addr) (*Socket, error) {
return nil, ErrNotImplemented return nil, ErrNotImplemented
} }
s, err := nl.Subscribe(syscall.NETLINK_INET_DIAG) s, err := nl.Subscribe(unix.NETLINK_INET_DIAG)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer s.Close() defer s.Close()
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, 0) req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, 0)
req.AddData(&socketRequest{ req.AddData(&socketRequest{
Family: syscall.AF_INET, Family: unix.AF_INET,
Protocol: syscall.IPPROTO_TCP, Protocol: unix.IPPROTO_TCP,
ID: SocketID{ ID: SocketID{
SourcePort: uint16(localTCP.Port), SourcePort: uint16(localTCP.Port),
DestinationPort: uint16(remoteTCP.Port), DestinationPort: uint16(remoteTCP.Port),

13
xfrm.go
View File

@@ -2,19 +2,20 @@ package netlink
import ( import (
"fmt" "fmt"
"syscall"
"golang.org/x/sys/unix"
) )
// Proto is an enum representing an ipsec protocol. // Proto is an enum representing an ipsec protocol.
type Proto uint8 type Proto uint8
const ( const (
XFRM_PROTO_ROUTE2 Proto = syscall.IPPROTO_ROUTING XFRM_PROTO_ROUTE2 Proto = unix.IPPROTO_ROUTING
XFRM_PROTO_ESP Proto = syscall.IPPROTO_ESP XFRM_PROTO_ESP Proto = unix.IPPROTO_ESP
XFRM_PROTO_AH Proto = syscall.IPPROTO_AH XFRM_PROTO_AH Proto = unix.IPPROTO_AH
XFRM_PROTO_HAO Proto = syscall.IPPROTO_DSTOPTS XFRM_PROTO_HAO Proto = unix.IPPROTO_DSTOPTS
XFRM_PROTO_COMP Proto = 0x6c // NOTE not defined on darwin XFRM_PROTO_COMP Proto = 0x6c // NOTE not defined on darwin
XFRM_PROTO_IPSEC_ANY Proto = syscall.IPPROTO_RAW XFRM_PROTO_IPSEC_ANY Proto = unix.IPPROTO_RAW
) )
func (p Proto) String() string { func (p Proto) String() string {

View File

@@ -2,11 +2,10 @@ package netlink
import ( import (
"fmt" "fmt"
"syscall"
"github.com/vishvananda/netns"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
"golang.org/x/sys/unix"
) )
type XfrmMsg interface { type XfrmMsg interface {
@@ -39,7 +38,7 @@ func XfrmMonitor(ch chan<- XfrmMsg, done <-chan struct{}, errorChan chan<- error
if err != nil { if err != nil {
return nil return nil
} }
s, err := nl.SubscribeAt(netns.None(), netns.None(), syscall.NETLINK_XFRM, groups...) s, err := nl.SubscribeAt(netns.None(), netns.None(), unix.NETLINK_XFRM, groups...)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -1,9 +1,8 @@
package netlink package netlink
import ( import (
"syscall"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) { func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) {
@@ -55,7 +54,7 @@ func (h *Handle) XfrmPolicyUpdate(policy *XfrmPolicy) error {
} }
func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error { func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error {
req := h.newNetlinkRequest(nlProto, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(nlProto, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
msg := &nl.XfrmUserpolicyInfo{} msg := &nl.XfrmUserpolicyInfo{}
selFromPolicy(&msg.Sel, policy) selFromPolicy(&msg.Sel, policy)
@@ -91,7 +90,7 @@ func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error {
req.AddData(out) req.AddData(out)
} }
_, err := req.Execute(syscall.NETLINK_XFRM, 0) _, err := req.Execute(unix.NETLINK_XFRM, 0)
return err return err
} }
@@ -121,12 +120,12 @@ func XfrmPolicyList(family int) ([]XfrmPolicy, error) {
// Equivalent to: `ip xfrm policy show`. // Equivalent to: `ip xfrm policy show`.
// The list can be filtered by ip family. // The list can be filtered by ip family.
func (h *Handle) XfrmPolicyList(family int) ([]XfrmPolicy, error) { func (h *Handle) XfrmPolicyList(family int) ([]XfrmPolicy, error) {
req := h.newNetlinkRequest(nl.XFRM_MSG_GETPOLICY, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(nl.XFRM_MSG_GETPOLICY, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(family) msg := nl.NewIfInfomsg(family)
req.AddData(msg) req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY) msgs, err := req.Execute(unix.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -165,13 +164,13 @@ func XfrmPolicyFlush() error {
// XfrmPolicyFlush will flush the policies on the system. // XfrmPolicyFlush will flush the policies on the system.
// Equivalent to: `ip xfrm policy flush` // Equivalent to: `ip xfrm policy flush`
func (h *Handle) XfrmPolicyFlush() error { func (h *Handle) XfrmPolicyFlush() error {
req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHPOLICY, syscall.NLM_F_ACK) req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHPOLICY, unix.NLM_F_ACK)
_, err := req.Execute(syscall.NETLINK_XFRM, 0) _, err := req.Execute(unix.NETLINK_XFRM, 0)
return err return err
} }
func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPolicy, error) { func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPolicy, error) {
req := h.newNetlinkRequest(nlProto, syscall.NLM_F_ACK) req := h.newNetlinkRequest(nlProto, unix.NLM_F_ACK)
msg := &nl.XfrmUserpolicyId{} msg := &nl.XfrmUserpolicyId{}
selFromPolicy(&msg.Sel, policy) selFromPolicy(&msg.Sel, policy)
@@ -189,7 +188,7 @@ func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPo
resType = 0 resType = 0
} }
msgs, err := req.Execute(syscall.NETLINK_XFRM, uint16(resType)) msgs, err := req.Execute(unix.NETLINK_XFRM, uint16(resType))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -2,10 +2,10 @@ package netlink
import ( import (
"fmt" "fmt"
"syscall"
"unsafe" "unsafe"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
) )
func writeStateAlgo(a *XfrmStateAlgo) []byte { func writeStateAlgo(a *XfrmStateAlgo) []byte {
@@ -111,7 +111,7 @@ func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
if state.Spi == 0 { if state.Spi == 0 {
return fmt.Errorf("Spi must be set when adding xfrm state.") return fmt.Errorf("Spi must be set when adding xfrm state.")
} }
req := h.newNetlinkRequest(nlProto, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) req := h.newNetlinkRequest(nlProto, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
msg := xfrmUsersaInfoFromXfrmState(state) msg := xfrmUsersaInfoFromXfrmState(state)
@@ -157,13 +157,13 @@ func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
req.AddData(out) req.AddData(out)
} }
_, err := req.Execute(syscall.NETLINK_XFRM, 0) _, err := req.Execute(unix.NETLINK_XFRM, 0)
return err return err
} }
func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) { func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI, req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI,
syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
msg := &nl.XfrmUserSpiInfo{} msg := &nl.XfrmUserSpiInfo{}
msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state)) msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state))
@@ -177,7 +177,7 @@ func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
req.AddData(out) req.AddData(out)
} }
msgs, err := req.Execute(syscall.NETLINK_XFRM, 0) msgs, err := req.Execute(unix.NETLINK_XFRM, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -216,9 +216,9 @@ func XfrmStateList(family int) ([]XfrmState, error) {
// Equivalent to: `ip xfrm state show`. // Equivalent to: `ip xfrm state show`.
// The list can be filtered by ip family. // The list can be filtered by ip family.
func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) { func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) {
req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, syscall.NLM_F_DUMP) req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, unix.NLM_F_DUMP)
msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWSA) msgs, err := req.Execute(unix.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -255,7 +255,7 @@ func (h *Handle) XfrmStateGet(state *XfrmState) (*XfrmState, error) {
} }
func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) { func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) {
req := h.newNetlinkRequest(nlProto, syscall.NLM_F_ACK) req := h.newNetlinkRequest(nlProto, unix.NLM_F_ACK)
msg := &nl.XfrmUsersaId{} msg := &nl.XfrmUsersaId{}
msg.Family = uint16(nl.GetIPFamily(state.Dst)) msg.Family = uint16(nl.GetIPFamily(state.Dst))
@@ -278,7 +278,7 @@ func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState
resType = 0 resType = 0
} }
msgs, err := req.Execute(syscall.NETLINK_XFRM, uint16(resType)) msgs, err := req.Execute(unix.NETLINK_XFRM, uint16(resType))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -386,11 +386,11 @@ func XfrmStateFlush(proto Proto) error {
// proto = 0 means any transformation protocols // proto = 0 means any transformation protocols
// Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]` // Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
func (h *Handle) XfrmStateFlush(proto Proto) error { func (h *Handle) XfrmStateFlush(proto Proto) error {
req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, syscall.NLM_F_ACK) req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, unix.NLM_F_ACK)
req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)}) req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)})
_, err := req.Execute(syscall.NETLINK_XFRM, 0) _, err := req.Execute(unix.NETLINK_XFRM, 0)
if err != nil { if err != nil {
return err return err
} }