diff --git a/Makefile b/Makefile index d3bb980..ca52afc 100644 --- a/Makefile +++ b/Makefile @@ -238,3 +238,4 @@ mockgen: GOOS=linux mockgen -source=internal/netutil/tcp_sniffer_helper_linux.go -package=mocks -destination=internal/netutil/internal/mocks/dependent_functions_mock.go mockgen -source=internal/metadata/updater/updater.go -package=updater -destination=internal/metadata/updater/updater_mocks.go mockgen -destination=internal/metadata/updater/readcloser_mocks.go -package=updater -build_flags=--mod=mod io ReadCloser + mockgen -typed -source=internal/reservedipv6/reserved_ipv6.go -package=reservedipv6 -destination=internal/reservedipv6/mocks.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 2d4f95a..15e1e66 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -12,12 +12,15 @@ import ( "syscall" "time" + "github.com/jsimonetti/rtnetlink/v2" + "github.com/digitalocean/droplet-agent/internal/config" "github.com/digitalocean/droplet-agent/internal/log" "github.com/digitalocean/droplet-agent/internal/metadata" "github.com/digitalocean/droplet-agent/internal/metadata/actioner" "github.com/digitalocean/droplet-agent/internal/metadata/updater" "github.com/digitalocean/droplet-agent/internal/metadata/watcher" + "github.com/digitalocean/droplet-agent/internal/reservedipv6" "github.com/digitalocean/droplet-agent/internal/sysaccess" ) @@ -51,19 +54,36 @@ func main() { log.Fatal("failed to initialize SSHManager: %v", err) } - doManagedKeysActioner := actioner.NewDOManagedKeysActioner(sshMgr) + // create the watcher metadataWatcher := newMetadataWatcher(&watcher.Conf{SSHPort: sshMgr.SSHDPort()}) - metadataWatcher.RegisterActioner(doManagedKeysActioner) - infoUpdater := updater.NewAgentInfoUpdater() - // monitor sshd_config + // ssh managed keys + doManagedKeysActioner := actioner.NewDOManagedKeysActioner(sshMgr) + metadataWatcher.RegisterActioner(doManagedKeysActioner) go mustMonitorSSHDConfig(sshMgr) - - // Launch background jobs bgJobsCtx, bgJobsCancel := context.WithCancel(context.Background()) go bgJobsRemoveExpiredDOTTYKeys(bgJobsCtx, sshMgr, cfg.AuthorizedKeysCheckInterval) + // reserved ipv6 + if cfg.ManageReservedIPv6 { + log.Info("Reserved IPv6 management enabled") + conn, err := rtnetlink.Dial(nil) + if err != nil { + log.Fatal("failed to create netlink client: %v", err) + } + defer conn.Close() + + rip6Manager, err := reservedipv6.NewManager(conn) + if err != nil { + log.Fatal("Failed to create Reserved IPv6 manager: %v", err) + } + + rip6Actioner := actioner.NewReservedIPv6Actioner(rip6Manager) + metadataWatcher.RegisterActioner(rip6Actioner) + } + // handle shutdown + infoUpdater := updater.NewAgentInfoUpdater() go handleShutdown(bgJobsCancel, metadataWatcher, infoUpdater, sshMgr) // report agent status and ssh info diff --git a/go.mod b/go.mod index 73c5211..507bc71 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,8 @@ go 1.22 require ( github.com/fsnotify/fsnotify v1.7.0 + github.com/jsimonetti/rtnetlink/v2 v2.0.2 + github.com/mdlayher/netlink v1.7.2 github.com/opencontainers/selinux v1.11.0 github.com/peterbourgon/ff/v3 v3.4.0 go.uber.org/mock v0.4.0 @@ -13,3 +15,9 @@ require ( golang.org/x/sys v0.26.0 golang.org/x/time v0.7.0 ) + +require ( + github.com/google/go-cmp v0.6.0 // indirect + github.com/josharian/native v1.1.0 // indirect + github.com/mdlayher/socket v0.4.1 // indirect +) diff --git a/go.sum b/go.sum index 893fb75..c876dc8 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,17 @@ +github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4= +github.com/cilium/ebpf v0.12.3/go.mod h1:TctK1ivibvI3znr66ljgi4hqOT8EYQjz1KWBfb1UVgM= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA= +github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= +github.com/jsimonetti/rtnetlink/v2 v2.0.2 h1:ZKlbCujrIpp4/u3V2Ka0oxlf4BCkt6ojkvpy3nZoCBY= +github.com/jsimonetti/rtnetlink/v2 v2.0.2/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsTKP1pqKLUTVCvToE= +github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g= +github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw= +github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U= +github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA= github.com/opencontainers/selinux v1.11.0 h1:+5Zbo97w3Lbmb3PeqQtpmTkMwsW5nRI3YaLpt7tQ7oU= github.com/opencontainers/selinux v1.11.0/go.mod h1:E5dMC3VPuVvVHDYmi78qvhJp8+M586T4DlDRYpFkyec= github.com/peterbourgon/ff/v3 v3.4.0 h1:QBvM/rizZM1cB0p0lGMdmR7HxZeI/ZrBWB4DqLkMUBc= @@ -8,6 +20,8 @@ go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= +golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 h1:Jvc7gsqn21cJHCmAWx0LiimpP18LZmUxkT5Mp7EZ1mI= +golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= diff --git a/internal/config/config.go b/internal/config/config.go index c1114a7..e6974cb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -28,6 +28,8 @@ type Conf struct { CustomSSHDPort int CustomSSHDCfgFile string AuthorizedKeysCheckInterval time.Duration + + ManageReservedIPv6 bool } // Init initializes the agent's configuration @@ -40,9 +42,12 @@ func Init() *Conf { fs.BoolVar(&cfg.UseSyslog, "syslog", false, "Use syslog service for logging") fs.BoolVar(&cfg.DebugMode, "debug", false, "Turn on debug mode") + fs.IntVar(&cfg.CustomSSHDPort, "sshd_port", 0, "The port sshd is binding to") fs.StringVar(&cfg.CustomSSHDCfgFile, "sshd_config", "", "The location of sshd_config") + fs.BoolVar(&cfg.ManageReservedIPv6, "reserved_ipv6", false, "enable reserved IPv6 assignment/unassignment feature") + ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix("DROPLET_AGENT"), ) diff --git a/internal/config/version.go b/internal/config/version.go index 2c33f70..83232bb 100644 --- a/internal/config/version.go +++ b/internal/config/version.go @@ -3,4 +3,4 @@ package config // Version is the current package version. -const Version = "v1.2.9" +const Version = "v1.3.0" diff --git a/internal/metadata/actioner/reserved_ipv6_actioner.go b/internal/metadata/actioner/reserved_ipv6_actioner.go new file mode 100644 index 0000000..123b217 --- /dev/null +++ b/internal/metadata/actioner/reserved_ipv6_actioner.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 + +package actioner + +import ( + "sync/atomic" + + "github.com/digitalocean/droplet-agent/internal/log" + "github.com/digitalocean/droplet-agent/internal/metadata" + "github.com/digitalocean/droplet-agent/internal/reservedipv6" +) + +const ( + logPrefix string = "[Reserved IPv6 Actioner]" +) + +// NewReservedIPv6Actioner returns a new DigitalOcean Reserved IPv6 actioner +func NewReservedIPv6Actioner(mgr reservedipv6.Manager) MetadataActioner { + return &reservedIPv6Actioner{ + mgr: mgr, + activeActions: &atomic.Uint32{}, + closing: &atomic.Bool{}, + allDone: make(chan struct{}, 1), + } +} + +type reservedIPv6Actioner struct { + mgr reservedipv6.Manager + activeActions *atomic.Uint32 + closing *atomic.Bool + allDone chan struct{} +} + +func (da *reservedIPv6Actioner) Do(md *metadata.Metadata) { + da.activeActions.Add(1) + defer func() { + // decrement active counter, then check shutdown state + ret := da.activeActions.Add(^uint32(0)) + if ret == 0 && da.closing.Load() { + close(da.allDone) + } + }() + + ipv6 := md.ReservedIP.IPv6 + + if ipv6.Active { + logDebug("Attempting to assign Reserved IPv6 address '%s'", ipv6.IPAddress) + if err := da.mgr.Assign(ipv6.IPAddress); err != nil { + logError("failed to assign Reserved IPv6 address '%s': %v", ipv6.IPAddress, err) + return + } + logInfo("Assigned Reserved IPv6 address '%s'", ipv6.IPAddress) + } else { + logDebug("Attempting to unassign all Reserved IPv6 addresses") + if err := da.mgr.Unassign(); err != nil { + logError("failed to unassign all Reserved IPv6 addresses: %v", err) + return + } + logInfo("Unassigned all Reserved IPv6 addresses") + } +} + +func (da *reservedIPv6Actioner) Shutdown() { + logInfo("Shutting down") + da.closing.Store(true) + + // if there are still jobs in progress, wait for them to finish + if da.activeActions.Load() > 0 { + logDebug("Waiting for jobs in progress") + <-da.allDone + } + logInfo("Bye-bye") +} + +// logInfo wraps log.Info with rip6LogPrefix +func logInfo(format string, params ...any) { + msg := logPrefix + " " + format + log.Info(msg, params) +} + +// logDebug wraps log.Debug with rip6LogPrefix +func logDebug(format string, params ...any) { + msg := logPrefix + " " + format + log.Debug(msg, params) +} + +// logError wraps log.Error with rip6LogPrefix +func logError(format string, params ...any) { + msg := logPrefix + " " + format + log.Error(msg, params) +} diff --git a/internal/metadata/actioner/reserved_ipv6_actioner_test.go b/internal/metadata/actioner/reserved_ipv6_actioner_test.go new file mode 100644 index 0000000..e627269 --- /dev/null +++ b/internal/metadata/actioner/reserved_ipv6_actioner_test.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 + +package actioner + +import ( + "testing" + + "github.com/digitalocean/droplet-agent/internal/metadata" + "github.com/digitalocean/droplet-agent/internal/reservedipv6" + "go.uber.org/mock/gomock" +) + +func TestReservedIPv6Actioner_Do(t *testing.T) { + t.Run("assign", func(t *testing.T) { + // Arrange + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + rip6Manager := reservedipv6.NewMockManager(ctrl) + actioner := NewReservedIPv6Actioner(rip6Manager) + + rip6Manager.EXPECT().Assign("2001:4860:4860::8888").Return(nil) + + // Act + actioner.Do(&metadata.Metadata{ + ReservedIP: &metadata.ReservedIP{ + IPv6: &metadata.ReservedIPv6{ + Active: true, + IPAddress: "2001:4860:4860::8888", + }, + }, + }) + }) + + t.Run("unassign", func(t *testing.T) { + // Arrange + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + rip6Manager := reservedipv6.NewMockManager(ctrl) + actioner := NewReservedIPv6Actioner(rip6Manager) + + rip6Manager.EXPECT().Unassign().Return(nil) + + // Act + actioner.Do(&metadata.Metadata{ + ReservedIP: &metadata.ReservedIP{ + IPv6: &metadata.ReservedIPv6{ + Active: false, + }, + }, + }) + }) +} diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index e682a3f..91710a2 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -30,6 +30,20 @@ type Metadata struct { DOTTYStatus AgentStatus `json:"dotty_status,omitempty"` SSHInfo *SSHInfo `json:"ssh_info,omitempty"` ManagedKeysEnabled *bool `json:"managed_keys_enabled,omitempty"` + + ReservedIP *ReservedIP `json:"reserved_ip,omitempty"` +} + +// ReservedIP defines the Metadata fields of a Reserved IP. + +type ReservedIP struct { + IPv6 *ReservedIPv6 `json:"ipv6,omitempty"` +} + +// ReservedIP defines the Metadata fields of a Reserved IPv6. +type ReservedIPv6 struct { + IPAddress string `json:"ip_address,omitempty"` + Active bool `json:"active,omitempty"` } // SSHInfo contains the information of the sshd service running on the droplet diff --git a/internal/metadata/updater/updater_test.go b/internal/metadata/updater/updater_test.go index da4dc72..f8cb265 100644 --- a/internal/metadata/updater/updater_test.go +++ b/internal/metadata/updater/updater_test.go @@ -35,7 +35,8 @@ func Test_agentInfoUpdaterImpl_Update(t *testing.T) { ExpectedRequest: newRequest(t, []byte("{\"dotty_status\":\"running\",\"ssh_info\":{\"port\":256}}")), } - client.EXPECT().Do(reqMatcher).Return(&http.Response{StatusCode: 202}, nil) + client.EXPECT().Do(reqMatcher).Return(&http.Response{StatusCode: 202, Body: respBody}, nil) + respBody.EXPECT().Close() }, false, }, diff --git a/internal/metadata/watcher/web_watcher.go b/internal/metadata/watcher/web_watcher.go index 8d5857f..721843f 100644 --- a/internal/metadata/watcher/web_watcher.go +++ b/internal/metadata/watcher/web_watcher.go @@ -9,10 +9,10 @@ import ( "sync" "time" - "github.com/digitalocean/droplet-agent/internal/log" + "golang.org/x/time/rate" + "github.com/digitalocean/droplet-agent/internal/log" "github.com/digitalocean/droplet-agent/internal/metadata/actioner" - "golang.org/x/time/rate" ) type webBasedWatcher struct { diff --git a/internal/reservedipv6/mocks.go b/internal/reservedipv6/mocks.go new file mode 100644 index 0000000..f6410e9 --- /dev/null +++ b/internal/reservedipv6/mocks.go @@ -0,0 +1,114 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/reservedipv6/reserved_ipv6.go +// +// Generated by this command: +// +// mockgen -typed -source=internal/reservedipv6/reserved_ipv6.go -package=reservedipv6 -destination=internal/reservedipv6/mocks.go +// +// Package reservedipv6 is a generated GoMock package. +package reservedipv6 + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockManager is a mock of Manager interface. +type MockManager struct { + ctrl *gomock.Controller + recorder *MockManagerMockRecorder +} + +// MockManagerMockRecorder is the mock recorder for MockManager. +type MockManagerMockRecorder struct { + mock *MockManager +} + +// NewMockManager creates a new mock instance. +func NewMockManager(ctrl *gomock.Controller) *MockManager { + mock := &MockManager{ctrl: ctrl} + mock.recorder = &MockManagerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockManager) EXPECT() *MockManagerMockRecorder { + return m.recorder +} + +// Assign mocks base method. +func (m *MockManager) Assign(ip string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Assign", ip) + ret0, _ := ret[0].(error) + return ret0 +} + +// Assign indicates an expected call of Assign. +func (mr *MockManagerMockRecorder) Assign(ip any) *ManagerAssignCall { + mr.mock.ctrl.T.Helper() + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Assign", reflect.TypeOf((*MockManager)(nil).Assign), ip) + return &ManagerAssignCall{Call: call} +} + +// ManagerAssignCall wrap *gomock.Call +type ManagerAssignCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *ManagerAssignCall) Return(arg0 error) *ManagerAssignCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *ManagerAssignCall) Do(f func(string) error) *ManagerAssignCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *ManagerAssignCall) DoAndReturn(f func(string) error) *ManagerAssignCall { + c.Call = c.Call.DoAndReturn(f) + return c +} + +// Unassign mocks base method. +func (m *MockManager) Unassign() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Unassign") + ret0, _ := ret[0].(error) + return ret0 +} + +// Unassign indicates an expected call of Unassign. +func (mr *MockManagerMockRecorder) Unassign() *ManagerUnassignCall { + mr.mock.ctrl.T.Helper() + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unassign", reflect.TypeOf((*MockManager)(nil).Unassign)) + return &ManagerUnassignCall{Call: call} +} + +// ManagerUnassignCall wrap *gomock.Call +type ManagerUnassignCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *ManagerUnassignCall) Return(arg0 error) *ManagerUnassignCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *ManagerUnassignCall) Do(f func() error) *ManagerUnassignCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *ManagerUnassignCall) DoAndReturn(f func() error) *ManagerUnassignCall { + c.Call = c.Call.DoAndReturn(f) + return c +} diff --git a/internal/reservedipv6/reserved_ipv6.go b/internal/reservedipv6/reserved_ipv6.go new file mode 100644 index 0000000..5ae986b --- /dev/null +++ b/internal/reservedipv6/reserved_ipv6.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 + +package reservedipv6 + +import ( + "fmt" + "net" + "net/netip" + + "github.com/jsimonetti/rtnetlink/v2" + "github.com/mdlayher/netlink" + "golang.org/x/sys/unix" +) + +const ( + loIface string = "lo" + eth0Iface string = "eth0" + prefixLen uint8 = 128 +) + +type Manager interface { + Assign(ip string) error + Unassign() error +} + +type mgr struct { + nlConn *rtnetlink.Conn + loIdx uint32 + eth0Idx uint32 +} + +func NewManager(netlink *rtnetlink.Conn) (Manager, error) { + lo, err := net.InterfaceByName(loIface) + if err != nil { + return nil, fmt.Errorf("failed to determine index for interface '%s': %w", loIface, err) + } + + eth0, err := net.InterfaceByName(eth0Iface) + if err != nil { + return nil, fmt.Errorf("failed to determine index for interface '%s': %w", eth0Iface, err) + } + + return &mgr{ + nlConn: netlink, + loIdx: uint32(lo.Index), + eth0Idx: uint32(eth0.Index), + }, nil +} + +// Assign creates a new global-scoped IPv6 address on +func (m *mgr) Assign(ip string) error { + addr, err := netip.ParseAddr(ip) + if err != nil { + return fmt.Errorf("invalid IP: %w", err) + } + if addr.Is4() || addr.Is4In6() { + return fmt.Errorf("IP must be an IPv6 address") + } + + // Equivalent to `ip -6 addr replace "${ip}/128" dev lo scope global` + req := reservedIPv6Addr(m.loIdx, addr) + flags := netlink.Request | netlink.Replace | netlink.Acknowledge + if _, err := m.nlConn.Execute(req, unix.RTM_NEWADDR, flags); err != nil { + return fmt.Errorf("failed to assign address: %w", err) + } + + if err := m.nlConn.Route.Replace(defaultIPv6Route(m.eth0Idx)); err != nil { + return fmt.Errorf("failed to replace default IPv6 route on eth0: %w", err) + } + + return nil +} + +// Unassign removes all global-scoped IPv6 addresses on localhost +func (m *mgr) Unassign() error { + addrs, err := m.nlConn.Address.List() + if err != nil { + return fmt.Errorf("failed to list addreses: %w", err) + } + + for _, a := range addrs { + if a.Index == m.loIdx && a.Family == unix.AF_INET6 && a.Scope == unix.RT_SCOPE_UNIVERSE { + if err := m.nlConn.Address.Delete(&a); err != nil { + return fmt.Errorf("failed to delete address '%s' from interface '%s': %w", a.Attributes.Address, loIface, err) + } + } + } + + // remove the default route if it existed + route := defaultIPv6Route(m.eth0Idx) + if _, err := m.nlConn.Route.Get(route); err == nil { + if err := m.nlConn.Route.Delete(route); err != nil { + return fmt.Errorf("failed to remove default IPv6 route on %s: %w", eth0Iface, err) + } + } + + return nil +} + +func reservedIPv6Addr(intfIdx uint32, addr netip.Addr) *rtnetlink.AddressMessage { + return &rtnetlink.AddressMessage{ + Family: unix.AF_INET6, + PrefixLength: prefixLen, + Scope: unix.RT_SCOPE_UNIVERSE, // global + Index: intfIdx, + Attributes: &rtnetlink.AddressAttributes{ + Address: net.IP(addr.AsSlice()), + }, + } +} + +// defaultIPv6Route returns a route equivalent to `ip -6 route replace default dev eth0` +func defaultIPv6Route(intfIdx uint32) *rtnetlink.RouteMessage { + return &rtnetlink.RouteMessage{ + Family: unix.AF_INET6, + Table: unix.RT_TABLE_MAIN, + Protocol: unix.RTPROT_BOOT, + Type: unix.RTN_UNICAST, + Scope: unix.RT_SCOPE_UNIVERSE, + DstLength: 0, // default route + Attributes: rtnetlink.RouteAttributes{ + Dst: nil, // default route + OutIface: intfIdx, + Priority: 1024, + }, + } +} diff --git a/internal/reservedipv6/reserved_ipv6_test.go b/internal/reservedipv6/reserved_ipv6_test.go new file mode 100644 index 0000000..e41f545 --- /dev/null +++ b/internal/reservedipv6/reserved_ipv6_test.go @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + +package reservedipv6 + +var _ Manager = (*mgr)(nil) diff --git a/vendor/github.com/google/go-cmp/LICENSE b/vendor/github.com/google/go-cmp/LICENSE new file mode 100644 index 0000000..32017f8 --- /dev/null +++ b/vendor/github.com/google/go-cmp/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2017 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/google/go-cmp/cmp/compare.go b/vendor/github.com/google/go-cmp/cmp/compare.go new file mode 100644 index 0000000..0f5b8a4 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/compare.go @@ -0,0 +1,671 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package cmp determines equality of values. +// +// This package is intended to be a more powerful and safer alternative to +// [reflect.DeepEqual] for comparing whether two values are semantically equal. +// It is intended to only be used in tests, as performance is not a goal and +// it may panic if it cannot compare the values. Its propensity towards +// panicking means that its unsuitable for production environments where a +// spurious panic may be fatal. +// +// The primary features of cmp are: +// +// - When the default behavior of equality does not suit the test's needs, +// custom equality functions can override the equality operation. +// For example, an equality function may report floats as equal so long as +// they are within some tolerance of each other. +// +// - Types with an Equal method (e.g., [time.Time.Equal]) may use that method +// to determine equality. This allows package authors to determine +// the equality operation for the types that they define. +// +// - If no custom equality functions are used and no Equal method is defined, +// equality is determined by recursively comparing the primitive kinds on +// both values, much like [reflect.DeepEqual]. Unlike [reflect.DeepEqual], +// unexported fields are not compared by default; they result in panics +// unless suppressed by using an [Ignore] option +// (see [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) +// or explicitly compared using the [Exporter] option. +package cmp + +import ( + "fmt" + "reflect" + "strings" + + "github.com/google/go-cmp/cmp/internal/diff" + "github.com/google/go-cmp/cmp/internal/function" + "github.com/google/go-cmp/cmp/internal/value" +) + +// TODO(≥go1.18): Use any instead of interface{}. + +// Equal reports whether x and y are equal by recursively applying the +// following rules in the given order to x and y and all of their sub-values: +// +// - Let S be the set of all [Ignore], [Transformer], and [Comparer] options that +// remain after applying all path filters, value filters, and type filters. +// If at least one [Ignore] exists in S, then the comparison is ignored. +// If the number of [Transformer] and [Comparer] options in S is non-zero, +// then Equal panics because it is ambiguous which option to use. +// If S contains a single [Transformer], then use that to transform +// the current values and recursively call Equal on the output values. +// If S contains a single [Comparer], then use that to compare the current values. +// Otherwise, evaluation proceeds to the next rule. +// +// - If the values have an Equal method of the form "(T) Equal(T) bool" or +// "(T) Equal(I) bool" where T is assignable to I, then use the result of +// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and +// evaluation proceeds to the next rule. +// +// - Lastly, try to compare x and y based on their basic kinds. +// Simple kinds like booleans, integers, floats, complex numbers, strings, +// and channels are compared using the equivalent of the == operator in Go. +// Functions are only equal if they are both nil, otherwise they are unequal. +// +// Structs are equal if recursively calling Equal on all fields report equal. +// If a struct contains unexported fields, Equal panics unless an [Ignore] option +// (e.g., [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) ignores that field +// or the [Exporter] option explicitly permits comparing the unexported field. +// +// Slices are equal if they are both nil or both non-nil, where recursively +// calling Equal on all non-ignored slice or array elements report equal. +// Empty non-nil slices and nil slices are not equal; to equate empty slices, +// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. +// +// Maps are equal if they are both nil or both non-nil, where recursively +// calling Equal on all non-ignored map entries report equal. +// Map keys are equal according to the == operator. +// To use custom comparisons for map keys, consider using +// [github.com/google/go-cmp/cmp/cmpopts.SortMaps]. +// Empty non-nil maps and nil maps are not equal; to equate empty maps, +// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. +// +// Pointers and interfaces are equal if they are both nil or both non-nil, +// where they have the same underlying concrete type and recursively +// calling Equal on the underlying values reports equal. +// +// Before recursing into a pointer, slice element, or map, the current path +// is checked to detect whether the address has already been visited. +// If there is a cycle, then the pointed at values are considered equal +// only if both addresses were previously visited in the same path step. +func Equal(x, y interface{}, opts ...Option) bool { + s := newState(opts) + s.compareAny(rootStep(x, y)) + return s.result.Equal() +} + +// Diff returns a human-readable report of the differences between two values: +// y - x. It returns an empty string if and only if Equal returns true for the +// same input values and options. +// +// The output is displayed as a literal in pseudo-Go syntax. +// At the start of each line, a "-" prefix indicates an element removed from x, +// a "+" prefix to indicates an element added from y, and the lack of a prefix +// indicates an element common to both x and y. If possible, the output +// uses fmt.Stringer.String or error.Error methods to produce more humanly +// readable outputs. In such cases, the string is prefixed with either an +// 's' or 'e' character, respectively, to indicate that the method was called. +// +// Do not depend on this output being stable. If you need the ability to +// programmatically interpret the difference, consider using a custom Reporter. +func Diff(x, y interface{}, opts ...Option) string { + s := newState(opts) + + // Optimization: If there are no other reporters, we can optimize for the + // common case where the result is equal (and thus no reported difference). + // This avoids the expensive construction of a difference tree. + if len(s.reporters) == 0 { + s.compareAny(rootStep(x, y)) + if s.result.Equal() { + return "" + } + s.result = diff.Result{} // Reset results + } + + r := new(defaultReporter) + s.reporters = append(s.reporters, reporter{r}) + s.compareAny(rootStep(x, y)) + d := r.String() + if (d == "") != s.result.Equal() { + panic("inconsistent difference and equality results") + } + return d +} + +// rootStep constructs the first path step. If x and y have differing types, +// then they are stored within an empty interface type. +func rootStep(x, y interface{}) PathStep { + vx := reflect.ValueOf(x) + vy := reflect.ValueOf(y) + + // If the inputs are different types, auto-wrap them in an empty interface + // so that they have the same parent type. + var t reflect.Type + if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { + t = anyType + if vx.IsValid() { + vvx := reflect.New(t).Elem() + vvx.Set(vx) + vx = vvx + } + if vy.IsValid() { + vvy := reflect.New(t).Elem() + vvy.Set(vy) + vy = vvy + } + } else { + t = vx.Type() + } + + return &pathStep{t, vx, vy} +} + +type state struct { + // These fields represent the "comparison state". + // Calling statelessCompare must not result in observable changes to these. + result diff.Result // The current result of comparison + curPath Path // The current path in the value tree + curPtrs pointerPath // The current set of visited pointers + reporters []reporter // Optional reporters + + // recChecker checks for infinite cycles applying the same set of + // transformers upon the output of itself. + recChecker recChecker + + // dynChecker triggers pseudo-random checks for option correctness. + // It is safe for statelessCompare to mutate this value. + dynChecker dynChecker + + // These fields, once set by processOption, will not change. + exporters []exporter // List of exporters for structs with unexported fields + opts Options // List of all fundamental and filter options +} + +func newState(opts []Option) *state { + // Always ensure a validator option exists to validate the inputs. + s := &state{opts: Options{validator{}}} + s.curPtrs.Init() + s.processOption(Options(opts)) + return s +} + +func (s *state) processOption(opt Option) { + switch opt := opt.(type) { + case nil: + case Options: + for _, o := range opt { + s.processOption(o) + } + case coreOption: + type filtered interface { + isFiltered() bool + } + if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() { + panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt)) + } + s.opts = append(s.opts, opt) + case exporter: + s.exporters = append(s.exporters, opt) + case reporter: + s.reporters = append(s.reporters, opt) + default: + panic(fmt.Sprintf("unknown option %T", opt)) + } +} + +// statelessCompare compares two values and returns the result. +// This function is stateless in that it does not alter the current result, +// or output to any registered reporters. +func (s *state) statelessCompare(step PathStep) diff.Result { + // We do not save and restore curPath and curPtrs because all of the + // compareX methods should properly push and pop from them. + // It is an implementation bug if the contents of the paths differ from + // when calling this function to when returning from it. + + oldResult, oldReporters := s.result, s.reporters + s.result = diff.Result{} // Reset result + s.reporters = nil // Remove reporters to avoid spurious printouts + s.compareAny(step) + res := s.result + s.result, s.reporters = oldResult, oldReporters + return res +} + +func (s *state) compareAny(step PathStep) { + // Update the path stack. + s.curPath.push(step) + defer s.curPath.pop() + for _, r := range s.reporters { + r.PushStep(step) + defer r.PopStep() + } + s.recChecker.Check(s.curPath) + + // Cycle-detection for slice elements (see NOTE in compareSlice). + t := step.Type() + vx, vy := step.Values() + if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() { + px, py := vx.Addr(), vy.Addr() + if eq, visited := s.curPtrs.Push(px, py); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(px, py) + } + + // Rule 1: Check whether an option applies on this node in the value tree. + if s.tryOptions(t, vx, vy) { + return + } + + // Rule 2: Check whether the type has a valid Equal method. + if s.tryMethod(t, vx, vy) { + return + } + + // Rule 3: Compare based on the underlying kind. + switch t.Kind() { + case reflect.Bool: + s.report(vx.Bool() == vy.Bool(), 0) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + s.report(vx.Int() == vy.Int(), 0) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + s.report(vx.Uint() == vy.Uint(), 0) + case reflect.Float32, reflect.Float64: + s.report(vx.Float() == vy.Float(), 0) + case reflect.Complex64, reflect.Complex128: + s.report(vx.Complex() == vy.Complex(), 0) + case reflect.String: + s.report(vx.String() == vy.String(), 0) + case reflect.Chan, reflect.UnsafePointer: + s.report(vx.Pointer() == vy.Pointer(), 0) + case reflect.Func: + s.report(vx.IsNil() && vy.IsNil(), 0) + case reflect.Struct: + s.compareStruct(t, vx, vy) + case reflect.Slice, reflect.Array: + s.compareSlice(t, vx, vy) + case reflect.Map: + s.compareMap(t, vx, vy) + case reflect.Ptr: + s.comparePtr(t, vx, vy) + case reflect.Interface: + s.compareInterface(t, vx, vy) + default: + panic(fmt.Sprintf("%v kind not handled", t.Kind())) + } +} + +func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool { + // Evaluate all filters and apply the remaining options. + if opt := s.opts.filter(s, t, vx, vy); opt != nil { + opt.apply(s, vx, vy) + return true + } + return false +} + +func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool { + // Check if this type even has an Equal method. + m, ok := t.MethodByName("Equal") + if !ok || !function.IsType(m.Type, function.EqualAssignable) { + return false + } + + eq := s.callTTBFunc(m.Func, vx, vy) + s.report(eq, reportByMethod) + return true +} + +func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value { + if !s.dynChecker.Next() { + return f.Call([]reflect.Value{v})[0] + } + + // Run the function twice and ensure that we get the same results back. + // We run in goroutines so that the race detector (if enabled) can detect + // unsafe mutations to the input. + c := make(chan reflect.Value) + go detectRaces(c, f, v) + got := <-c + want := f.Call([]reflect.Value{v})[0] + if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() { + // To avoid false-positives with non-reflexive equality operations, + // we sanity check whether a value is equal to itself. + if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() { + return want + } + panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f))) + } + return want +} + +func (s *state) callTTBFunc(f, x, y reflect.Value) bool { + if !s.dynChecker.Next() { + return f.Call([]reflect.Value{x, y})[0].Bool() + } + + // Swapping the input arguments is sufficient to check that + // f is symmetric and deterministic. + // We run in goroutines so that the race detector (if enabled) can detect + // unsafe mutations to the input. + c := make(chan reflect.Value) + go detectRaces(c, f, y, x) + got := <-c + want := f.Call([]reflect.Value{x, y})[0].Bool() + if !got.IsValid() || got.Bool() != want { + panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f))) + } + return want +} + +func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { + var ret reflect.Value + defer func() { + recover() // Ignore panics, let the other call to f panic instead + c <- ret + }() + ret = f.Call(vs)[0] +} + +func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { + var addr bool + var vax, vay reflect.Value // Addressable versions of vx and vy + + var mayForce, mayForceInit bool + step := StructField{&structField{}} + for i := 0; i < t.NumField(); i++ { + step.typ = t.Field(i).Type + step.vx = vx.Field(i) + step.vy = vy.Field(i) + step.name = t.Field(i).Name + step.idx = i + step.unexported = !isExported(step.name) + if step.unexported { + if step.name == "_" { + continue + } + // Defer checking of unexported fields until later to give an + // Ignore a chance to ignore the field. + if !vax.IsValid() || !vay.IsValid() { + // For retrieveUnexportedField to work, the parent struct must + // be addressable. Create a new copy of the values if + // necessary to make them addressable. + addr = vx.CanAddr() || vy.CanAddr() + vax = makeAddressable(vx) + vay = makeAddressable(vy) + } + if !mayForceInit { + for _, xf := range s.exporters { + mayForce = mayForce || xf(t) + } + mayForceInit = true + } + step.mayForce = mayForce + step.paddr = addr + step.pvx = vax + step.pvy = vay + step.field = t.Field(i) + } + s.compareAny(step) + } +} + +func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) { + isSlice := t.Kind() == reflect.Slice + if isSlice && (vx.IsNil() || vy.IsNil()) { + s.report(vx.IsNil() && vy.IsNil(), 0) + return + } + + // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer + // since slices represents a list of pointers, rather than a single pointer. + // The pointer checking logic must be handled on a per-element basis + // in compareAny. + // + // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting + // pointer P, a length N, and a capacity C. Supposing each slice element has + // a memory size of M, then the slice is equivalent to the list of pointers: + // [P+i*M for i in range(N)] + // + // For example, v[:0] and v[:1] are slices with the same starting pointer, + // but they are clearly different values. Using the slice pointer alone + // violates the assumption that equal pointers implies equal values. + + step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}} + withIndexes := func(ix, iy int) SliceIndex { + if ix >= 0 { + step.vx, step.xkey = vx.Index(ix), ix + } else { + step.vx, step.xkey = reflect.Value{}, -1 + } + if iy >= 0 { + step.vy, step.ykey = vy.Index(iy), iy + } else { + step.vy, step.ykey = reflect.Value{}, -1 + } + return step + } + + // Ignore options are able to ignore missing elements in a slice. + // However, detecting these reliably requires an optimal differencing + // algorithm, for which diff.Difference is not. + // + // Instead, we first iterate through both slices to detect which elements + // would be ignored if standing alone. The index of non-discarded elements + // are stored in a separate slice, which diffing is then performed on. + var indexesX, indexesY []int + var ignoredX, ignoredY []bool + for ix := 0; ix < vx.Len(); ix++ { + ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0 + if !ignored { + indexesX = append(indexesX, ix) + } + ignoredX = append(ignoredX, ignored) + } + for iy := 0; iy < vy.Len(); iy++ { + ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0 + if !ignored { + indexesY = append(indexesY, iy) + } + ignoredY = append(ignoredY, ignored) + } + + // Compute an edit-script for slices vx and vy (excluding ignored elements). + edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result { + return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy])) + }) + + // Replay the ignore-scripts and the edit-script. + var ix, iy int + for ix < vx.Len() || iy < vy.Len() { + var e diff.EditType + switch { + case ix < len(ignoredX) && ignoredX[ix]: + e = diff.UniqueX + case iy < len(ignoredY) && ignoredY[iy]: + e = diff.UniqueY + default: + e, edits = edits[0], edits[1:] + } + switch e { + case diff.UniqueX: + s.compareAny(withIndexes(ix, -1)) + ix++ + case diff.UniqueY: + s.compareAny(withIndexes(-1, iy)) + iy++ + default: + s.compareAny(withIndexes(ix, iy)) + ix++ + iy++ + } + } +} + +func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) { + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), 0) + return + } + + // Cycle-detection for maps. + if eq, visited := s.curPtrs.Push(vx, vy); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(vx, vy) + + // We combine and sort the two map keys so that we can perform the + // comparisons in a deterministic order. + step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}} + for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) { + step.vx = vx.MapIndex(k) + step.vy = vy.MapIndex(k) + step.key = k + if !step.vx.IsValid() && !step.vy.IsValid() { + // It is possible for both vx and vy to be invalid if the + // key contained a NaN value in it. + // + // Even with the ability to retrieve NaN keys in Go 1.12, + // there still isn't a sensible way to compare the values since + // a NaN key may map to multiple unordered values. + // The most reasonable way to compare NaNs would be to compare the + // set of values. However, this is impossible to do efficiently + // since set equality is provably an O(n^2) operation given only + // an Equal function. If we had a Less function or Hash function, + // this could be done in O(n*log(n)) or O(n), respectively. + // + // Rather than adding complex logic to deal with NaNs, make it + // the user's responsibility to compare such obscure maps. + const help = "consider providing a Comparer to compare the map" + panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help)) + } + s.compareAny(step) + } +} + +func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) { + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), 0) + return + } + + // Cycle-detection for pointers. + if eq, visited := s.curPtrs.Push(vx, vy); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(vx, vy) + + vx, vy = vx.Elem(), vy.Elem() + s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}}) +} + +func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) { + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), 0) + return + } + vx, vy = vx.Elem(), vy.Elem() + if vx.Type() != vy.Type() { + s.report(false, 0) + return + } + s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}}) +} + +func (s *state) report(eq bool, rf resultFlags) { + if rf&reportByIgnore == 0 { + if eq { + s.result.NumSame++ + rf |= reportEqual + } else { + s.result.NumDiff++ + rf |= reportUnequal + } + } + for _, r := range s.reporters { + r.Report(Result{flags: rf}) + } +} + +// recChecker tracks the state needed to periodically perform checks that +// user provided transformers are not stuck in an infinitely recursive cycle. +type recChecker struct{ next int } + +// Check scans the Path for any recursive transformers and panics when any +// recursive transformers are detected. Note that the presence of a +// recursive Transformer does not necessarily imply an infinite cycle. +// As such, this check only activates after some minimal number of path steps. +func (rc *recChecker) Check(p Path) { + const minLen = 1 << 16 + if rc.next == 0 { + rc.next = minLen + } + if len(p) < rc.next { + return + } + rc.next <<= 1 + + // Check whether the same transformer has appeared at least twice. + var ss []string + m := map[Option]int{} + for _, ps := range p { + if t, ok := ps.(Transform); ok { + t := t.Option() + if m[t] == 1 { // Transformer was used exactly once before + tf := t.(*transformer).fnc.Type() + ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) + } + m[t]++ + } + } + if len(ss) > 0 { + const warning = "recursive set of Transformers detected" + const help = "consider using cmpopts.AcyclicTransformer" + set := strings.Join(ss, "\n\t") + panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) + } +} + +// dynChecker tracks the state needed to periodically perform checks that +// user provided functions are symmetric and deterministic. +// The zero value is safe for immediate use. +type dynChecker struct{ curr, next int } + +// Next increments the state and reports whether a check should be performed. +// +// Checks occur every Nth function call, where N is a triangular number: +// +// 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ... +// +// See https://en.wikipedia.org/wiki/Triangular_number +// +// This sequence ensures that the cost of checks drops significantly as +// the number of functions calls grows larger. +func (dc *dynChecker) Next() bool { + ok := dc.curr == dc.next + if ok { + dc.curr = 0 + dc.next++ + } + dc.curr++ + return ok +} + +// makeAddressable returns a value that is always addressable. +// It returns the input verbatim if it is already addressable, +// otherwise it creates a new value and returns an addressable copy. +func makeAddressable(v reflect.Value) reflect.Value { + if v.CanAddr() { + return v + } + vc := reflect.New(v.Type()).Elem() + vc.Set(v) + return vc +} diff --git a/vendor/github.com/google/go-cmp/cmp/export.go b/vendor/github.com/google/go-cmp/cmp/export.go new file mode 100644 index 0000000..29f82fe --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/export.go @@ -0,0 +1,31 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "reflect" + "unsafe" +) + +// retrieveUnexportedField uses unsafe to forcibly retrieve any field from +// a struct such that the value has read-write permissions. +// +// The parent struct, v, must be addressable, while f must be a StructField +// describing the field to retrieve. If addr is false, +// then the returned value will be shallowed copied to be non-addressable. +func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { + ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() + if !addr { + // A field is addressable if and only if the struct is addressable. + // If the original parent value was not addressable, shallow copy the + // value to make it non-addressable to avoid leaking an implementation + // detail of how forcibly exporting a field works. + if ve.Kind() == reflect.Interface && ve.IsNil() { + return reflect.Zero(f.Type) + } + return reflect.ValueOf(ve.Interface()).Convert(f.Type) + } + return ve +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go new file mode 100644 index 0000000..36062a6 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go @@ -0,0 +1,18 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !cmp_debug +// +build !cmp_debug + +package diff + +var debug debugger + +type debugger struct{} + +func (debugger) Begin(_, _ int, f EqualFunc, _, _ *EditScript) EqualFunc { + return f +} +func (debugger) Update() {} +func (debugger) Finish() {} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go new file mode 100644 index 0000000..a3b97a1 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go @@ -0,0 +1,123 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build cmp_debug +// +build cmp_debug + +package diff + +import ( + "fmt" + "strings" + "sync" + "time" +) + +// The algorithm can be seen running in real-time by enabling debugging: +// go test -tags=cmp_debug -v +// +// Example output: +// === RUN TestDifference/#34 +// ┌───────────────────────────────┐ +// │ \ · · · · · · · · · · · · · · │ +// │ · # · · · · · · · · · · · · · │ +// │ · \ · · · · · · · · · · · · · │ +// │ · · \ · · · · · · · · · · · · │ +// │ · · · X # · · · · · · · · · · │ +// │ · · · # \ · · · · · · · · · · │ +// │ · · · · · # # · · · · · · · · │ +// │ · · · · · # \ · · · · · · · · │ +// │ · · · · · · · \ · · · · · · · │ +// │ · · · · · · · · \ · · · · · · │ +// │ · · · · · · · · · \ · · · · · │ +// │ · · · · · · · · · · \ · · # · │ +// │ · · · · · · · · · · · \ # # · │ +// │ · · · · · · · · · · · # # # · │ +// │ · · · · · · · · · · # # # # · │ +// │ · · · · · · · · · # # # # # · │ +// │ · · · · · · · · · · · · · · \ │ +// └───────────────────────────────┘ +// [.Y..M.XY......YXYXY.|] +// +// The grid represents the edit-graph where the horizontal axis represents +// list X and the vertical axis represents list Y. The start of the two lists +// is the top-left, while the ends are the bottom-right. The '·' represents +// an unexplored node in the graph. The '\' indicates that the two symbols +// from list X and Y are equal. The 'X' indicates that two symbols are similar +// (but not exactly equal) to each other. The '#' indicates that the two symbols +// are different (and not similar). The algorithm traverses this graph trying to +// make the paths starting in the top-left and the bottom-right connect. +// +// The series of '.', 'X', 'Y', and 'M' characters at the bottom represents +// the currently established path from the forward and reverse searches, +// separated by a '|' character. + +const ( + updateDelay = 100 * time.Millisecond + finishDelay = 500 * time.Millisecond + ansiTerminal = true // ANSI escape codes used to move terminal cursor +) + +var debug debugger + +type debugger struct { + sync.Mutex + p1, p2 EditScript + fwdPath, revPath *EditScript + grid []byte + lines int +} + +func (dbg *debugger) Begin(nx, ny int, f EqualFunc, p1, p2 *EditScript) EqualFunc { + dbg.Lock() + dbg.fwdPath, dbg.revPath = p1, p2 + top := "┌─" + strings.Repeat("──", nx) + "┐\n" + row := "│ " + strings.Repeat("· ", nx) + "│\n" + btm := "└─" + strings.Repeat("──", nx) + "┘\n" + dbg.grid = []byte(top + strings.Repeat(row, ny) + btm) + dbg.lines = strings.Count(dbg.String(), "\n") + fmt.Print(dbg) + + // Wrap the EqualFunc so that we can intercept each result. + return func(ix, iy int) (r Result) { + cell := dbg.grid[len(top)+iy*len(row):][len("│ ")+len("· ")*ix:][:len("·")] + for i := range cell { + cell[i] = 0 // Zero out the multiple bytes of UTF-8 middle-dot + } + switch r = f(ix, iy); { + case r.Equal(): + cell[0] = '\\' + case r.Similar(): + cell[0] = 'X' + default: + cell[0] = '#' + } + return + } +} + +func (dbg *debugger) Update() { + dbg.print(updateDelay) +} + +func (dbg *debugger) Finish() { + dbg.print(finishDelay) + dbg.Unlock() +} + +func (dbg *debugger) String() string { + dbg.p1, dbg.p2 = *dbg.fwdPath, dbg.p2[:0] + for i := len(*dbg.revPath) - 1; i >= 0; i-- { + dbg.p2 = append(dbg.p2, (*dbg.revPath)[i]) + } + return fmt.Sprintf("%s[%v|%v]\n\n", dbg.grid, dbg.p1, dbg.p2) +} + +func (dbg *debugger) print(d time.Duration) { + if ansiTerminal { + fmt.Printf("\x1b[%dA", dbg.lines) // Reset terminal cursor + } + fmt.Print(dbg) + time.Sleep(d) +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go new file mode 100644 index 0000000..a248e54 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go @@ -0,0 +1,402 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package diff implements an algorithm for producing edit-scripts. +// The edit-script is a sequence of operations needed to transform one list +// of symbols into another (or vice-versa). The edits allowed are insertions, +// deletions, and modifications. The summation of all edits is called the +// Levenshtein distance as this problem is well-known in computer science. +// +// This package prioritizes performance over accuracy. That is, the run time +// is more important than obtaining a minimal Levenshtein distance. +package diff + +import ( + "math/rand" + "time" + + "github.com/google/go-cmp/cmp/internal/flags" +) + +// EditType represents a single operation within an edit-script. +type EditType uint8 + +const ( + // Identity indicates that a symbol pair is identical in both list X and Y. + Identity EditType = iota + // UniqueX indicates that a symbol only exists in X and not Y. + UniqueX + // UniqueY indicates that a symbol only exists in Y and not X. + UniqueY + // Modified indicates that a symbol pair is a modification of each other. + Modified +) + +// EditScript represents the series of differences between two lists. +type EditScript []EditType + +// String returns a human-readable string representing the edit-script where +// Identity, UniqueX, UniqueY, and Modified are represented by the +// '.', 'X', 'Y', and 'M' characters, respectively. +func (es EditScript) String() string { + b := make([]byte, len(es)) + for i, e := range es { + switch e { + case Identity: + b[i] = '.' + case UniqueX: + b[i] = 'X' + case UniqueY: + b[i] = 'Y' + case Modified: + b[i] = 'M' + default: + panic("invalid edit-type") + } + } + return string(b) +} + +// stats returns a histogram of the number of each type of edit operation. +func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) { + for _, e := range es { + switch e { + case Identity: + s.NI++ + case UniqueX: + s.NX++ + case UniqueY: + s.NY++ + case Modified: + s.NM++ + default: + panic("invalid edit-type") + } + } + return +} + +// Dist is the Levenshtein distance and is guaranteed to be 0 if and only if +// lists X and Y are equal. +func (es EditScript) Dist() int { return len(es) - es.stats().NI } + +// LenX is the length of the X list. +func (es EditScript) LenX() int { return len(es) - es.stats().NY } + +// LenY is the length of the Y list. +func (es EditScript) LenY() int { return len(es) - es.stats().NX } + +// EqualFunc reports whether the symbols at indexes ix and iy are equal. +// When called by Difference, the index is guaranteed to be within nx and ny. +type EqualFunc func(ix int, iy int) Result + +// Result is the result of comparison. +// NumSame is the number of sub-elements that are equal. +// NumDiff is the number of sub-elements that are not equal. +type Result struct{ NumSame, NumDiff int } + +// BoolResult returns a Result that is either Equal or not Equal. +func BoolResult(b bool) Result { + if b { + return Result{NumSame: 1} // Equal, Similar + } else { + return Result{NumDiff: 2} // Not Equal, not Similar + } +} + +// Equal indicates whether the symbols are equal. Two symbols are equal +// if and only if NumDiff == 0. If Equal, then they are also Similar. +func (r Result) Equal() bool { return r.NumDiff == 0 } + +// Similar indicates whether two symbols are similar and may be represented +// by using the Modified type. As a special case, we consider binary comparisons +// (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar. +// +// The exact ratio of NumSame to NumDiff to determine similarity may change. +func (r Result) Similar() bool { + // Use NumSame+1 to offset NumSame so that binary comparisons are similar. + return r.NumSame+1 >= r.NumDiff +} + +var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 + +// Difference reports whether two lists of lengths nx and ny are equal +// given the definition of equality provided as f. +// +// This function returns an edit-script, which is a sequence of operations +// needed to convert one list into the other. The following invariants for +// the edit-script are maintained: +// - eq == (es.Dist()==0) +// - nx == es.LenX() +// - ny == es.LenY() +// +// This algorithm is not guaranteed to be an optimal solution (i.e., one that +// produces an edit-script with a minimal Levenshtein distance). This algorithm +// favors performance over optimality. The exact output is not guaranteed to +// be stable and may change over time. +func Difference(nx, ny int, f EqualFunc) (es EditScript) { + // This algorithm is based on traversing what is known as an "edit-graph". + // See Figure 1 from "An O(ND) Difference Algorithm and Its Variations" + // by Eugene W. Myers. Since D can be as large as N itself, this is + // effectively O(N^2). Unlike the algorithm from that paper, we are not + // interested in the optimal path, but at least some "decent" path. + // + // For example, let X and Y be lists of symbols: + // X = [A B C A B B A] + // Y = [C B A B A C] + // + // The edit-graph can be drawn as the following: + // A B C A B B A + // ┌─────────────┐ + // C │_|_|\|_|_|_|_│ 0 + // B │_|\|_|_|\|\|_│ 1 + // A │\|_|_|\|_|_|\│ 2 + // B │_|\|_|_|\|\|_│ 3 + // A │\|_|_|\|_|_|\│ 4 + // C │ | |\| | | | │ 5 + // └─────────────┘ 6 + // 0 1 2 3 4 5 6 7 + // + // List X is written along the horizontal axis, while list Y is written + // along the vertical axis. At any point on this grid, if the symbol in + // list X matches the corresponding symbol in list Y, then a '\' is drawn. + // The goal of any minimal edit-script algorithm is to find a path from the + // top-left corner to the bottom-right corner, while traveling through the + // fewest horizontal or vertical edges. + // A horizontal edge is equivalent to inserting a symbol from list X. + // A vertical edge is equivalent to inserting a symbol from list Y. + // A diagonal edge is equivalent to a matching symbol between both X and Y. + + // Invariants: + // - 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx + // - 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny + // + // In general: + // - fwdFrontier.X < revFrontier.X + // - fwdFrontier.Y < revFrontier.Y + // + // Unless, it is time for the algorithm to terminate. + fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)} + revPath := path{-1, point{nx, ny}, make(EditScript, 0)} + fwdFrontier := fwdPath.point // Forward search frontier + revFrontier := revPath.point // Reverse search frontier + + // Search budget bounds the cost of searching for better paths. + // The longest sequence of non-matching symbols that can be tolerated is + // approximately the square-root of the search budget. + searchBudget := 4 * (nx + ny) // O(n) + + // Running the tests with the "cmp_debug" build tag prints a visualization + // of the algorithm running in real-time. This is educational for + // understanding how the algorithm works. See debug_enable.go. + f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es) + + // The algorithm below is a greedy, meet-in-the-middle algorithm for + // computing sub-optimal edit-scripts between two lists. + // + // The algorithm is approximately as follows: + // - Searching for differences switches back-and-forth between + // a search that starts at the beginning (the top-left corner), and + // a search that starts at the end (the bottom-right corner). + // The goal of the search is connect with the search + // from the opposite corner. + // - As we search, we build a path in a greedy manner, + // where the first match seen is added to the path (this is sub-optimal, + // but provides a decent result in practice). When matches are found, + // we try the next pair of symbols in the lists and follow all matches + // as far as possible. + // - When searching for matches, we search along a diagonal going through + // through the "frontier" point. If no matches are found, + // we advance the frontier towards the opposite corner. + // - This algorithm terminates when either the X coordinates or the + // Y coordinates of the forward and reverse frontier points ever intersect. + + // This algorithm is correct even if searching only in the forward direction + // or in the reverse direction. We do both because it is commonly observed + // that two lists commonly differ because elements were added to the front + // or end of the other list. + // + // Non-deterministically start with either the forward or reverse direction + // to introduce some deliberate instability so that we have the flexibility + // to change this algorithm in the future. + if flags.Deterministic || randBool { + goto forwardSearch + } else { + goto reverseSearch + } + +forwardSearch: + { + // Forward search from the beginning. + if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { + goto finishSearch + } + for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { + // Search in a diagonal pattern for a match. + z := zigzag(i) + p := point{fwdFrontier.X + z, fwdFrontier.Y - z} + switch { + case p.X >= revPath.X || p.Y < fwdPath.Y: + stop1 = true // Hit top-right corner + case p.Y >= revPath.Y || p.X < fwdPath.X: + stop2 = true // Hit bottom-left corner + case f(p.X, p.Y).Equal(): + // Match found, so connect the path to this point. + fwdPath.connect(p, f) + fwdPath.append(Identity) + // Follow sequence of matches as far as possible. + for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { + if !f(fwdPath.X, fwdPath.Y).Equal() { + break + } + fwdPath.append(Identity) + } + fwdFrontier = fwdPath.point + stop1, stop2 = true, true + default: + searchBudget-- // Match not found + } + debug.Update() + } + // Advance the frontier towards reverse point. + if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y { + fwdFrontier.X++ + } else { + fwdFrontier.Y++ + } + goto reverseSearch + } + +reverseSearch: + { + // Reverse search from the end. + if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { + goto finishSearch + } + for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { + // Search in a diagonal pattern for a match. + z := zigzag(i) + p := point{revFrontier.X - z, revFrontier.Y + z} + switch { + case fwdPath.X >= p.X || revPath.Y < p.Y: + stop1 = true // Hit bottom-left corner + case fwdPath.Y >= p.Y || revPath.X < p.X: + stop2 = true // Hit top-right corner + case f(p.X-1, p.Y-1).Equal(): + // Match found, so connect the path to this point. + revPath.connect(p, f) + revPath.append(Identity) + // Follow sequence of matches as far as possible. + for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { + if !f(revPath.X-1, revPath.Y-1).Equal() { + break + } + revPath.append(Identity) + } + revFrontier = revPath.point + stop1, stop2 = true, true + default: + searchBudget-- // Match not found + } + debug.Update() + } + // Advance the frontier towards forward point. + if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y { + revFrontier.X-- + } else { + revFrontier.Y-- + } + goto forwardSearch + } + +finishSearch: + // Join the forward and reverse paths and then append the reverse path. + fwdPath.connect(revPath.point, f) + for i := len(revPath.es) - 1; i >= 0; i-- { + t := revPath.es[i] + revPath.es = revPath.es[:i] + fwdPath.append(t) + } + debug.Finish() + return fwdPath.es +} + +type path struct { + dir int // +1 if forward, -1 if reverse + point // Leading point of the EditScript path + es EditScript +} + +// connect appends any necessary Identity, Modified, UniqueX, or UniqueY types +// to the edit-script to connect p.point to dst. +func (p *path) connect(dst point, f EqualFunc) { + if p.dir > 0 { + // Connect in forward direction. + for dst.X > p.X && dst.Y > p.Y { + switch r := f(p.X, p.Y); { + case r.Equal(): + p.append(Identity) + case r.Similar(): + p.append(Modified) + case dst.X-p.X >= dst.Y-p.Y: + p.append(UniqueX) + default: + p.append(UniqueY) + } + } + for dst.X > p.X { + p.append(UniqueX) + } + for dst.Y > p.Y { + p.append(UniqueY) + } + } else { + // Connect in reverse direction. + for p.X > dst.X && p.Y > dst.Y { + switch r := f(p.X-1, p.Y-1); { + case r.Equal(): + p.append(Identity) + case r.Similar(): + p.append(Modified) + case p.Y-dst.Y >= p.X-dst.X: + p.append(UniqueY) + default: + p.append(UniqueX) + } + } + for p.X > dst.X { + p.append(UniqueX) + } + for p.Y > dst.Y { + p.append(UniqueY) + } + } +} + +func (p *path) append(t EditType) { + p.es = append(p.es, t) + switch t { + case Identity, Modified: + p.add(p.dir, p.dir) + case UniqueX: + p.add(p.dir, 0) + case UniqueY: + p.add(0, p.dir) + } + debug.Update() +} + +type point struct{ X, Y int } + +func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy } + +// zigzag maps a consecutive sequence of integers to a zig-zag sequence. +// +// [0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...] +func zigzag(x int) int { + if x&1 != 0 { + x = ^x + } + return x >> 1 +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go b/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go new file mode 100644 index 0000000..d8e459c --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go @@ -0,0 +1,9 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package flags + +// Deterministic controls whether the output of Diff should be deterministic. +// This is only used for testing. +var Deterministic bool diff --git a/vendor/github.com/google/go-cmp/cmp/internal/function/func.go b/vendor/github.com/google/go-cmp/cmp/internal/function/func.go new file mode 100644 index 0000000..d127d43 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/function/func.go @@ -0,0 +1,99 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package function provides functionality for identifying function types. +package function + +import ( + "reflect" + "regexp" + "runtime" + "strings" +) + +type funcType int + +const ( + _ funcType = iota + + tbFunc // func(T) bool + ttbFunc // func(T, T) bool + trbFunc // func(T, R) bool + tibFunc // func(T, I) bool + trFunc // func(T) R + + Equal = ttbFunc // func(T, T) bool + EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool + Transformer = trFunc // func(T) R + ValueFilter = ttbFunc // func(T, T) bool + Less = ttbFunc // func(T, T) bool + ValuePredicate = tbFunc // func(T) bool + KeyValuePredicate = trbFunc // func(T, R) bool +) + +var boolType = reflect.TypeOf(true) + +// IsType reports whether the reflect.Type is of the specified function type. +func IsType(t reflect.Type, ft funcType) bool { + if t == nil || t.Kind() != reflect.Func || t.IsVariadic() { + return false + } + ni, no := t.NumIn(), t.NumOut() + switch ft { + case tbFunc: // func(T) bool + if ni == 1 && no == 1 && t.Out(0) == boolType { + return true + } + case ttbFunc: // func(T, T) bool + if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType { + return true + } + case trbFunc: // func(T, R) bool + if ni == 2 && no == 1 && t.Out(0) == boolType { + return true + } + case tibFunc: // func(T, I) bool + if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType { + return true + } + case trFunc: // func(T) R + if ni == 1 && no == 1 { + return true + } + } + return false +} + +var lastIdentRx = regexp.MustCompile(`[_\p{L}][_\p{L}\p{N}]*$`) + +// NameOf returns the name of the function value. +func NameOf(v reflect.Value) string { + fnc := runtime.FuncForPC(v.Pointer()) + if fnc == nil { + return "" + } + fullName := fnc.Name() // e.g., "long/path/name/mypkg.(*MyType).(long/path/name/mypkg.myMethod)-fm" + + // Method closures have a "-fm" suffix. + fullName = strings.TrimSuffix(fullName, "-fm") + + var name string + for len(fullName) > 0 { + inParen := strings.HasSuffix(fullName, ")") + fullName = strings.TrimSuffix(fullName, ")") + + s := lastIdentRx.FindString(fullName) + if s == "" { + break + } + name = s + "." + name + fullName = strings.TrimSuffix(fullName, s) + + if i := strings.LastIndexByte(fullName, '('); inParen && i >= 0 { + fullName = fullName[:i] + } + fullName = strings.TrimSuffix(fullName, ".") + } + return strings.TrimSuffix(name, ".") +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/name.go b/vendor/github.com/google/go-cmp/cmp/internal/value/name.go new file mode 100644 index 0000000..7b498bb --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/name.go @@ -0,0 +1,164 @@ +// Copyright 2020, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package value + +import ( + "reflect" + "strconv" +) + +var anyType = reflect.TypeOf((*interface{})(nil)).Elem() + +// TypeString is nearly identical to reflect.Type.String, +// but has an additional option to specify that full type names be used. +func TypeString(t reflect.Type, qualified bool) string { + return string(appendTypeName(nil, t, qualified, false)) +} + +func appendTypeName(b []byte, t reflect.Type, qualified, elideFunc bool) []byte { + // BUG: Go reflection provides no way to disambiguate two named types + // of the same name and within the same package, + // but declared within the namespace of different functions. + + // Use the "any" alias instead of "interface{}" for better readability. + if t == anyType { + return append(b, "any"...) + } + + // Named type. + if t.Name() != "" { + if qualified && t.PkgPath() != "" { + b = append(b, '"') + b = append(b, t.PkgPath()...) + b = append(b, '"') + b = append(b, '.') + b = append(b, t.Name()...) + } else { + b = append(b, t.String()...) + } + return b + } + + // Unnamed type. + switch k := t.Kind(); k { + case reflect.Bool, reflect.String, reflect.UnsafePointer, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + b = append(b, k.String()...) + case reflect.Chan: + if t.ChanDir() == reflect.RecvDir { + b = append(b, "<-"...) + } + b = append(b, "chan"...) + if t.ChanDir() == reflect.SendDir { + b = append(b, "<-"...) + } + b = append(b, ' ') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Func: + if !elideFunc { + b = append(b, "func"...) + } + b = append(b, '(') + for i := 0; i < t.NumIn(); i++ { + if i > 0 { + b = append(b, ", "...) + } + if i == t.NumIn()-1 && t.IsVariadic() { + b = append(b, "..."...) + b = appendTypeName(b, t.In(i).Elem(), qualified, false) + } else { + b = appendTypeName(b, t.In(i), qualified, false) + } + } + b = append(b, ')') + switch t.NumOut() { + case 0: + // Do nothing + case 1: + b = append(b, ' ') + b = appendTypeName(b, t.Out(0), qualified, false) + default: + b = append(b, " ("...) + for i := 0; i < t.NumOut(); i++ { + if i > 0 { + b = append(b, ", "...) + } + b = appendTypeName(b, t.Out(i), qualified, false) + } + b = append(b, ')') + } + case reflect.Struct: + b = append(b, "struct{ "...) + for i := 0; i < t.NumField(); i++ { + if i > 0 { + b = append(b, "; "...) + } + sf := t.Field(i) + if !sf.Anonymous { + if qualified && sf.PkgPath != "" { + b = append(b, '"') + b = append(b, sf.PkgPath...) + b = append(b, '"') + b = append(b, '.') + } + b = append(b, sf.Name...) + b = append(b, ' ') + } + b = appendTypeName(b, sf.Type, qualified, false) + if sf.Tag != "" { + b = append(b, ' ') + b = strconv.AppendQuote(b, string(sf.Tag)) + } + } + if b[len(b)-1] == ' ' { + b = b[:len(b)-1] + } else { + b = append(b, ' ') + } + b = append(b, '}') + case reflect.Slice, reflect.Array: + b = append(b, '[') + if k == reflect.Array { + b = strconv.AppendUint(b, uint64(t.Len()), 10) + } + b = append(b, ']') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Map: + b = append(b, "map["...) + b = appendTypeName(b, t.Key(), qualified, false) + b = append(b, ']') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Ptr: + b = append(b, '*') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Interface: + b = append(b, "interface{ "...) + for i := 0; i < t.NumMethod(); i++ { + if i > 0 { + b = append(b, "; "...) + } + m := t.Method(i) + if qualified && m.PkgPath != "" { + b = append(b, '"') + b = append(b, m.PkgPath...) + b = append(b, '"') + b = append(b, '.') + } + b = append(b, m.Name...) + b = appendTypeName(b, m.Type, qualified, true) + } + if b[len(b)-1] == ' ' { + b = b[:len(b)-1] + } else { + b = append(b, ' ') + } + b = append(b, '}') + default: + panic("invalid kind: " + k.String()) + } + return b +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go new file mode 100644 index 0000000..e5dfff6 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go @@ -0,0 +1,34 @@ +// Copyright 2018, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package value + +import ( + "reflect" + "unsafe" +) + +// Pointer is an opaque typed pointer and is guaranteed to be comparable. +type Pointer struct { + p unsafe.Pointer + t reflect.Type +} + +// PointerOf returns a Pointer from v, which must be a +// reflect.Ptr, reflect.Slice, or reflect.Map. +func PointerOf(v reflect.Value) Pointer { + // The proper representation of a pointer is unsafe.Pointer, + // which is necessary if the GC ever uses a moving collector. + return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} +} + +// IsNil reports whether the pointer is nil. +func (p Pointer) IsNil() bool { + return p.p == nil +} + +// Uintptr returns the pointer as a uintptr. +func (p Pointer) Uintptr() uintptr { + return uintptr(p.p) +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go b/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go new file mode 100644 index 0000000..98533b0 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go @@ -0,0 +1,106 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package value + +import ( + "fmt" + "math" + "reflect" + "sort" +) + +// SortKeys sorts a list of map keys, deduplicating keys if necessary. +// The type of each value must be comparable. +func SortKeys(vs []reflect.Value) []reflect.Value { + if len(vs) == 0 { + return vs + } + + // Sort the map keys. + sort.SliceStable(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) }) + + // Deduplicate keys (fails for NaNs). + vs2 := vs[:1] + for _, v := range vs[1:] { + if isLess(vs2[len(vs2)-1], v) { + vs2 = append(vs2, v) + } + } + return vs2 +} + +// isLess is a generic function for sorting arbitrary map keys. +// The inputs must be of the same type and must be comparable. +func isLess(x, y reflect.Value) bool { + switch x.Type().Kind() { + case reflect.Bool: + return !x.Bool() && y.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return x.Int() < y.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return x.Uint() < y.Uint() + case reflect.Float32, reflect.Float64: + // NOTE: This does not sort -0 as less than +0 + // since Go maps treat -0 and +0 as equal keys. + fx, fy := x.Float(), y.Float() + return fx < fy || math.IsNaN(fx) && !math.IsNaN(fy) + case reflect.Complex64, reflect.Complex128: + cx, cy := x.Complex(), y.Complex() + rx, ix, ry, iy := real(cx), imag(cx), real(cy), imag(cy) + if rx == ry || (math.IsNaN(rx) && math.IsNaN(ry)) { + return ix < iy || math.IsNaN(ix) && !math.IsNaN(iy) + } + return rx < ry || math.IsNaN(rx) && !math.IsNaN(ry) + case reflect.Ptr, reflect.UnsafePointer, reflect.Chan: + return x.Pointer() < y.Pointer() + case reflect.String: + return x.String() < y.String() + case reflect.Array: + for i := 0; i < x.Len(); i++ { + if isLess(x.Index(i), y.Index(i)) { + return true + } + if isLess(y.Index(i), x.Index(i)) { + return false + } + } + return false + case reflect.Struct: + for i := 0; i < x.NumField(); i++ { + if isLess(x.Field(i), y.Field(i)) { + return true + } + if isLess(y.Field(i), x.Field(i)) { + return false + } + } + return false + case reflect.Interface: + vx, vy := x.Elem(), y.Elem() + if !vx.IsValid() || !vy.IsValid() { + return !vx.IsValid() && vy.IsValid() + } + tx, ty := vx.Type(), vy.Type() + if tx == ty { + return isLess(x.Elem(), y.Elem()) + } + if tx.Kind() != ty.Kind() { + return vx.Kind() < vy.Kind() + } + if tx.String() != ty.String() { + return tx.String() < ty.String() + } + if tx.PkgPath() != ty.PkgPath() { + return tx.PkgPath() < ty.PkgPath() + } + // This can happen in rare situations, so we fallback to just comparing + // the unique pointer for a reflect.Type. This guarantees deterministic + // ordering within a program, but it is obviously not stable. + return reflect.ValueOf(vx.Type()).Pointer() < reflect.ValueOf(vy.Type()).Pointer() + default: + // Must be Func, Map, or Slice; which are not comparable. + panic(fmt.Sprintf("%T is not comparable", x.Type())) + } +} diff --git a/vendor/github.com/google/go-cmp/cmp/options.go b/vendor/github.com/google/go-cmp/cmp/options.go new file mode 100644 index 0000000..754496f --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/options.go @@ -0,0 +1,554 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "fmt" + "reflect" + "regexp" + "strings" + + "github.com/google/go-cmp/cmp/internal/function" +) + +// Option configures for specific behavior of [Equal] and [Diff]. In particular, +// the fundamental Option functions ([Ignore], [Transformer], and [Comparer]), +// configure how equality is determined. +// +// The fundamental options may be composed with filters ([FilterPath] and +// [FilterValues]) to control the scope over which they are applied. +// +// The [github.com/google/go-cmp/cmp/cmpopts] package provides helper functions +// for creating options that may be used with [Equal] and [Diff]. +type Option interface { + // filter applies all filters and returns the option that remains. + // Each option may only read s.curPath and call s.callTTBFunc. + // + // An Options is returned only if multiple comparers or transformers + // can apply simultaneously and will only contain values of those types + // or sub-Options containing values of those types. + filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption +} + +// applicableOption represents the following types: +// +// Fundamental: ignore | validator | *comparer | *transformer +// Grouping: Options +type applicableOption interface { + Option + + // apply executes the option, which may mutate s or panic. + apply(s *state, vx, vy reflect.Value) +} + +// coreOption represents the following types: +// +// Fundamental: ignore | validator | *comparer | *transformer +// Filters: *pathFilter | *valuesFilter +type coreOption interface { + Option + isCore() +} + +type core struct{} + +func (core) isCore() {} + +// Options is a list of [Option] values that also satisfies the [Option] interface. +// Helper comparison packages may return an Options value when packing multiple +// [Option] values into a single [Option]. When this package processes an Options, +// it will be implicitly expanded into a flat list. +// +// Applying a filter on an Options is equivalent to applying that same filter +// on all individual options held within. +type Options []Option + +func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) { + for _, opt := range opts { + switch opt := opt.filter(s, t, vx, vy); opt.(type) { + case ignore: + return ignore{} // Only ignore can short-circuit evaluation + case validator: + out = validator{} // Takes precedence over comparer or transformer + case *comparer, *transformer, Options: + switch out.(type) { + case nil: + out = opt + case validator: + // Keep validator + case *comparer, *transformer, Options: + out = Options{out, opt} // Conflicting comparers or transformers + } + } + } + return out +} + +func (opts Options) apply(s *state, _, _ reflect.Value) { + const warning = "ambiguous set of applicable options" + const help = "consider using filters to ensure at most one Comparer or Transformer may apply" + var ss []string + for _, opt := range flattenOptions(nil, opts) { + ss = append(ss, fmt.Sprint(opt)) + } + set := strings.Join(ss, "\n\t") + panic(fmt.Sprintf("%s at %#v:\n\t%s\n%s", warning, s.curPath, set, help)) +} + +func (opts Options) String() string { + var ss []string + for _, opt := range opts { + ss = append(ss, fmt.Sprint(opt)) + } + return fmt.Sprintf("Options{%s}", strings.Join(ss, ", ")) +} + +// FilterPath returns a new [Option] where opt is only evaluated if filter f +// returns true for the current [Path] in the value tree. +// +// This filter is called even if a slice element or map entry is missing and +// provides an opportunity to ignore such cases. The filter function must be +// symmetric such that the filter result is identical regardless of whether the +// missing value is from x or y. +// +// The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or +// a previously filtered [Option]. +func FilterPath(f func(Path) bool, opt Option) Option { + if f == nil { + panic("invalid path filter function") + } + if opt := normalizeOption(opt); opt != nil { + return &pathFilter{fnc: f, opt: opt} + } + return nil +} + +type pathFilter struct { + core + fnc func(Path) bool + opt Option +} + +func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { + if f.fnc(s.curPath) { + return f.opt.filter(s, t, vx, vy) + } + return nil +} + +func (f pathFilter) String() string { + return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt) +} + +// FilterValues returns a new [Option] where opt is only evaluated if filter f, +// which is a function of the form "func(T, T) bool", returns true for the +// current pair of values being compared. If either value is invalid or +// the type of the values is not assignable to T, then this filter implicitly +// returns false. +// +// The filter function must be +// symmetric (i.e., agnostic to the order of the inputs) and +// deterministic (i.e., produces the same result when given the same inputs). +// If T is an interface, it is possible that f is called with two values with +// different concrete types that both implement T. +// +// The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or +// a previously filtered [Option]. +func FilterValues(f interface{}, opt Option) Option { + v := reflect.ValueOf(f) + if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() { + panic(fmt.Sprintf("invalid values filter function: %T", f)) + } + if opt := normalizeOption(opt); opt != nil { + vf := &valuesFilter{fnc: v, opt: opt} + if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { + vf.typ = ti + } + return vf + } + return nil +} + +type valuesFilter struct { + core + typ reflect.Type // T + fnc reflect.Value // func(T, T) bool + opt Option +} + +func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { + if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() { + return nil + } + if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) { + return f.opt.filter(s, t, vx, vy) + } + return nil +} + +func (f valuesFilter) String() string { + return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt) +} + +// Ignore is an [Option] that causes all comparisons to be ignored. +// This value is intended to be combined with [FilterPath] or [FilterValues]. +// It is an error to pass an unfiltered Ignore option to [Equal]. +func Ignore() Option { return ignore{} } + +type ignore struct{ core } + +func (ignore) isFiltered() bool { return false } +func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} } +func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) } +func (ignore) String() string { return "Ignore()" } + +// validator is a sentinel Option type to indicate that some options could not +// be evaluated due to unexported fields, missing slice elements, or +// missing map entries. Both values are validator only for unexported fields. +type validator struct{ core } + +func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption { + if !vx.IsValid() || !vy.IsValid() { + return validator{} + } + if !vx.CanInterface() || !vy.CanInterface() { + return validator{} + } + return nil +} +func (validator) apply(s *state, vx, vy reflect.Value) { + // Implies missing slice element or map entry. + if !vx.IsValid() || !vy.IsValid() { + s.report(vx.IsValid() == vy.IsValid(), 0) + return + } + + // Unable to Interface implies unexported field without visibility access. + if !vx.CanInterface() || !vy.CanInterface() { + help := "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported" + var name string + if t := s.curPath.Index(-2).Type(); t.Name() != "" { + // Named type with unexported fields. + name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType + if _, ok := reflect.New(t).Interface().(error); ok { + help = "consider using cmpopts.EquateErrors to compare error values" + } else if t.Comparable() { + help = "consider using cmpopts.EquateComparable to compare comparable Go types" + } + } else { + // Unnamed type with unexported fields. Derive PkgPath from field. + var pkgPath string + for i := 0; i < t.NumField() && pkgPath == ""; i++ { + pkgPath = t.Field(i).PkgPath + } + name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int }) + } + panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help)) + } + + panic("not reachable") +} + +// identRx represents a valid identifier according to the Go specification. +const identRx = `[_\p{L}][_\p{L}\p{N}]*` + +var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) + +// Transformer returns an [Option] that applies a transformation function that +// converts values of a certain type into that of another. +// +// The transformer f must be a function "func(T) R" that converts values of +// type T to those of type R and is implicitly filtered to input values +// assignable to T. The transformer must not mutate T in any way. +// +// To help prevent some cases of infinite recursive cycles applying the +// same transform to the output of itself (e.g., in the case where the +// input and output types are the same), an implicit filter is added such that +// a transformer is applicable only if that exact transformer is not already +// in the tail of the [Path] since the last non-[Transform] step. +// For situations where the implicit filter is still insufficient, +// consider using [github.com/google/go-cmp/cmp/cmpopts.AcyclicTransformer], +// which adds a filter to prevent the transformer from +// being recursively applied upon itself. +// +// The name is a user provided label that is used as the [Transform.Name] in the +// transformation [PathStep] (and eventually shown in the [Diff] output). +// The name must be a valid identifier or qualified identifier in Go syntax. +// If empty, an arbitrary name is used. +func Transformer(name string, f interface{}) Option { + v := reflect.ValueOf(f) + if !function.IsType(v.Type(), function.Transformer) || v.IsNil() { + panic(fmt.Sprintf("invalid transformer function: %T", f)) + } + if name == "" { + name = function.NameOf(v) + if !identsRx.MatchString(name) { + name = "λ" // Lambda-symbol as placeholder name + } + } else if !identsRx.MatchString(name) { + panic(fmt.Sprintf("invalid name: %q", name)) + } + tr := &transformer{name: name, fnc: reflect.ValueOf(f)} + if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { + tr.typ = ti + } + return tr +} + +type transformer struct { + core + name string + typ reflect.Type // T + fnc reflect.Value // func(T) R +} + +func (tr *transformer) isFiltered() bool { return tr.typ != nil } + +func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption { + for i := len(s.curPath) - 1; i >= 0; i-- { + if t, ok := s.curPath[i].(Transform); !ok { + break // Hit most recent non-Transform step + } else if tr == t.trans { + return nil // Cannot directly use same Transform + } + } + if tr.typ == nil || t.AssignableTo(tr.typ) { + return tr + } + return nil +} + +func (tr *transformer) apply(s *state, vx, vy reflect.Value) { + step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}} + vvx := s.callTRFunc(tr.fnc, vx, step) + vvy := s.callTRFunc(tr.fnc, vy, step) + step.vx, step.vy = vvx, vvy + s.compareAny(step) +} + +func (tr transformer) String() string { + return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc)) +} + +// Comparer returns an [Option] that determines whether two values are equal +// to each other. +// +// The comparer f must be a function "func(T, T) bool" and is implicitly +// filtered to input values assignable to T. If T is an interface, it is +// possible that f is called with two values of different concrete types that +// both implement T. +// +// The equality function must be: +// - Symmetric: equal(x, y) == equal(y, x) +// - Deterministic: equal(x, y) == equal(x, y) +// - Pure: equal(x, y) does not modify x or y +func Comparer(f interface{}) Option { + v := reflect.ValueOf(f) + if !function.IsType(v.Type(), function.Equal) || v.IsNil() { + panic(fmt.Sprintf("invalid comparer function: %T", f)) + } + cm := &comparer{fnc: v} + if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { + cm.typ = ti + } + return cm +} + +type comparer struct { + core + typ reflect.Type // T + fnc reflect.Value // func(T, T) bool +} + +func (cm *comparer) isFiltered() bool { return cm.typ != nil } + +func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption { + if cm.typ == nil || t.AssignableTo(cm.typ) { + return cm + } + return nil +} + +func (cm *comparer) apply(s *state, vx, vy reflect.Value) { + eq := s.callTTBFunc(cm.fnc, vx, vy) + s.report(eq, reportByFunc) +} + +func (cm comparer) String() string { + return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc)) +} + +// Exporter returns an [Option] that specifies whether [Equal] is allowed to +// introspect into the unexported fields of certain struct types. +// +// Users of this option must understand that comparing on unexported fields +// from external packages is not safe since changes in the internal +// implementation of some external package may cause the result of [Equal] +// to unexpectedly change. However, it may be valid to use this option on types +// defined in an internal package where the semantic meaning of an unexported +// field is in the control of the user. +// +// In many cases, a custom [Comparer] should be used instead that defines +// equality as a function of the public API of a type rather than the underlying +// unexported implementation. +// +// For example, the [reflect.Type] documentation defines equality to be determined +// by the == operator on the interface (essentially performing a shallow pointer +// comparison) and most attempts to compare *[regexp.Regexp] types are interested +// in only checking that the regular expression strings are equal. +// Both of these are accomplished using [Comparer] options: +// +// Comparer(func(x, y reflect.Type) bool { return x == y }) +// Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() }) +// +// In other cases, the [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported] +// option can be used to ignore all unexported fields on specified struct types. +func Exporter(f func(reflect.Type) bool) Option { + return exporter(f) +} + +type exporter func(reflect.Type) bool + +func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { + panic("not implemented") +} + +// AllowUnexported returns an [Option] that allows [Equal] to forcibly introspect +// unexported fields of the specified struct types. +// +// See [Exporter] for the proper use of this option. +func AllowUnexported(types ...interface{}) Option { + m := make(map[reflect.Type]bool) + for _, typ := range types { + t := reflect.TypeOf(typ) + if t.Kind() != reflect.Struct { + panic(fmt.Sprintf("invalid struct type: %T", typ)) + } + m[t] = true + } + return exporter(func(t reflect.Type) bool { return m[t] }) +} + +// Result represents the comparison result for a single node and +// is provided by cmp when calling Report (see [Reporter]). +type Result struct { + _ [0]func() // Make Result incomparable + flags resultFlags +} + +// Equal reports whether the node was determined to be equal or not. +// As a special case, ignored nodes are considered equal. +func (r Result) Equal() bool { + return r.flags&(reportEqual|reportByIgnore) != 0 +} + +// ByIgnore reports whether the node is equal because it was ignored. +// This never reports true if [Result.Equal] reports false. +func (r Result) ByIgnore() bool { + return r.flags&reportByIgnore != 0 +} + +// ByMethod reports whether the Equal method determined equality. +func (r Result) ByMethod() bool { + return r.flags&reportByMethod != 0 +} + +// ByFunc reports whether a [Comparer] function determined equality. +func (r Result) ByFunc() bool { + return r.flags&reportByFunc != 0 +} + +// ByCycle reports whether a reference cycle was detected. +func (r Result) ByCycle() bool { + return r.flags&reportByCycle != 0 +} + +type resultFlags uint + +const ( + _ resultFlags = (1 << iota) / 2 + + reportEqual + reportUnequal + reportByIgnore + reportByMethod + reportByFunc + reportByCycle +) + +// Reporter is an [Option] that can be passed to [Equal]. When [Equal] traverses +// the value trees, it calls PushStep as it descends into each node in the +// tree and PopStep as it ascend out of the node. The leaves of the tree are +// either compared (determined to be equal or not equal) or ignored and reported +// as such by calling the Report method. +func Reporter(r interface { + // PushStep is called when a tree-traversal operation is performed. + // The PathStep itself is only valid until the step is popped. + // The PathStep.Values are valid for the duration of the entire traversal + // and must not be mutated. + // + // Equal always calls PushStep at the start to provide an operation-less + // PathStep used to report the root values. + // + // Within a slice, the exact set of inserted, removed, or modified elements + // is unspecified and may change in future implementations. + // The entries of a map are iterated through in an unspecified order. + PushStep(PathStep) + + // Report is called exactly once on leaf nodes to report whether the + // comparison identified the node as equal, unequal, or ignored. + // A leaf node is one that is immediately preceded by and followed by + // a pair of PushStep and PopStep calls. + Report(Result) + + // PopStep ascends back up the value tree. + // There is always a matching pop call for every push call. + PopStep() +}) Option { + return reporter{r} +} + +type reporter struct{ reporterIface } +type reporterIface interface { + PushStep(PathStep) + Report(Result) + PopStep() +} + +func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { + panic("not implemented") +} + +// normalizeOption normalizes the input options such that all Options groups +// are flattened and groups with a single element are reduced to that element. +// Only coreOptions and Options containing coreOptions are allowed. +func normalizeOption(src Option) Option { + switch opts := flattenOptions(nil, Options{src}); len(opts) { + case 0: + return nil + case 1: + return opts[0] + default: + return opts + } +} + +// flattenOptions copies all options in src to dst as a flat list. +// Only coreOptions and Options containing coreOptions are allowed. +func flattenOptions(dst, src Options) Options { + for _, opt := range src { + switch opt := opt.(type) { + case nil: + continue + case Options: + dst = flattenOptions(dst, opt) + case coreOption: + dst = append(dst, opt) + default: + panic(fmt.Sprintf("invalid option type: %T", opt)) + } + } + return dst +} diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go new file mode 100644 index 0000000..c3c1456 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/path.go @@ -0,0 +1,390 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "fmt" + "reflect" + "strings" + "unicode" + "unicode/utf8" + + "github.com/google/go-cmp/cmp/internal/value" +) + +// Path is a list of [PathStep] describing the sequence of operations to get +// from some root type to the current position in the value tree. +// The first Path element is always an operation-less [PathStep] that exists +// simply to identify the initial type. +// +// When traversing structs with embedded structs, the embedded struct will +// always be accessed as a field before traversing the fields of the +// embedded struct themselves. That is, an exported field from the +// embedded struct will never be accessed directly from the parent struct. +type Path []PathStep + +// PathStep is a union-type for specific operations to traverse +// a value's tree structure. Users of this package never need to implement +// these types as values of this type will be returned by this package. +// +// Implementations of this interface: +// - [StructField] +// - [SliceIndex] +// - [MapIndex] +// - [Indirect] +// - [TypeAssertion] +// - [Transform] +type PathStep interface { + String() string + + // Type is the resulting type after performing the path step. + Type() reflect.Type + + // Values is the resulting values after performing the path step. + // The type of each valid value is guaranteed to be identical to Type. + // + // In some cases, one or both may be invalid or have restrictions: + // - For StructField, both are not interface-able if the current field + // is unexported and the struct type is not explicitly permitted by + // an Exporter to traverse unexported fields. + // - For SliceIndex, one may be invalid if an element is missing from + // either the x or y slice. + // - For MapIndex, one may be invalid if an entry is missing from + // either the x or y map. + // + // The provided values must not be mutated. + Values() (vx, vy reflect.Value) +} + +var ( + _ PathStep = StructField{} + _ PathStep = SliceIndex{} + _ PathStep = MapIndex{} + _ PathStep = Indirect{} + _ PathStep = TypeAssertion{} + _ PathStep = Transform{} +) + +func (pa *Path) push(s PathStep) { + *pa = append(*pa, s) +} + +func (pa *Path) pop() { + *pa = (*pa)[:len(*pa)-1] +} + +// Last returns the last [PathStep] in the Path. +// If the path is empty, this returns a non-nil [PathStep] +// that reports a nil [PathStep.Type]. +func (pa Path) Last() PathStep { + return pa.Index(-1) +} + +// Index returns the ith step in the Path and supports negative indexing. +// A negative index starts counting from the tail of the Path such that -1 +// refers to the last step, -2 refers to the second-to-last step, and so on. +// If index is invalid, this returns a non-nil [PathStep] +// that reports a nil [PathStep.Type]. +func (pa Path) Index(i int) PathStep { + if i < 0 { + i = len(pa) + i + } + if i < 0 || i >= len(pa) { + return pathStep{} + } + return pa[i] +} + +// String returns the simplified path to a node. +// The simplified path only contains struct field accesses. +// +// For example: +// +// MyMap.MySlices.MyField +func (pa Path) String() string { + var ss []string + for _, s := range pa { + if _, ok := s.(StructField); ok { + ss = append(ss, s.String()) + } + } + return strings.TrimPrefix(strings.Join(ss, ""), ".") +} + +// GoString returns the path to a specific node using Go syntax. +// +// For example: +// +// (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField +func (pa Path) GoString() string { + var ssPre, ssPost []string + var numIndirect int + for i, s := range pa { + var nextStep PathStep + if i+1 < len(pa) { + nextStep = pa[i+1] + } + switch s := s.(type) { + case Indirect: + numIndirect++ + pPre, pPost := "(", ")" + switch nextStep.(type) { + case Indirect: + continue // Next step is indirection, so let them batch up + case StructField: + numIndirect-- // Automatic indirection on struct fields + case nil: + pPre, pPost = "", "" // Last step; no need for parenthesis + } + if numIndirect > 0 { + ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect)) + ssPost = append(ssPost, pPost) + } + numIndirect = 0 + continue + case Transform: + ssPre = append(ssPre, s.trans.name+"(") + ssPost = append(ssPost, ")") + continue + } + ssPost = append(ssPost, s.String()) + } + for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 { + ssPre[i], ssPre[j] = ssPre[j], ssPre[i] + } + return strings.Join(ssPre, "") + strings.Join(ssPost, "") +} + +type pathStep struct { + typ reflect.Type + vx, vy reflect.Value +} + +func (ps pathStep) Type() reflect.Type { return ps.typ } +func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy } +func (ps pathStep) String() string { + if ps.typ == nil { + return "" + } + s := value.TypeString(ps.typ, false) + if s == "" || strings.ContainsAny(s, "{}\n") { + return "root" // Type too simple or complex to print + } + return fmt.Sprintf("{%s}", s) +} + +// StructField is a [PathStep] that represents a struct field access +// on a field called [StructField.Name]. +type StructField struct{ *structField } +type structField struct { + pathStep + name string + idx int + + // These fields are used for forcibly accessing an unexported field. + // pvx, pvy, and field are only valid if unexported is true. + unexported bool + mayForce bool // Forcibly allow visibility + paddr bool // Was parent addressable? + pvx, pvy reflect.Value // Parent values (always addressable) + field reflect.StructField // Field information +} + +func (sf StructField) Type() reflect.Type { return sf.typ } +func (sf StructField) Values() (vx, vy reflect.Value) { + if !sf.unexported { + return sf.vx, sf.vy // CanInterface reports true + } + + // Forcibly obtain read-write access to an unexported struct field. + if sf.mayForce { + vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr) + vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr) + return vx, vy // CanInterface reports true + } + return sf.vx, sf.vy // CanInterface reports false +} +func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) } + +// Name is the field name. +func (sf StructField) Name() string { return sf.name } + +// Index is the index of the field in the parent struct type. +// See [reflect.Type.Field]. +func (sf StructField) Index() int { return sf.idx } + +// SliceIndex is a [PathStep] that represents an index operation on +// a slice or array at some index [SliceIndex.Key]. +type SliceIndex struct{ *sliceIndex } +type sliceIndex struct { + pathStep + xkey, ykey int + isSlice bool // False for reflect.Array +} + +func (si SliceIndex) Type() reflect.Type { return si.typ } +func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy } +func (si SliceIndex) String() string { + switch { + case si.xkey == si.ykey: + return fmt.Sprintf("[%d]", si.xkey) + case si.ykey == -1: + // [5->?] means "I don't know where X[5] went" + return fmt.Sprintf("[%d->?]", si.xkey) + case si.xkey == -1: + // [?->3] means "I don't know where Y[3] came from" + return fmt.Sprintf("[?->%d]", si.ykey) + default: + // [5->3] means "X[5] moved to Y[3]" + return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey) + } +} + +// Key is the index key; it may return -1 if in a split state +func (si SliceIndex) Key() int { + if si.xkey != si.ykey { + return -1 + } + return si.xkey +} + +// SplitKeys are the indexes for indexing into slices in the +// x and y values, respectively. These indexes may differ due to the +// insertion or removal of an element in one of the slices, causing +// all of the indexes to be shifted. If an index is -1, then that +// indicates that the element does not exist in the associated slice. +// +// [SliceIndex.Key] is guaranteed to return -1 if and only if the indexes +// returned by SplitKeys are not the same. SplitKeys will never return -1 for +// both indexes. +func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey } + +// MapIndex is a [PathStep] that represents an index operation on a map at some index Key. +type MapIndex struct{ *mapIndex } +type mapIndex struct { + pathStep + key reflect.Value +} + +func (mi MapIndex) Type() reflect.Type { return mi.typ } +func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy } +func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) } + +// Key is the value of the map key. +func (mi MapIndex) Key() reflect.Value { return mi.key } + +// Indirect is a [PathStep] that represents pointer indirection on the parent type. +type Indirect struct{ *indirect } +type indirect struct { + pathStep +} + +func (in Indirect) Type() reflect.Type { return in.typ } +func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy } +func (in Indirect) String() string { return "*" } + +// TypeAssertion is a [PathStep] that represents a type assertion on an interface. +type TypeAssertion struct{ *typeAssertion } +type typeAssertion struct { + pathStep +} + +func (ta TypeAssertion) Type() reflect.Type { return ta.typ } +func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy } +func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", value.TypeString(ta.typ, false)) } + +// Transform is a [PathStep] that represents a transformation +// from the parent type to the current type. +type Transform struct{ *transform } +type transform struct { + pathStep + trans *transformer +} + +func (tf Transform) Type() reflect.Type { return tf.typ } +func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy } +func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } + +// Name is the name of the [Transformer]. +func (tf Transform) Name() string { return tf.trans.name } + +// Func is the function pointer to the transformer function. +func (tf Transform) Func() reflect.Value { return tf.trans.fnc } + +// Option returns the originally constructed [Transformer] option. +// The == operator can be used to detect the exact option used. +func (tf Transform) Option() Option { return tf.trans } + +// pointerPath represents a dual-stack of pointers encountered when +// recursively traversing the x and y values. This data structure supports +// detection of cycles and determining whether the cycles are equal. +// In Go, cycles can occur via pointers, slices, and maps. +// +// The pointerPath uses a map to represent a stack; where descension into a +// pointer pushes the address onto the stack, and ascension from a pointer +// pops the address from the stack. Thus, when traversing into a pointer from +// reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles +// by checking whether the pointer has already been visited. The cycle detection +// uses a separate stack for the x and y values. +// +// If a cycle is detected we need to determine whether the two pointers +// should be considered equal. The definition of equality chosen by Equal +// requires two graphs to have the same structure. To determine this, both the +// x and y values must have a cycle where the previous pointers were also +// encountered together as a pair. +// +// Semantically, this is equivalent to augmenting Indirect, SliceIndex, and +// MapIndex with pointer information for the x and y values. +// Suppose px and py are two pointers to compare, we then search the +// Path for whether px was ever encountered in the Path history of x, and +// similarly so with py. If either side has a cycle, the comparison is only +// equal if both px and py have a cycle resulting from the same PathStep. +// +// Using a map as a stack is more performant as we can perform cycle detection +// in O(1) instead of O(N) where N is len(Path). +type pointerPath struct { + // mx is keyed by x pointers, where the value is the associated y pointer. + mx map[value.Pointer]value.Pointer + // my is keyed by y pointers, where the value is the associated x pointer. + my map[value.Pointer]value.Pointer +} + +func (p *pointerPath) Init() { + p.mx = make(map[value.Pointer]value.Pointer) + p.my = make(map[value.Pointer]value.Pointer) +} + +// Push indicates intent to descend into pointers vx and vy where +// visited reports whether either has been seen before. If visited before, +// equal reports whether both pointers were encountered together. +// Pop must be called if and only if the pointers were never visited. +// +// The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map +// and be non-nil. +func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) { + px := value.PointerOf(vx) + py := value.PointerOf(vy) + _, ok1 := p.mx[px] + _, ok2 := p.my[py] + if ok1 || ok2 { + equal = p.mx[px] == py && p.my[py] == px // Pointers paired together + return equal, true + } + p.mx[px] = py + p.my[py] = px + return false, false +} + +// Pop ascends from pointers vx and vy. +func (p pointerPath) Pop(vx, vy reflect.Value) { + delete(p.mx, value.PointerOf(vx)) + delete(p.my, value.PointerOf(vy)) +} + +// isExported reports whether the identifier is exported. +func isExported(id string) bool { + r, _ := utf8.DecodeRuneInString(id) + return unicode.IsUpper(r) +} diff --git a/vendor/github.com/google/go-cmp/cmp/report.go b/vendor/github.com/google/go-cmp/cmp/report.go new file mode 100644 index 0000000..f43cd12 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report.go @@ -0,0 +1,54 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +// defaultReporter implements the reporter interface. +// +// As Equal serially calls the PushStep, Report, and PopStep methods, the +// defaultReporter constructs a tree-based representation of the compared value +// and the result of each comparison (see valueNode). +// +// When the String method is called, the FormatDiff method transforms the +// valueNode tree into a textNode tree, which is a tree-based representation +// of the textual output (see textNode). +// +// Lastly, the textNode.String method produces the final report as a string. +type defaultReporter struct { + root *valueNode + curr *valueNode +} + +func (r *defaultReporter) PushStep(ps PathStep) { + r.curr = r.curr.PushStep(ps) + if r.root == nil { + r.root = r.curr + } +} +func (r *defaultReporter) Report(rs Result) { + r.curr.Report(rs) +} +func (r *defaultReporter) PopStep() { + r.curr = r.curr.PopStep() +} + +// String provides a full report of the differences detected as a structured +// literal in pseudo-Go syntax. String may only be called after the entire tree +// has been traversed. +func (r *defaultReporter) String() string { + assert(r.root != nil && r.curr == nil) + if r.root.NumDiff == 0 { + return "" + } + ptrs := new(pointerReferences) + text := formatOptions{}.FormatDiff(r.root, ptrs) + resolveReferences(text) + return text.String() +} + +func assert(ok bool) { + if !ok { + panic("assertion failure") + } +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_compare.go b/vendor/github.com/google/go-cmp/cmp/report_compare.go new file mode 100644 index 0000000..2050bf6 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_compare.go @@ -0,0 +1,433 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "fmt" + "reflect" +) + +// numContextRecords is the number of surrounding equal records to print. +const numContextRecords = 2 + +type diffMode byte + +const ( + diffUnknown diffMode = 0 + diffIdentical diffMode = ' ' + diffRemoved diffMode = '-' + diffInserted diffMode = '+' +) + +type typeMode int + +const ( + // emitType always prints the type. + emitType typeMode = iota + // elideType never prints the type. + elideType + // autoType prints the type only for composite kinds + // (i.e., structs, slices, arrays, and maps). + autoType +) + +type formatOptions struct { + // DiffMode controls the output mode of FormatDiff. + // + // If diffUnknown, then produce a diff of the x and y values. + // If diffIdentical, then emit values as if they were equal. + // If diffRemoved, then only emit x values (ignoring y values). + // If diffInserted, then only emit y values (ignoring x values). + DiffMode diffMode + + // TypeMode controls whether to print the type for the current node. + // + // As a general rule of thumb, we always print the type of the next node + // after an interface, and always elide the type of the next node after + // a slice or map node. + TypeMode typeMode + + // formatValueOptions are options specific to printing reflect.Values. + formatValueOptions +} + +func (opts formatOptions) WithDiffMode(d diffMode) formatOptions { + opts.DiffMode = d + return opts +} +func (opts formatOptions) WithTypeMode(t typeMode) formatOptions { + opts.TypeMode = t + return opts +} +func (opts formatOptions) WithVerbosity(level int) formatOptions { + opts.VerbosityLevel = level + opts.LimitVerbosity = true + return opts +} +func (opts formatOptions) verbosity() uint { + switch { + case opts.VerbosityLevel < 0: + return 0 + case opts.VerbosityLevel > 16: + return 16 // some reasonable maximum to avoid shift overflow + default: + return uint(opts.VerbosityLevel) + } +} + +const maxVerbosityPreset = 6 + +// verbosityPreset modifies the verbosity settings given an index +// between 0 and maxVerbosityPreset, inclusive. +func verbosityPreset(opts formatOptions, i int) formatOptions { + opts.VerbosityLevel = int(opts.verbosity()) + 2*i + if i > 0 { + opts.AvoidStringer = true + } + if i >= maxVerbosityPreset { + opts.PrintAddresses = true + opts.QualifiedNames = true + } + return opts +} + +// FormatDiff converts a valueNode tree into a textNode tree, where the later +// is a textual representation of the differences detected in the former. +func (opts formatOptions) FormatDiff(v *valueNode, ptrs *pointerReferences) (out textNode) { + if opts.DiffMode == diffIdentical { + opts = opts.WithVerbosity(1) + } else if opts.verbosity() < 3 { + opts = opts.WithVerbosity(3) + } + + // Check whether we have specialized formatting for this node. + // This is not necessary, but helpful for producing more readable outputs. + if opts.CanFormatDiffSlice(v) { + return opts.FormatDiffSlice(v) + } + + var parentKind reflect.Kind + if v.parent != nil && v.parent.TransformerName == "" { + parentKind = v.parent.Type.Kind() + } + + // For leaf nodes, format the value based on the reflect.Values alone. + // As a special case, treat equal []byte as a leaf nodes. + isBytes := v.Type.Kind() == reflect.Slice && v.Type.Elem() == byteType + isEqualBytes := isBytes && v.NumDiff+v.NumIgnored+v.NumTransformed == 0 + if v.MaxDepth == 0 || isEqualBytes { + switch opts.DiffMode { + case diffUnknown, diffIdentical: + // Format Equal. + if v.NumDiff == 0 { + outx := opts.FormatValue(v.ValueX, parentKind, ptrs) + outy := opts.FormatValue(v.ValueY, parentKind, ptrs) + if v.NumIgnored > 0 && v.NumSame == 0 { + return textEllipsis + } else if outx.Len() < outy.Len() { + return outx + } else { + return outy + } + } + + // Format unequal. + assert(opts.DiffMode == diffUnknown) + var list textList + outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, parentKind, ptrs) + outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, parentKind, ptrs) + for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { + opts2 := verbosityPreset(opts, i).WithTypeMode(elideType) + outx = opts2.FormatValue(v.ValueX, parentKind, ptrs) + outy = opts2.FormatValue(v.ValueY, parentKind, ptrs) + } + if outx != nil { + list = append(list, textRecord{Diff: '-', Value: outx}) + } + if outy != nil { + list = append(list, textRecord{Diff: '+', Value: outy}) + } + return opts.WithTypeMode(emitType).FormatType(v.Type, list) + case diffRemoved: + return opts.FormatValue(v.ValueX, parentKind, ptrs) + case diffInserted: + return opts.FormatValue(v.ValueY, parentKind, ptrs) + default: + panic("invalid diff mode") + } + } + + // Register slice element to support cycle detection. + if parentKind == reflect.Slice { + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, true) + defer ptrs.Pop() + defer func() { out = wrapTrunkReferences(ptrRefs, out) }() + } + + // Descend into the child value node. + if v.TransformerName != "" { + out := opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) + out = &textWrap{Prefix: "Inverse(" + v.TransformerName + ", ", Value: out, Suffix: ")"} + return opts.FormatType(v.Type, out) + } else { + switch k := v.Type.Kind(); k { + case reflect.Struct, reflect.Array, reflect.Slice: + out = opts.formatDiffList(v.Records, k, ptrs) + out = opts.FormatType(v.Type, out) + case reflect.Map: + // Register map to support cycle detection. + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) + defer ptrs.Pop() + + out = opts.formatDiffList(v.Records, k, ptrs) + out = wrapTrunkReferences(ptrRefs, out) + out = opts.FormatType(v.Type, out) + case reflect.Ptr: + // Register pointer to support cycle detection. + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) + defer ptrs.Pop() + + out = opts.FormatDiff(v.Value, ptrs) + out = wrapTrunkReferences(ptrRefs, out) + out = &textWrap{Prefix: "&", Value: out} + case reflect.Interface: + out = opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) + default: + panic(fmt.Sprintf("%v cannot have children", k)) + } + return out + } +} + +func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind, ptrs *pointerReferences) textNode { + // Derive record name based on the data structure kind. + var name string + var formatKey func(reflect.Value) string + switch k { + case reflect.Struct: + name = "field" + opts = opts.WithTypeMode(autoType) + formatKey = func(v reflect.Value) string { return v.String() } + case reflect.Slice, reflect.Array: + name = "element" + opts = opts.WithTypeMode(elideType) + formatKey = func(reflect.Value) string { return "" } + case reflect.Map: + name = "entry" + opts = opts.WithTypeMode(elideType) + formatKey = func(v reflect.Value) string { return formatMapKey(v, false, ptrs) } + } + + maxLen := -1 + if opts.LimitVerbosity { + if opts.DiffMode == diffIdentical { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + } else { + maxLen = (1 << opts.verbosity()) << 1 // 2, 4, 8, 16, 32, 64, etc... + } + opts.VerbosityLevel-- + } + + // Handle unification. + switch opts.DiffMode { + case diffIdentical, diffRemoved, diffInserted: + var list textList + var deferredEllipsis bool // Add final "..." to indicate records were dropped + for _, r := range recs { + if len(list) == maxLen { + deferredEllipsis = true + break + } + + // Elide struct fields that are zero value. + if k == reflect.Struct { + var isZero bool + switch opts.DiffMode { + case diffIdentical: + isZero = r.Value.ValueX.IsZero() || r.Value.ValueY.IsZero() + case diffRemoved: + isZero = r.Value.ValueX.IsZero() + case diffInserted: + isZero = r.Value.ValueY.IsZero() + } + if isZero { + continue + } + } + // Elide ignored nodes. + if r.Value.NumIgnored > 0 && r.Value.NumSame+r.Value.NumDiff == 0 { + deferredEllipsis = !(k == reflect.Slice || k == reflect.Array) + if !deferredEllipsis { + list.AppendEllipsis(diffStats{}) + } + continue + } + if out := opts.FormatDiff(r.Value, ptrs); out != nil { + list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + } + } + if deferredEllipsis { + list.AppendEllipsis(diffStats{}) + } + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} + case diffUnknown: + default: + panic("invalid diff mode") + } + + // Handle differencing. + var numDiffs int + var list textList + var keys []reflect.Value // invariant: len(list) == len(keys) + groups := coalesceAdjacentRecords(name, recs) + maxGroup := diffStats{Name: name} + for i, ds := range groups { + if maxLen >= 0 && numDiffs >= maxLen { + maxGroup = maxGroup.Append(ds) + continue + } + + // Handle equal records. + if ds.NumDiff() == 0 { + // Compute the number of leading and trailing records to print. + var numLo, numHi int + numEqual := ds.NumIgnored + ds.NumIdentical + for numLo < numContextRecords && numLo+numHi < numEqual && i != 0 { + if r := recs[numLo].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { + break + } + numLo++ + } + for numHi < numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { + if r := recs[numEqual-numHi-1].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { + break + } + numHi++ + } + if numEqual-(numLo+numHi) == 1 && ds.NumIgnored == 0 { + numHi++ // Avoid pointless coalescing of a single equal record + } + + // Format the equal values. + for _, r := range recs[:numLo] { + out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) + list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) + } + if numEqual > numLo+numHi { + ds.NumIdentical -= numLo + numHi + list.AppendEllipsis(ds) + for len(keys) < len(list) { + keys = append(keys, reflect.Value{}) + } + } + for _, r := range recs[numEqual-numHi : numEqual] { + out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) + list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) + } + recs = recs[numEqual:] + continue + } + + // Handle unequal records. + for _, r := range recs[:ds.NumDiff()] { + switch { + case opts.CanFormatDiffSlice(r.Value): + out := opts.FormatDiffSlice(r.Value) + list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) + case r.Value.NumChildren == r.Value.MaxDepth: + outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) + outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) + for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { + opts2 := verbosityPreset(opts, i) + outx = opts2.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) + outy = opts2.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) + } + if outx != nil { + list = append(list, textRecord{Diff: diffRemoved, Key: formatKey(r.Key), Value: outx}) + keys = append(keys, r.Key) + } + if outy != nil { + list = append(list, textRecord{Diff: diffInserted, Key: formatKey(r.Key), Value: outy}) + keys = append(keys, r.Key) + } + default: + out := opts.FormatDiff(r.Value, ptrs) + list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) + } + } + recs = recs[ds.NumDiff():] + numDiffs += ds.NumDiff() + } + if maxGroup.IsZero() { + assert(len(recs) == 0) + } else { + list.AppendEllipsis(maxGroup) + for len(keys) < len(list) { + keys = append(keys, reflect.Value{}) + } + } + assert(len(list) == len(keys)) + + // For maps, the default formatting logic uses fmt.Stringer which may + // produce ambiguous output. Avoid calling String to disambiguate. + if k == reflect.Map { + var ambiguous bool + seenKeys := map[string]reflect.Value{} + for i, currKey := range keys { + if currKey.IsValid() { + strKey := list[i].Key + prevKey, seen := seenKeys[strKey] + if seen && prevKey.CanInterface() && currKey.CanInterface() { + ambiguous = prevKey.Interface() != currKey.Interface() + if ambiguous { + break + } + } + seenKeys[strKey] = currKey + } + } + if ambiguous { + for i, k := range keys { + if k.IsValid() { + list[i].Key = formatMapKey(k, true, ptrs) + } + } + } + } + + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} +} + +// coalesceAdjacentRecords coalesces the list of records into groups of +// adjacent equal, or unequal counts. +func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) { + var prevCase int // Arbitrary index into which case last occurred + lastStats := func(i int) *diffStats { + if prevCase != i { + groups = append(groups, diffStats{Name: name}) + prevCase = i + } + return &groups[len(groups)-1] + } + for _, r := range recs { + switch rv := r.Value; { + case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0: + lastStats(1).NumIgnored++ + case rv.NumDiff == 0: + lastStats(1).NumIdentical++ + case rv.NumDiff > 0 && !rv.ValueY.IsValid(): + lastStats(2).NumRemoved++ + case rv.NumDiff > 0 && !rv.ValueX.IsValid(): + lastStats(2).NumInserted++ + default: + lastStats(2).NumModified++ + } + } + return groups +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_references.go b/vendor/github.com/google/go-cmp/cmp/report_references.go new file mode 100644 index 0000000..be31b33 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_references.go @@ -0,0 +1,264 @@ +// Copyright 2020, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "fmt" + "reflect" + "strings" + + "github.com/google/go-cmp/cmp/internal/flags" + "github.com/google/go-cmp/cmp/internal/value" +) + +const ( + pointerDelimPrefix = "⟪" + pointerDelimSuffix = "⟫" +) + +// formatPointer prints the address of the pointer. +func formatPointer(p value.Pointer, withDelims bool) string { + v := p.Uintptr() + if flags.Deterministic { + v = 0xdeadf00f // Only used for stable testing purposes + } + if withDelims { + return pointerDelimPrefix + formatHex(uint64(v)) + pointerDelimSuffix + } + return formatHex(uint64(v)) +} + +// pointerReferences is a stack of pointers visited so far. +type pointerReferences [][2]value.Pointer + +func (ps *pointerReferences) PushPair(vx, vy reflect.Value, d diffMode, deref bool) (pp [2]value.Pointer) { + if deref && vx.IsValid() { + vx = vx.Addr() + } + if deref && vy.IsValid() { + vy = vy.Addr() + } + switch d { + case diffUnknown, diffIdentical: + pp = [2]value.Pointer{value.PointerOf(vx), value.PointerOf(vy)} + case diffRemoved: + pp = [2]value.Pointer{value.PointerOf(vx), value.Pointer{}} + case diffInserted: + pp = [2]value.Pointer{value.Pointer{}, value.PointerOf(vy)} + } + *ps = append(*ps, pp) + return pp +} + +func (ps *pointerReferences) Push(v reflect.Value) (p value.Pointer, seen bool) { + p = value.PointerOf(v) + for _, pp := range *ps { + if p == pp[0] || p == pp[1] { + return p, true + } + } + *ps = append(*ps, [2]value.Pointer{p, p}) + return p, false +} + +func (ps *pointerReferences) Pop() { + *ps = (*ps)[:len(*ps)-1] +} + +// trunkReferences is metadata for a textNode indicating that the sub-tree +// represents the value for either pointer in a pair of references. +type trunkReferences struct{ pp [2]value.Pointer } + +// trunkReference is metadata for a textNode indicating that the sub-tree +// represents the value for the given pointer reference. +type trunkReference struct{ p value.Pointer } + +// leafReference is metadata for a textNode indicating that the value is +// truncated as it refers to another part of the tree (i.e., a trunk). +type leafReference struct{ p value.Pointer } + +func wrapTrunkReferences(pp [2]value.Pointer, s textNode) textNode { + switch { + case pp[0].IsNil(): + return &textWrap{Value: s, Metadata: trunkReference{pp[1]}} + case pp[1].IsNil(): + return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} + case pp[0] == pp[1]: + return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} + default: + return &textWrap{Value: s, Metadata: trunkReferences{pp}} + } +} +func wrapTrunkReference(p value.Pointer, printAddress bool, s textNode) textNode { + var prefix string + if printAddress { + prefix = formatPointer(p, true) + } + return &textWrap{Prefix: prefix, Value: s, Metadata: trunkReference{p}} +} +func makeLeafReference(p value.Pointer, printAddress bool) textNode { + out := &textWrap{Prefix: "(", Value: textEllipsis, Suffix: ")"} + var prefix string + if printAddress { + prefix = formatPointer(p, true) + } + return &textWrap{Prefix: prefix, Value: out, Metadata: leafReference{p}} +} + +// resolveReferences walks the textNode tree searching for any leaf reference +// metadata and resolves each against the corresponding trunk references. +// Since pointer addresses in memory are not particularly readable to the user, +// it replaces each pointer value with an arbitrary and unique reference ID. +func resolveReferences(s textNode) { + var walkNodes func(textNode, func(textNode)) + walkNodes = func(s textNode, f func(textNode)) { + f(s) + switch s := s.(type) { + case *textWrap: + walkNodes(s.Value, f) + case textList: + for _, r := range s { + walkNodes(r.Value, f) + } + } + } + + // Collect all trunks and leaves with reference metadata. + var trunks, leaves []*textWrap + walkNodes(s, func(s textNode) { + if s, ok := s.(*textWrap); ok { + switch s.Metadata.(type) { + case leafReference: + leaves = append(leaves, s) + case trunkReference, trunkReferences: + trunks = append(trunks, s) + } + } + }) + + // No leaf references to resolve. + if len(leaves) == 0 { + return + } + + // Collect the set of all leaf references to resolve. + leafPtrs := make(map[value.Pointer]bool) + for _, leaf := range leaves { + leafPtrs[leaf.Metadata.(leafReference).p] = true + } + + // Collect the set of trunk pointers that are always paired together. + // This allows us to assign a single ID to both pointers for brevity. + // If a pointer in a pair ever occurs by itself or as a different pair, + // then the pair is broken. + pairedTrunkPtrs := make(map[value.Pointer]value.Pointer) + unpair := func(p value.Pointer) { + if !pairedTrunkPtrs[p].IsNil() { + pairedTrunkPtrs[pairedTrunkPtrs[p]] = value.Pointer{} // invalidate other half + } + pairedTrunkPtrs[p] = value.Pointer{} // invalidate this half + } + for _, trunk := range trunks { + switch p := trunk.Metadata.(type) { + case trunkReference: + unpair(p.p) // standalone pointer cannot be part of a pair + case trunkReferences: + p0, ok0 := pairedTrunkPtrs[p.pp[0]] + p1, ok1 := pairedTrunkPtrs[p.pp[1]] + switch { + case !ok0 && !ok1: + // Register the newly seen pair. + pairedTrunkPtrs[p.pp[0]] = p.pp[1] + pairedTrunkPtrs[p.pp[1]] = p.pp[0] + case ok0 && ok1 && p0 == p.pp[1] && p1 == p.pp[0]: + // Exact pair already seen; do nothing. + default: + // Pair conflicts with some other pair; break all pairs. + unpair(p.pp[0]) + unpair(p.pp[1]) + } + } + } + + // Correlate each pointer referenced by leaves to a unique identifier, + // and print the IDs for each trunk that matches those pointers. + var nextID uint + ptrIDs := make(map[value.Pointer]uint) + newID := func() uint { + id := nextID + nextID++ + return id + } + for _, trunk := range trunks { + switch p := trunk.Metadata.(type) { + case trunkReference: + if print := leafPtrs[p.p]; print { + id, ok := ptrIDs[p.p] + if !ok { + id = newID() + ptrIDs[p.p] = id + } + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) + } + case trunkReferences: + print0 := leafPtrs[p.pp[0]] + print1 := leafPtrs[p.pp[1]] + if print0 || print1 { + id0, ok0 := ptrIDs[p.pp[0]] + id1, ok1 := ptrIDs[p.pp[1]] + isPair := pairedTrunkPtrs[p.pp[0]] == p.pp[1] && pairedTrunkPtrs[p.pp[1]] == p.pp[0] + if isPair { + var id uint + assert(ok0 == ok1) // must be seen together or not at all + if ok0 { + assert(id0 == id1) // must have the same ID + id = id0 + } else { + id = newID() + ptrIDs[p.pp[0]] = id + ptrIDs[p.pp[1]] = id + } + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) + } else { + if print0 && !ok0 { + id0 = newID() + ptrIDs[p.pp[0]] = id0 + } + if print1 && !ok1 { + id1 = newID() + ptrIDs[p.pp[1]] = id1 + } + switch { + case print0 && print1: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)+","+formatReference(id1)) + case print0: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)) + case print1: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id1)) + } + } + } + } + } + + // Update all leaf references with the unique identifier. + for _, leaf := range leaves { + if id, ok := ptrIDs[leaf.Metadata.(leafReference).p]; ok { + leaf.Prefix = updateReferencePrefix(leaf.Prefix, formatReference(id)) + } + } +} + +func formatReference(id uint) string { + return fmt.Sprintf("ref#%d", id) +} + +func updateReferencePrefix(prefix, ref string) string { + if prefix == "" { + return pointerDelimPrefix + ref + pointerDelimSuffix + } + suffix := strings.TrimPrefix(prefix, pointerDelimPrefix) + return pointerDelimPrefix + ref + ": " + suffix +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_reflect.go b/vendor/github.com/google/go-cmp/cmp/report_reflect.go new file mode 100644 index 0000000..e39f422 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_reflect.go @@ -0,0 +1,414 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/google/go-cmp/cmp/internal/value" +) + +var ( + anyType = reflect.TypeOf((*interface{})(nil)).Elem() + stringType = reflect.TypeOf((*string)(nil)).Elem() + bytesType = reflect.TypeOf((*[]byte)(nil)).Elem() + byteType = reflect.TypeOf((*byte)(nil)).Elem() +) + +type formatValueOptions struct { + // AvoidStringer controls whether to avoid calling custom stringer + // methods like error.Error or fmt.Stringer.String. + AvoidStringer bool + + // PrintAddresses controls whether to print the address of all pointers, + // slice elements, and maps. + PrintAddresses bool + + // QualifiedNames controls whether FormatType uses the fully qualified name + // (including the full package path as opposed to just the package name). + QualifiedNames bool + + // VerbosityLevel controls the amount of output to produce. + // A higher value produces more output. A value of zero or lower produces + // no output (represented using an ellipsis). + // If LimitVerbosity is false, then the level is treated as infinite. + VerbosityLevel int + + // LimitVerbosity specifies that formatting should respect VerbosityLevel. + LimitVerbosity bool +} + +// FormatType prints the type as if it were wrapping s. +// This may return s as-is depending on the current type and TypeMode mode. +func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode { + // Check whether to emit the type or not. + switch opts.TypeMode { + case autoType: + switch t.Kind() { + case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map: + if s.Equal(textNil) { + return s + } + default: + return s + } + if opts.DiffMode == diffIdentical { + return s // elide type for identical nodes + } + case elideType: + return s + } + + // Determine the type label, applying special handling for unnamed types. + typeName := value.TypeString(t, opts.QualifiedNames) + if t.Name() == "" { + // According to Go grammar, certain type literals contain symbols that + // do not strongly bind to the next lexicographical token (e.g., *T). + switch t.Kind() { + case reflect.Chan, reflect.Func, reflect.Ptr: + typeName = "(" + typeName + ")" + } + } + return &textWrap{Prefix: typeName, Value: wrapParens(s)} +} + +// wrapParens wraps s with a set of parenthesis, but avoids it if the +// wrapped node itself is already surrounded by a pair of parenthesis or braces. +// It handles unwrapping one level of pointer-reference nodes. +func wrapParens(s textNode) textNode { + var refNode *textWrap + if s2, ok := s.(*textWrap); ok { + // Unwrap a single pointer reference node. + switch s2.Metadata.(type) { + case leafReference, trunkReference, trunkReferences: + refNode = s2 + if s3, ok := refNode.Value.(*textWrap); ok { + s2 = s3 + } + } + + // Already has delimiters that make parenthesis unnecessary. + hasParens := strings.HasPrefix(s2.Prefix, "(") && strings.HasSuffix(s2.Suffix, ")") + hasBraces := strings.HasPrefix(s2.Prefix, "{") && strings.HasSuffix(s2.Suffix, "}") + if hasParens || hasBraces { + return s + } + } + if refNode != nil { + refNode.Value = &textWrap{Prefix: "(", Value: refNode.Value, Suffix: ")"} + return s + } + return &textWrap{Prefix: "(", Value: s, Suffix: ")"} +} + +// FormatValue prints the reflect.Value, taking extra care to avoid descending +// into pointers already in ptrs. As pointers are visited, ptrs is also updated. +func (opts formatOptions) FormatValue(v reflect.Value, parentKind reflect.Kind, ptrs *pointerReferences) (out textNode) { + if !v.IsValid() { + return nil + } + t := v.Type() + + // Check slice element for cycles. + if parentKind == reflect.Slice { + ptrRef, visited := ptrs.Push(v.Addr()) + if visited { + return makeLeafReference(ptrRef, false) + } + defer ptrs.Pop() + defer func() { out = wrapTrunkReference(ptrRef, false, out) }() + } + + // Check whether there is an Error or String method to call. + if !opts.AvoidStringer && v.CanInterface() { + // Avoid calling Error or String methods on nil receivers since many + // implementations crash when doing so. + if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() { + var prefix, strVal string + func() { + // Swallow and ignore any panics from String or Error. + defer func() { recover() }() + switch v := v.Interface().(type) { + case error: + strVal = v.Error() + prefix = "e" + case fmt.Stringer: + strVal = v.String() + prefix = "s" + } + }() + if prefix != "" { + return opts.formatString(prefix, strVal) + } + } + } + + // Check whether to explicitly wrap the result with the type. + var skipType bool + defer func() { + if !skipType { + out = opts.FormatType(t, out) + } + }() + + switch t.Kind() { + case reflect.Bool: + return textLine(fmt.Sprint(v.Bool())) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return textLine(fmt.Sprint(v.Int())) + case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return textLine(fmt.Sprint(v.Uint())) + case reflect.Uint8: + if parentKind == reflect.Slice || parentKind == reflect.Array { + return textLine(formatHex(v.Uint())) + } + return textLine(fmt.Sprint(v.Uint())) + case reflect.Uintptr: + return textLine(formatHex(v.Uint())) + case reflect.Float32, reflect.Float64: + return textLine(fmt.Sprint(v.Float())) + case reflect.Complex64, reflect.Complex128: + return textLine(fmt.Sprint(v.Complex())) + case reflect.String: + return opts.formatString("", v.String()) + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + return textLine(formatPointer(value.PointerOf(v), true)) + case reflect.Struct: + var list textList + v := makeAddressable(v) // needed for retrieveUnexportedField + maxLen := v.NumField() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } + for i := 0; i < v.NumField(); i++ { + vv := v.Field(i) + if vv.IsZero() { + continue // Elide fields with zero values + } + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break + } + sf := t.Field(i) + if !isExported(sf.Name) { + vv = retrieveUnexportedField(v, sf, true) + } + s := opts.WithTypeMode(autoType).FormatValue(vv, t.Kind(), ptrs) + list = append(list, textRecord{Key: sf.Name, Value: s}) + } + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} + case reflect.Slice: + if v.IsNil() { + return textNil + } + + // Check whether this is a []byte of text data. + if t.Elem() == byteType { + b := v.Bytes() + isPrintSpace := func(r rune) bool { return unicode.IsPrint(r) || unicode.IsSpace(r) } + if len(b) > 0 && utf8.Valid(b) && len(bytes.TrimFunc(b, isPrintSpace)) == 0 { + out = opts.formatString("", string(b)) + skipType = true + return opts.FormatType(t, out) + } + } + + fallthrough + case reflect.Array: + maxLen := v.Len() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } + var list textList + for i := 0; i < v.Len(); i++ { + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break + } + s := opts.WithTypeMode(elideType).FormatValue(v.Index(i), t.Kind(), ptrs) + list = append(list, textRecord{Value: s}) + } + + out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} + if t.Kind() == reflect.Slice && opts.PrintAddresses { + header := fmt.Sprintf("ptr:%v, len:%d, cap:%d", formatPointer(value.PointerOf(v), false), v.Len(), v.Cap()) + out = &textWrap{Prefix: pointerDelimPrefix + header + pointerDelimSuffix, Value: out} + } + return out + case reflect.Map: + if v.IsNil() { + return textNil + } + + // Check pointer for cycles. + ptrRef, visited := ptrs.Push(v) + if visited { + return makeLeafReference(ptrRef, opts.PrintAddresses) + } + defer ptrs.Pop() + + maxLen := v.Len() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } + var list textList + for _, k := range value.SortKeys(v.MapKeys()) { + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break + } + sk := formatMapKey(k, false, ptrs) + sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), t.Kind(), ptrs) + list = append(list, textRecord{Key: sk, Value: sv}) + } + + out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} + out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) + return out + case reflect.Ptr: + if v.IsNil() { + return textNil + } + + // Check pointer for cycles. + ptrRef, visited := ptrs.Push(v) + if visited { + out = makeLeafReference(ptrRef, opts.PrintAddresses) + return &textWrap{Prefix: "&", Value: out} + } + defer ptrs.Pop() + + // Skip the name only if this is an unnamed pointer type. + // Otherwise taking the address of a value does not reproduce + // the named pointer type. + if v.Type().Name() == "" { + skipType = true // Let the underlying value print the type instead + } + out = opts.FormatValue(v.Elem(), t.Kind(), ptrs) + out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) + out = &textWrap{Prefix: "&", Value: out} + return out + case reflect.Interface: + if v.IsNil() { + return textNil + } + // Interfaces accept different concrete types, + // so configure the underlying value to explicitly print the type. + return opts.WithTypeMode(emitType).FormatValue(v.Elem(), t.Kind(), ptrs) + default: + panic(fmt.Sprintf("%v kind not handled", v.Kind())) + } +} + +func (opts formatOptions) formatString(prefix, s string) textNode { + maxLen := len(s) + maxLines := strings.Count(s, "\n") + 1 + if opts.LimitVerbosity { + maxLen = (1 << opts.verbosity()) << 5 // 32, 64, 128, 256, etc... + maxLines = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc... + } + + // For multiline strings, use the triple-quote syntax, + // but only use it when printing removed or inserted nodes since + // we only want the extra verbosity for those cases. + lines := strings.Split(strings.TrimSuffix(s, "\n"), "\n") + isTripleQuoted := len(lines) >= 4 && (opts.DiffMode == '-' || opts.DiffMode == '+') + for i := 0; i < len(lines) && isTripleQuoted; i++ { + lines[i] = strings.TrimPrefix(strings.TrimSuffix(lines[i], "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support + isPrintable := func(r rune) bool { + return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable + } + line := lines[i] + isTripleQuoted = !strings.HasPrefix(strings.TrimPrefix(line, prefix), `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" && len(line) <= maxLen + } + if isTripleQuoted { + var list textList + list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true}) + for i, line := range lines { + if numElided := len(lines) - i; i == maxLines-1 && numElided > 1 { + comment := commentString(fmt.Sprintf("%d elided lines", numElided)) + list = append(list, textRecord{Diff: opts.DiffMode, Value: textEllipsis, ElideComma: true, Comment: comment}) + break + } + list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(line), ElideComma: true}) + } + list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true}) + return &textWrap{Prefix: "(", Value: list, Suffix: ")"} + } + + // Format the string as a single-line quoted string. + if len(s) > maxLen+len(textEllipsis) { + return textLine(prefix + formatString(s[:maxLen]) + string(textEllipsis)) + } + return textLine(prefix + formatString(s)) +} + +// formatMapKey formats v as if it were a map key. +// The result is guaranteed to be a single line. +func formatMapKey(v reflect.Value, disambiguate bool, ptrs *pointerReferences) string { + var opts formatOptions + opts.DiffMode = diffIdentical + opts.TypeMode = elideType + opts.PrintAddresses = disambiguate + opts.AvoidStringer = disambiguate + opts.QualifiedNames = disambiguate + opts.VerbosityLevel = maxVerbosityPreset + opts.LimitVerbosity = true + s := opts.FormatValue(v, reflect.Map, ptrs).String() + return strings.TrimSpace(s) +} + +// formatString prints s as a double-quoted or backtick-quoted string. +func formatString(s string) string { + // Use quoted string if it the same length as a raw string literal. + // Otherwise, attempt to use the raw string form. + qs := strconv.Quote(s) + if len(qs) == 1+len(s)+1 { + return qs + } + + // Disallow newlines to ensure output is a single line. + // Only allow printable runes for readability purposes. + rawInvalid := func(r rune) bool { + return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t') + } + if utf8.ValidString(s) && strings.IndexFunc(s, rawInvalid) < 0 { + return "`" + s + "`" + } + return qs +} + +// formatHex prints u as a hexadecimal integer in Go notation. +func formatHex(u uint64) string { + var f string + switch { + case u <= 0xff: + f = "0x%02x" + case u <= 0xffff: + f = "0x%04x" + case u <= 0xffffff: + f = "0x%06x" + case u <= 0xffffffff: + f = "0x%08x" + case u <= 0xffffffffff: + f = "0x%010x" + case u <= 0xffffffffffff: + f = "0x%012x" + case u <= 0xffffffffffffff: + f = "0x%014x" + case u <= 0xffffffffffffffff: + f = "0x%016x" + } + return fmt.Sprintf(f, u) +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_slices.go b/vendor/github.com/google/go-cmp/cmp/report_slices.go new file mode 100644 index 0000000..23e444f --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_slices.go @@ -0,0 +1,614 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "bytes" + "fmt" + "math" + "reflect" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/google/go-cmp/cmp/internal/diff" +) + +// CanFormatDiffSlice reports whether we support custom formatting for nodes +// that are slices of primitive kinds or strings. +func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool { + switch { + case opts.DiffMode != diffUnknown: + return false // Must be formatting in diff mode + case v.NumDiff == 0: + return false // No differences detected + case !v.ValueX.IsValid() || !v.ValueY.IsValid(): + return false // Both values must be valid + case v.NumIgnored > 0: + return false // Some ignore option was used + case v.NumTransformed > 0: + return false // Some transform option was used + case v.NumCompared > 1: + return false // More than one comparison was used + case v.NumCompared == 1 && v.Type.Name() != "": + // The need for cmp to check applicability of options on every element + // in a slice is a significant performance detriment for large []byte. + // The workaround is to specify Comparer(bytes.Equal), + // which enables cmp to compare []byte more efficiently. + // If they differ, we still want to provide batched diffing. + // The logic disallows named types since they tend to have their own + // String method, with nicer formatting than what this provides. + return false + } + + // Check whether this is an interface with the same concrete types. + t := v.Type + vx, vy := v.ValueX, v.ValueY + if t.Kind() == reflect.Interface && !vx.IsNil() && !vy.IsNil() && vx.Elem().Type() == vy.Elem().Type() { + vx, vy = vx.Elem(), vy.Elem() + t = vx.Type() + } + + // Check whether we provide specialized diffing for this type. + switch t.Kind() { + case reflect.String: + case reflect.Array, reflect.Slice: + // Only slices of primitive types have specialized handling. + switch t.Elem().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + default: + return false + } + + // Both slice values have to be non-empty. + if t.Kind() == reflect.Slice && (vx.Len() == 0 || vy.Len() == 0) { + return false + } + + // If a sufficient number of elements already differ, + // use specialized formatting even if length requirement is not met. + if v.NumDiff > v.NumSame { + return true + } + default: + return false + } + + // Use specialized string diffing for longer slices or strings. + const minLength = 32 + return vx.Len() >= minLength && vy.Len() >= minLength +} + +// FormatDiffSlice prints a diff for the slices (or strings) represented by v. +// This provides custom-tailored logic to make printing of differences in +// textual strings and slices of primitive kinds more readable. +func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { + assert(opts.DiffMode == diffUnknown) + t, vx, vy := v.Type, v.ValueX, v.ValueY + if t.Kind() == reflect.Interface { + vx, vy = vx.Elem(), vy.Elem() + t = vx.Type() + opts = opts.WithTypeMode(emitType) + } + + // Auto-detect the type of the data. + var sx, sy string + var ssx, ssy []string + var isString, isMostlyText, isPureLinedText, isBinary bool + switch { + case t.Kind() == reflect.String: + sx, sy = vx.String(), vy.String() + isString = true + case t.Kind() == reflect.Slice && t.Elem() == byteType: + sx, sy = string(vx.Bytes()), string(vy.Bytes()) + isString = true + case t.Kind() == reflect.Array: + // Arrays need to be addressable for slice operations to work. + vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem() + vx2.Set(vx) + vy2.Set(vy) + vx, vy = vx2, vy2 + } + if isString { + var numTotalRunes, numValidRunes, numLines, lastLineIdx, maxLineLen int + for i, r := range sx + sy { + numTotalRunes++ + if (unicode.IsPrint(r) || unicode.IsSpace(r)) && r != utf8.RuneError { + numValidRunes++ + } + if r == '\n' { + if maxLineLen < i-lastLineIdx { + maxLineLen = i - lastLineIdx + } + lastLineIdx = i + 1 + numLines++ + } + } + isPureText := numValidRunes == numTotalRunes + isMostlyText = float64(numValidRunes) > math.Floor(0.90*float64(numTotalRunes)) + isPureLinedText = isPureText && numLines >= 4 && maxLineLen <= 1024 + isBinary = !isMostlyText + + // Avoid diffing by lines if it produces a significantly more complex + // edit script than diffing by bytes. + if isPureLinedText { + ssx = strings.Split(sx, "\n") + ssy = strings.Split(sy, "\n") + esLines := diff.Difference(len(ssx), len(ssy), func(ix, iy int) diff.Result { + return diff.BoolResult(ssx[ix] == ssy[iy]) + }) + esBytes := diff.Difference(len(sx), len(sy), func(ix, iy int) diff.Result { + return diff.BoolResult(sx[ix] == sy[iy]) + }) + efficiencyLines := float64(esLines.Dist()) / float64(len(esLines)) + efficiencyBytes := float64(esBytes.Dist()) / float64(len(esBytes)) + quotedLength := len(strconv.Quote(sx + sy)) + unquotedLength := len(sx) + len(sy) + escapeExpansionRatio := float64(quotedLength) / float64(unquotedLength) + isPureLinedText = efficiencyLines < 4*efficiencyBytes || escapeExpansionRatio > 1.1 + } + } + + // Format the string into printable records. + var list textList + var delim string + switch { + // If the text appears to be multi-lined text, + // then perform differencing across individual lines. + case isPureLinedText: + list = opts.formatDiffSlice( + reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line", + func(v reflect.Value, d diffMode) textRecord { + s := formatString(v.Index(0).String()) + return textRecord{Diff: d, Value: textLine(s)} + }, + ) + delim = "\n" + + // If possible, use a custom triple-quote (""") syntax for printing + // differences in a string literal. This format is more readable, + // but has edge-cases where differences are visually indistinguishable. + // This format is avoided under the following conditions: + // - A line starts with `"""` + // - A line starts with "..." + // - A line contains non-printable characters + // - Adjacent different lines differ only by whitespace + // + // For example: + // + // """ + // ... // 3 identical lines + // foo + // bar + // - baz + // + BAZ + // """ + isTripleQuoted := true + prevRemoveLines := map[string]bool{} + prevInsertLines := map[string]bool{} + var list2 textList + list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) + for _, r := range list { + if !r.Value.Equal(textEllipsis) { + line, _ := strconv.Unquote(string(r.Value.(textLine))) + line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support + normLine := strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + return -1 // drop whitespace to avoid visually indistinguishable output + } + return r + }, line) + isPrintable := func(r rune) bool { + return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable + } + isTripleQuoted = !strings.HasPrefix(line, `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" + switch r.Diff { + case diffRemoved: + isTripleQuoted = isTripleQuoted && !prevInsertLines[normLine] + prevRemoveLines[normLine] = true + case diffInserted: + isTripleQuoted = isTripleQuoted && !prevRemoveLines[normLine] + prevInsertLines[normLine] = true + } + if !isTripleQuoted { + break + } + r.Value = textLine(line) + r.ElideComma = true + } + if !(r.Diff == diffRemoved || r.Diff == diffInserted) { // start a new non-adjacent difference group + prevRemoveLines = map[string]bool{} + prevInsertLines = map[string]bool{} + } + list2 = append(list2, r) + } + if r := list2[len(list2)-1]; r.Diff == diffIdentical && len(r.Value.(textLine)) == 0 { + list2 = list2[:len(list2)-1] // elide single empty line at the end + } + list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) + if isTripleQuoted { + var out textNode = &textWrap{Prefix: "(", Value: list2, Suffix: ")"} + switch t.Kind() { + case reflect.String: + if t != stringType { + out = opts.FormatType(t, out) + } + case reflect.Slice: + // Always emit type for slices since the triple-quote syntax + // looks like a string (not a slice). + opts = opts.WithTypeMode(emitType) + out = opts.FormatType(t, out) + } + return out + } + + // If the text appears to be single-lined text, + // then perform differencing in approximately fixed-sized chunks. + // The output is printed as quoted strings. + case isMostlyText: + list = opts.formatDiffSlice( + reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte", + func(v reflect.Value, d diffMode) textRecord { + s := formatString(v.String()) + return textRecord{Diff: d, Value: textLine(s)} + }, + ) + + // If the text appears to be binary data, + // then perform differencing in approximately fixed-sized chunks. + // The output is inspired by hexdump. + case isBinary: + list = opts.formatDiffSlice( + reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte", + func(v reflect.Value, d diffMode) textRecord { + var ss []string + for i := 0; i < v.Len(); i++ { + ss = append(ss, formatHex(v.Index(i).Uint())) + } + s := strings.Join(ss, ", ") + comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String()))) + return textRecord{Diff: d, Value: textLine(s), Comment: comment} + }, + ) + + // For all other slices of primitive types, + // then perform differencing in approximately fixed-sized chunks. + // The size of each chunk depends on the width of the element kind. + default: + var chunkSize int + if t.Elem().Kind() == reflect.Bool { + chunkSize = 16 + } else { + switch t.Elem().Bits() { + case 8: + chunkSize = 16 + case 16: + chunkSize = 12 + case 32: + chunkSize = 8 + default: + chunkSize = 8 + } + } + list = opts.formatDiffSlice( + vx, vy, chunkSize, t.Elem().Kind().String(), + func(v reflect.Value, d diffMode) textRecord { + var ss []string + for i := 0; i < v.Len(); i++ { + switch t.Elem().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + ss = append(ss, fmt.Sprint(v.Index(i).Int())) + case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + ss = append(ss, fmt.Sprint(v.Index(i).Uint())) + case reflect.Uint8, reflect.Uintptr: + ss = append(ss, formatHex(v.Index(i).Uint())) + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + ss = append(ss, fmt.Sprint(v.Index(i).Interface())) + } + } + s := strings.Join(ss, ", ") + return textRecord{Diff: d, Value: textLine(s)} + }, + ) + } + + // Wrap the output with appropriate type information. + var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"} + if !isMostlyText { + // The "{...}" byte-sequence literal is not valid Go syntax for strings. + // Emit the type for extra clarity (e.g. "string{...}"). + if t.Kind() == reflect.String { + opts = opts.WithTypeMode(emitType) + } + return opts.FormatType(t, out) + } + switch t.Kind() { + case reflect.String: + out = &textWrap{Prefix: "strings.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} + if t != stringType { + out = opts.FormatType(t, out) + } + case reflect.Slice: + out = &textWrap{Prefix: "bytes.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} + if t != bytesType { + out = opts.FormatType(t, out) + } + } + return out +} + +// formatASCII formats s as an ASCII string. +// This is useful for printing binary strings in a semi-legible way. +func formatASCII(s string) string { + b := bytes.Repeat([]byte{'.'}, len(s)) + for i := 0; i < len(s); i++ { + if ' ' <= s[i] && s[i] <= '~' { + b[i] = s[i] + } + } + return string(b) +} + +func (opts formatOptions) formatDiffSlice( + vx, vy reflect.Value, chunkSize int, name string, + makeRec func(reflect.Value, diffMode) textRecord, +) (list textList) { + eq := func(ix, iy int) bool { + return vx.Index(ix).Interface() == vy.Index(iy).Interface() + } + es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result { + return diff.BoolResult(eq(ix, iy)) + }) + + appendChunks := func(v reflect.Value, d diffMode) int { + n0 := v.Len() + for v.Len() > 0 { + n := chunkSize + if n > v.Len() { + n = v.Len() + } + list = append(list, makeRec(v.Slice(0, n), d)) + v = v.Slice(n, v.Len()) + } + return n0 - v.Len() + } + + var numDiffs int + maxLen := -1 + if opts.LimitVerbosity { + maxLen = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc... + opts.VerbosityLevel-- + } + + groups := coalesceAdjacentEdits(name, es) + groups = coalesceInterveningIdentical(groups, chunkSize/4) + groups = cleanupSurroundingIdentical(groups, eq) + maxGroup := diffStats{Name: name} + for i, ds := range groups { + if maxLen >= 0 && numDiffs >= maxLen { + maxGroup = maxGroup.Append(ds) + continue + } + + // Print equal. + if ds.NumDiff() == 0 { + // Compute the number of leading and trailing equal bytes to print. + var numLo, numHi int + numEqual := ds.NumIgnored + ds.NumIdentical + for numLo < chunkSize*numContextRecords && numLo+numHi < numEqual && i != 0 { + numLo++ + } + for numHi < chunkSize*numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { + numHi++ + } + if numEqual-(numLo+numHi) <= chunkSize && ds.NumIgnored == 0 { + numHi = numEqual - numLo // Avoid pointless coalescing of single equal row + } + + // Print the equal bytes. + appendChunks(vx.Slice(0, numLo), diffIdentical) + if numEqual > numLo+numHi { + ds.NumIdentical -= numLo + numHi + list.AppendEllipsis(ds) + } + appendChunks(vx.Slice(numEqual-numHi, numEqual), diffIdentical) + vx = vx.Slice(numEqual, vx.Len()) + vy = vy.Slice(numEqual, vy.Len()) + continue + } + + // Print unequal. + len0 := len(list) + nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved) + vx = vx.Slice(nx, vx.Len()) + ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted) + vy = vy.Slice(ny, vy.Len()) + numDiffs += len(list) - len0 + } + if maxGroup.IsZero() { + assert(vx.Len() == 0 && vy.Len() == 0) + } else { + list.AppendEllipsis(maxGroup) + } + return list +} + +// coalesceAdjacentEdits coalesces the list of edits into groups of adjacent +// equal or unequal counts. +// +// Example: +// +// Input: "..XXY...Y" +// Output: [ +// {NumIdentical: 2}, +// {NumRemoved: 2, NumInserted 1}, +// {NumIdentical: 3}, +// {NumInserted: 1}, +// ] +func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) { + var prevMode byte + lastStats := func(mode byte) *diffStats { + if prevMode != mode { + groups = append(groups, diffStats{Name: name}) + prevMode = mode + } + return &groups[len(groups)-1] + } + for _, e := range es { + switch e { + case diff.Identity: + lastStats('=').NumIdentical++ + case diff.UniqueX: + lastStats('!').NumRemoved++ + case diff.UniqueY: + lastStats('!').NumInserted++ + case diff.Modified: + lastStats('!').NumModified++ + } + } + return groups +} + +// coalesceInterveningIdentical coalesces sufficiently short (<= windowSize) +// equal groups into adjacent unequal groups that currently result in a +// dual inserted/removed printout. This acts as a high-pass filter to smooth +// out high-frequency changes within the windowSize. +// +// Example: +// +// WindowSize: 16, +// Input: [ +// {NumIdentical: 61}, // group 0 +// {NumRemoved: 3, NumInserted: 1}, // group 1 +// {NumIdentical: 6}, // ├── coalesce +// {NumInserted: 2}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 9}, // └── coalesce +// {NumIdentical: 64}, // group 2 +// {NumRemoved: 3, NumInserted: 1}, // group 3 +// {NumIdentical: 6}, // ├── coalesce +// {NumInserted: 2}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 7}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 2}, // └── coalesce +// {NumIdentical: 63}, // group 4 +// ] +// Output: [ +// {NumIdentical: 61}, +// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, +// {NumIdentical: 64}, +// {NumIdentical: 8, NumRemoved: 12, NumInserted: 3}, +// {NumIdentical: 63}, +// ] +func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats { + groups, groupsOrig := groups[:0], groups + for i, ds := range groupsOrig { + if len(groups) >= 2 && ds.NumDiff() > 0 { + prev := &groups[len(groups)-2] // Unequal group + curr := &groups[len(groups)-1] // Equal group + next := &groupsOrig[i] // Unequal group + hadX, hadY := prev.NumRemoved > 0, prev.NumInserted > 0 + hasX, hasY := next.NumRemoved > 0, next.NumInserted > 0 + if ((hadX || hasX) && (hadY || hasY)) && curr.NumIdentical <= windowSize { + *prev = prev.Append(*curr).Append(*next) + groups = groups[:len(groups)-1] // Truncate off equal group + continue + } + } + groups = append(groups, ds) + } + return groups +} + +// cleanupSurroundingIdentical scans through all unequal groups, and +// moves any leading sequence of equal elements to the preceding equal group and +// moves and trailing sequence of equal elements to the succeeding equal group. +// +// This is necessary since coalesceInterveningIdentical may coalesce edit groups +// together such that leading/trailing spans of equal elements becomes possible. +// Note that this can occur even with an optimal diffing algorithm. +// +// Example: +// +// Input: [ +// {NumIdentical: 61}, +// {NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements +// {NumIdentical: 67}, +// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // assume 10 trailing identical elements +// {NumIdentical: 54}, +// ] +// Output: [ +// {NumIdentical: 64}, // incremented by 3 +// {NumRemoved: 9}, +// {NumIdentical: 67}, +// {NumRemoved: 9}, +// {NumIdentical: 64}, // incremented by 10 +// ] +func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats { + var ix, iy int // indexes into sequence x and y + for i, ds := range groups { + // Handle equal group. + if ds.NumDiff() == 0 { + ix += ds.NumIdentical + iy += ds.NumIdentical + continue + } + + // Handle unequal group. + nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified + ny := ds.NumIdentical + ds.NumInserted + ds.NumModified + var numLeadingIdentical, numTrailingIdentical int + for j := 0; j < nx && j < ny && eq(ix+j, iy+j); j++ { + numLeadingIdentical++ + } + for j := 0; j < nx && j < ny && eq(ix+nx-1-j, iy+ny-1-j); j++ { + numTrailingIdentical++ + } + if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 { + if numLeadingIdentical > 0 { + // Remove leading identical span from this group and + // insert it into the preceding group. + if i-1 >= 0 { + groups[i-1].NumIdentical += numLeadingIdentical + } else { + // No preceding group exists, so prepend a new group, + // but do so after we finish iterating over all groups. + defer func() { + groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...) + }() + } + // Increment indexes since the preceding group would have handled this. + ix += numLeadingIdentical + iy += numLeadingIdentical + } + if numTrailingIdentical > 0 { + // Remove trailing identical span from this group and + // insert it into the succeeding group. + if i+1 < len(groups) { + groups[i+1].NumIdentical += numTrailingIdentical + } else { + // No succeeding group exists, so append a new group, + // but do so after we finish iterating over all groups. + defer func() { + groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical}) + }() + } + // Do not increment indexes since the succeeding group will handle this. + } + + // Update this group since some identical elements were removed. + nx -= numIdentical + ny -= numIdentical + groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny} + } + ix += nx + iy += ny + } + return groups +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_text.go b/vendor/github.com/google/go-cmp/cmp/report_text.go new file mode 100644 index 0000000..388fcf5 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_text.go @@ -0,0 +1,432 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import ( + "bytes" + "fmt" + "math/rand" + "strings" + "time" + "unicode/utf8" + + "github.com/google/go-cmp/cmp/internal/flags" +) + +var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 + +const maxColumnLength = 80 + +type indentMode int + +func (n indentMode) appendIndent(b []byte, d diffMode) []byte { + // The output of Diff is documented as being unstable to provide future + // flexibility in changing the output for more humanly readable reports. + // This logic intentionally introduces instability to the exact output + // so that users can detect accidental reliance on stability early on, + // rather than much later when an actual change to the format occurs. + if flags.Deterministic || randBool { + // Use regular spaces (U+0020). + switch d { + case diffUnknown, diffIdentical: + b = append(b, " "...) + case diffRemoved: + b = append(b, "- "...) + case diffInserted: + b = append(b, "+ "...) + } + } else { + // Use non-breaking spaces (U+00a0). + switch d { + case diffUnknown, diffIdentical: + b = append(b, "  "...) + case diffRemoved: + b = append(b, "- "...) + case diffInserted: + b = append(b, "+ "...) + } + } + return repeatCount(n).appendChar(b, '\t') +} + +type repeatCount int + +func (n repeatCount) appendChar(b []byte, c byte) []byte { + for ; n > 0; n-- { + b = append(b, c) + } + return b +} + +// textNode is a simplified tree-based representation of structured text. +// Possible node types are textWrap, textList, or textLine. +type textNode interface { + // Len reports the length in bytes of a single-line version of the tree. + // Nested textRecord.Diff and textRecord.Comment fields are ignored. + Len() int + // Equal reports whether the two trees are structurally identical. + // Nested textRecord.Diff and textRecord.Comment fields are compared. + Equal(textNode) bool + // String returns the string representation of the text tree. + // It is not guaranteed that len(x.String()) == x.Len(), + // nor that x.String() == y.String() implies that x.Equal(y). + String() string + + // formatCompactTo formats the contents of the tree as a single-line string + // to the provided buffer. Any nested textRecord.Diff and textRecord.Comment + // fields are ignored. + // + // However, not all nodes in the tree should be collapsed as a single-line. + // If a node can be collapsed as a single-line, it is replaced by a textLine + // node. Since the top-level node cannot replace itself, this also returns + // the current node itself. + // + // This does not mutate the receiver. + formatCompactTo([]byte, diffMode) ([]byte, textNode) + // formatExpandedTo formats the contents of the tree as a multi-line string + // to the provided buffer. In order for column alignment to operate well, + // formatCompactTo must be called before calling formatExpandedTo. + formatExpandedTo([]byte, diffMode, indentMode) []byte +} + +// textWrap is a wrapper that concatenates a prefix and/or a suffix +// to the underlying node. +type textWrap struct { + Prefix string // e.g., "bytes.Buffer{" + Value textNode // textWrap | textList | textLine + Suffix string // e.g., "}" + Metadata interface{} // arbitrary metadata; has no effect on formatting +} + +func (s *textWrap) Len() int { + return len(s.Prefix) + s.Value.Len() + len(s.Suffix) +} +func (s1 *textWrap) Equal(s2 textNode) bool { + if s2, ok := s2.(*textWrap); ok { + return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix + } + return false +} +func (s *textWrap) String() string { + var d diffMode + var n indentMode + _, s2 := s.formatCompactTo(nil, d) + b := n.appendIndent(nil, d) // Leading indent + b = s2.formatExpandedTo(b, d, n) // Main body + b = append(b, '\n') // Trailing newline + return string(b) +} +func (s *textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { + n0 := len(b) // Original buffer length + b = append(b, s.Prefix...) + b, s.Value = s.Value.formatCompactTo(b, d) + b = append(b, s.Suffix...) + if _, ok := s.Value.(textLine); ok { + return b, textLine(b[n0:]) + } + return b, s +} +func (s *textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { + b = append(b, s.Prefix...) + b = s.Value.formatExpandedTo(b, d, n) + b = append(b, s.Suffix...) + return b +} + +// textList is a comma-separated list of textWrap or textLine nodes. +// The list may be formatted as multi-lines or single-line at the discretion +// of the textList.formatCompactTo method. +type textList []textRecord +type textRecord struct { + Diff diffMode // e.g., 0 or '-' or '+' + Key string // e.g., "MyField" + Value textNode // textWrap | textLine + ElideComma bool // avoid trailing comma + Comment fmt.Stringer // e.g., "6 identical fields" +} + +// AppendEllipsis appends a new ellipsis node to the list if none already +// exists at the end. If cs is non-zero it coalesces the statistics with the +// previous diffStats. +func (s *textList) AppendEllipsis(ds diffStats) { + hasStats := !ds.IsZero() + if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) { + if hasStats { + *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true, Comment: ds}) + } else { + *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true}) + } + return + } + if hasStats { + (*s)[len(*s)-1].Comment = (*s)[len(*s)-1].Comment.(diffStats).Append(ds) + } +} + +func (s textList) Len() (n int) { + for i, r := range s { + n += len(r.Key) + if r.Key != "" { + n += len(": ") + } + n += r.Value.Len() + if i < len(s)-1 { + n += len(", ") + } + } + return n +} + +func (s1 textList) Equal(s2 textNode) bool { + if s2, ok := s2.(textList); ok { + if len(s1) != len(s2) { + return false + } + for i := range s1 { + r1, r2 := s1[i], s2[i] + if !(r1.Diff == r2.Diff && r1.Key == r2.Key && r1.Value.Equal(r2.Value) && r1.Comment == r2.Comment) { + return false + } + } + return true + } + return false +} + +func (s textList) String() string { + return (&textWrap{Prefix: "{", Value: s, Suffix: "}"}).String() +} + +func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { + s = append(textList(nil), s...) // Avoid mutating original + + // Determine whether we can collapse this list as a single line. + n0 := len(b) // Original buffer length + var multiLine bool + for i, r := range s { + if r.Diff == diffInserted || r.Diff == diffRemoved { + multiLine = true + } + b = append(b, r.Key...) + if r.Key != "" { + b = append(b, ": "...) + } + b, s[i].Value = r.Value.formatCompactTo(b, d|r.Diff) + if _, ok := s[i].Value.(textLine); !ok { + multiLine = true + } + if r.Comment != nil { + multiLine = true + } + if i < len(s)-1 { + b = append(b, ", "...) + } + } + // Force multi-lined output when printing a removed/inserted node that + // is sufficiently long. + if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > maxColumnLength { + multiLine = true + } + if !multiLine { + return b, textLine(b[n0:]) + } + return b, s +} + +func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { + alignKeyLens := s.alignLens( + func(r textRecord) bool { + _, isLine := r.Value.(textLine) + return r.Key == "" || !isLine + }, + func(r textRecord) int { return utf8.RuneCountInString(r.Key) }, + ) + alignValueLens := s.alignLens( + func(r textRecord) bool { + _, isLine := r.Value.(textLine) + return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil + }, + func(r textRecord) int { return utf8.RuneCount(r.Value.(textLine)) }, + ) + + // Format lists of simple lists in a batched form. + // If the list is sequence of only textLine values, + // then batch multiple values on a single line. + var isSimple bool + for _, r := range s { + _, isLine := r.Value.(textLine) + isSimple = r.Diff == 0 && r.Key == "" && isLine && r.Comment == nil + if !isSimple { + break + } + } + if isSimple { + n++ + var batch []byte + emitBatch := func() { + if len(batch) > 0 { + b = n.appendIndent(append(b, '\n'), d) + b = append(b, bytes.TrimRight(batch, " ")...) + batch = batch[:0] + } + } + for _, r := range s { + line := r.Value.(textLine) + if len(batch)+len(line)+len(", ") > maxColumnLength { + emitBatch() + } + batch = append(batch, line...) + batch = append(batch, ", "...) + } + emitBatch() + n-- + return n.appendIndent(append(b, '\n'), d) + } + + // Format the list as a multi-lined output. + n++ + for i, r := range s { + b = n.appendIndent(append(b, '\n'), d|r.Diff) + if r.Key != "" { + b = append(b, r.Key+": "...) + } + b = alignKeyLens[i].appendChar(b, ' ') + + b = r.Value.formatExpandedTo(b, d|r.Diff, n) + if !r.ElideComma { + b = append(b, ',') + } + b = alignValueLens[i].appendChar(b, ' ') + + if r.Comment != nil { + b = append(b, " // "+r.Comment.String()...) + } + } + n-- + + return n.appendIndent(append(b, '\n'), d) +} + +func (s textList) alignLens( + skipFunc func(textRecord) bool, + lenFunc func(textRecord) int, +) []repeatCount { + var startIdx, endIdx, maxLen int + lens := make([]repeatCount, len(s)) + for i, r := range s { + if skipFunc(r) { + for j := startIdx; j < endIdx && j < len(s); j++ { + lens[j] = repeatCount(maxLen - lenFunc(s[j])) + } + startIdx, endIdx, maxLen = i+1, i+1, 0 + } else { + if maxLen < lenFunc(r) { + maxLen = lenFunc(r) + } + endIdx = i + 1 + } + } + for j := startIdx; j < endIdx && j < len(s); j++ { + lens[j] = repeatCount(maxLen - lenFunc(s[j])) + } + return lens +} + +// textLine is a single-line segment of text and is always a leaf node +// in the textNode tree. +type textLine []byte + +var ( + textNil = textLine("nil") + textEllipsis = textLine("...") +) + +func (s textLine) Len() int { + return len(s) +} +func (s1 textLine) Equal(s2 textNode) bool { + if s2, ok := s2.(textLine); ok { + return bytes.Equal([]byte(s1), []byte(s2)) + } + return false +} +func (s textLine) String() string { + return string(s) +} +func (s textLine) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { + return append(b, s...), s +} +func (s textLine) formatExpandedTo(b []byte, _ diffMode, _ indentMode) []byte { + return append(b, s...) +} + +type diffStats struct { + Name string + NumIgnored int + NumIdentical int + NumRemoved int + NumInserted int + NumModified int +} + +func (s diffStats) IsZero() bool { + s.Name = "" + return s == diffStats{} +} + +func (s diffStats) NumDiff() int { + return s.NumRemoved + s.NumInserted + s.NumModified +} + +func (s diffStats) Append(ds diffStats) diffStats { + assert(s.Name == ds.Name) + s.NumIgnored += ds.NumIgnored + s.NumIdentical += ds.NumIdentical + s.NumRemoved += ds.NumRemoved + s.NumInserted += ds.NumInserted + s.NumModified += ds.NumModified + return s +} + +// String prints a humanly-readable summary of coalesced records. +// +// Example: +// +// diffStats{Name: "Field", NumIgnored: 5}.String() => "5 ignored fields" +func (s diffStats) String() string { + var ss []string + var sum int + labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"} + counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified} + for i, n := range counts { + if n > 0 { + ss = append(ss, fmt.Sprintf("%d %v", n, labels[i])) + } + sum += n + } + + // Pluralize the name (adjusting for some obscure English grammar rules). + name := s.Name + if sum > 1 { + name += "s" + if strings.HasSuffix(name, "ys") { + name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries" + } + } + + // Format the list according to English grammar (with Oxford comma). + switch n := len(ss); n { + case 0: + return "" + case 1, 2: + return strings.Join(ss, " and ") + " " + name + default: + return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name + } +} + +type commentString string + +func (s commentString) String() string { return string(s) } diff --git a/vendor/github.com/google/go-cmp/cmp/report_value.go b/vendor/github.com/google/go-cmp/cmp/report_value.go new file mode 100644 index 0000000..668d470 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_value.go @@ -0,0 +1,121 @@ +// Copyright 2019, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cmp + +import "reflect" + +// valueNode represents a single node within a report, which is a +// structured representation of the value tree, containing information +// regarding which nodes are equal or not. +type valueNode struct { + parent *valueNode + + Type reflect.Type + ValueX reflect.Value + ValueY reflect.Value + + // NumSame is the number of leaf nodes that are equal. + // All descendants are equal only if NumDiff is 0. + NumSame int + // NumDiff is the number of leaf nodes that are not equal. + NumDiff int + // NumIgnored is the number of leaf nodes that are ignored. + NumIgnored int + // NumCompared is the number of leaf nodes that were compared + // using an Equal method or Comparer function. + NumCompared int + // NumTransformed is the number of non-leaf nodes that were transformed. + NumTransformed int + // NumChildren is the number of transitive descendants of this node. + // This counts from zero; thus, leaf nodes have no descendants. + NumChildren int + // MaxDepth is the maximum depth of the tree. This counts from zero; + // thus, leaf nodes have a depth of zero. + MaxDepth int + + // Records is a list of struct fields, slice elements, or map entries. + Records []reportRecord // If populated, implies Value is not populated + + // Value is the result of a transformation, pointer indirect, of + // type assertion. + Value *valueNode // If populated, implies Records is not populated + + // TransformerName is the name of the transformer. + TransformerName string // If non-empty, implies Value is populated +} +type reportRecord struct { + Key reflect.Value // Invalid for slice element + Value *valueNode +} + +func (parent *valueNode) PushStep(ps PathStep) (child *valueNode) { + vx, vy := ps.Values() + child = &valueNode{parent: parent, Type: ps.Type(), ValueX: vx, ValueY: vy} + switch s := ps.(type) { + case StructField: + assert(parent.Value == nil) + parent.Records = append(parent.Records, reportRecord{Key: reflect.ValueOf(s.Name()), Value: child}) + case SliceIndex: + assert(parent.Value == nil) + parent.Records = append(parent.Records, reportRecord{Value: child}) + case MapIndex: + assert(parent.Value == nil) + parent.Records = append(parent.Records, reportRecord{Key: s.Key(), Value: child}) + case Indirect: + assert(parent.Value == nil && parent.Records == nil) + parent.Value = child + case TypeAssertion: + assert(parent.Value == nil && parent.Records == nil) + parent.Value = child + case Transform: + assert(parent.Value == nil && parent.Records == nil) + parent.Value = child + parent.TransformerName = s.Name() + parent.NumTransformed++ + default: + assert(parent == nil) // Must be the root step + } + return child +} + +func (r *valueNode) Report(rs Result) { + assert(r.MaxDepth == 0) // May only be called on leaf nodes + + if rs.ByIgnore() { + r.NumIgnored++ + } else { + if rs.Equal() { + r.NumSame++ + } else { + r.NumDiff++ + } + } + assert(r.NumSame+r.NumDiff+r.NumIgnored == 1) + + if rs.ByMethod() { + r.NumCompared++ + } + if rs.ByFunc() { + r.NumCompared++ + } + assert(r.NumCompared <= 1) +} + +func (child *valueNode) PopStep() (parent *valueNode) { + if child.parent == nil { + return nil + } + parent = child.parent + parent.NumSame += child.NumSame + parent.NumDiff += child.NumDiff + parent.NumIgnored += child.NumIgnored + parent.NumCompared += child.NumCompared + parent.NumTransformed += child.NumTransformed + parent.NumChildren += child.NumChildren + 1 + if parent.MaxDepth < child.MaxDepth+1 { + parent.MaxDepth = child.MaxDepth + 1 + } + return parent +} diff --git a/vendor/github.com/josharian/native/doc.go b/vendor/github.com/josharian/native/doc.go new file mode 100644 index 0000000..2ca7ddc --- /dev/null +++ b/vendor/github.com/josharian/native/doc.go @@ -0,0 +1,8 @@ +// Package native provides easy access to native byte order. +// +// Usage: use native.Endian where you need the native binary.ByteOrder. +// +// Please think twice before using this package. +// It can break program portability. +// Native byte order is usually not the right answer. +package native diff --git a/vendor/github.com/josharian/native/endian_big.go b/vendor/github.com/josharian/native/endian_big.go new file mode 100644 index 0000000..77744fd --- /dev/null +++ b/vendor/github.com/josharian/native/endian_big.go @@ -0,0 +1,14 @@ +//go:build mips || mips64 || ppc64 || s390x +// +build mips mips64 ppc64 s390x + +package native + +import "encoding/binary" + +// Endian is the encoding/binary.ByteOrder implementation for the +// current CPU's native byte order. +var Endian = binary.BigEndian + +// IsBigEndian is whether the current CPU's native byte order is big +// endian. +const IsBigEndian = true diff --git a/vendor/github.com/josharian/native/endian_generic.go b/vendor/github.com/josharian/native/endian_generic.go new file mode 100644 index 0000000..c15228f --- /dev/null +++ b/vendor/github.com/josharian/native/endian_generic.go @@ -0,0 +1,31 @@ +//go:build !mips && !mips64 && !ppc64 && !s390x && !amd64 && !386 && !arm && !arm64 && !loong64 && !mipsle && !mips64le && !ppc64le && !riscv64 && !wasm +// +build !mips,!mips64,!ppc64,!s390x,!amd64,!386,!arm,!arm64,!loong64,!mipsle,!mips64le,!ppc64le,!riscv64,!wasm + +// This file is a fallback, so that package native doesn't break +// the instant the Go project adds support for a new architecture. +// + +package native + +import ( + "encoding/binary" + "log" + "runtime" + "unsafe" +) + +var Endian binary.ByteOrder + +var IsBigEndian bool + +func init() { + b := uint16(0xff) // one byte + if *(*byte)(unsafe.Pointer(&b)) == 0 { + Endian = binary.BigEndian + IsBigEndian = true + } else { + Endian = binary.LittleEndian + IsBigEndian = false + } + log.Printf("github.com/josharian/native: unrecognized arch %v (%v), please file an issue", runtime.GOARCH, Endian) +} diff --git a/vendor/github.com/josharian/native/endian_little.go b/vendor/github.com/josharian/native/endian_little.go new file mode 100644 index 0000000..5098fec --- /dev/null +++ b/vendor/github.com/josharian/native/endian_little.go @@ -0,0 +1,14 @@ +//go:build amd64 || 386 || arm || arm64 || loong64 || mipsle || mips64le || ppc64le || riscv64 || wasm +// +build amd64 386 arm arm64 loong64 mipsle mips64le ppc64le riscv64 wasm + +package native + +import "encoding/binary" + +// Endian is the encoding/binary.ByteOrder implementation for the +// current CPU's native byte order. +var Endian = binary.LittleEndian + +// IsBigEndian is whether the current CPU's native byte order is big +// endian. +const IsBigEndian = false diff --git a/vendor/github.com/josharian/native/license b/vendor/github.com/josharian/native/license new file mode 100644 index 0000000..6e617a9 --- /dev/null +++ b/vendor/github.com/josharian/native/license @@ -0,0 +1,7 @@ +Copyright 2020 Josh Bleecher Snyder + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/josharian/native/readme.md b/vendor/github.com/josharian/native/readme.md new file mode 100644 index 0000000..1fc5a01 --- /dev/null +++ b/vendor/github.com/josharian/native/readme.md @@ -0,0 +1,10 @@ +Package native provides easy access to native byte order. + +`go get github.com/josharian/native` + +Usage: Use `native.Endian` where you need the native binary.ByteOrder. + +Please think twice before using this package. +It can break program portability. +Native byte order is usually not the right answer. + diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/.gitignore b/vendor/github.com/jsimonetti/rtnetlink/v2/.gitignore new file mode 100644 index 0000000..bcacfc6 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/.gitignore @@ -0,0 +1 @@ +rtnetlink-fuzz.zip \ No newline at end of file diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/.golangci.yml b/vendor/github.com/jsimonetti/rtnetlink/v2/.golangci.yml new file mode 100644 index 0000000..295167c --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/.golangci.yml @@ -0,0 +1,18 @@ +--- +linters: + enable: + - gofmt + - misspell + - revive + +linters-settings: + misspell: + ignore-words: + # Incorrect spelling used in CacheInfo struct. + - Prefered + revive: + rules: + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter + - name: unused-parameter + severity: warning + disabled: true diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/LICENSE.md b/vendor/github.com/jsimonetti/rtnetlink/v2/LICENSE.md new file mode 100644 index 0000000..9c073eb --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/LICENSE.md @@ -0,0 +1,10 @@ +MIT License +=========== + +Copyright (C) 2016 Jeroen Simonetti + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/Makefile.fuzz b/vendor/github.com/jsimonetti/rtnetlink/v2/Makefile.fuzz new file mode 100644 index 0000000..4116833 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/Makefile.fuzz @@ -0,0 +1,32 @@ +# Makefile for fuzzing +# +# Currently fuzzing only works inside $GOPATH +# +# Installing go-fuzz +#$ go get github.com/dvyukov/go-fuzz/go-fuzz +#$ go get github.com/dvyukov/go-fuzz/go-fuzz-build +# (or) +#$ make -f Makefile.fuzz install +# +# Start fuzzing: +#$ make -f Makefile.fuzz fuzz +# +# Cleanup using: +#$ make -f Makefile.fuzz clean + +.PHONY: install +install: + go get github.com/dvyukov/go-fuzz/go-fuzz + go get github.com/dvyukov/go-fuzz/go-fuzz-build + +.PHONY: fuzz +fuzz: + go-fuzz-build -tags gofuzz + echo go-fuzz -bin=./rtnetlink-fuzz.zip -workdir=testdata -func FuzzLinkMessage + echo go-fuzz -bin=./rtnetlink-fuzz.zip -workdir=testdata -func FuzzAddressMessage + echo go-fuzz -bin=./rtnetlink-fuzz.zip -workdir=testdata -func FuzzRouteMessage + echo go-fuzz -bin=./rtnetlink-fuzz.zip -workdir=testdata -func FuzzNeighMessage + +.PHONY: clean +clean: + rm rtnetlink-fuzz.zip diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/README.md b/vendor/github.com/jsimonetti/rtnetlink/v2/README.md new file mode 100644 index 0000000..58b592f --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/README.md @@ -0,0 +1,43 @@ +rtnetlink ![Linux Integration](https://github.com/jsimonetti/rtnetlink/workflows/Go/badge.svg) [![GoDoc](https://godoc.org/github.com/jsimonetti/rtnetlink?status.svg)](https://godoc.org/github.com/jsimonetti/rtnetlink) [![Go Report Card](https://goreportcard.com/badge/github.com/jsimonetti/rtnetlink)](https://goreportcard.com/report/github.com/jsimonetti/rtnetlink) +======= + +Package `rtnetlink` allows the kernel's routing tables to be read and +altered. Network routes, IP addresses, Link parameters, Neighbor setups, +Queueing disciplines, Traffic classes and Packet classifiers may all be +controlled. It is based on netlink messages. + +A convenient, high-level API wrapper is available using package +[`rtnl`](https://godoc.org/github.com/jsimonetti/rtnetlink/rtnl). + +The base `rtnetlink` library explicitly only exposes a limited low-level API to +rtnetlink. It is not the intention (nor wish) to create an iproute2 +replacement. + +### Debugging and netlink errors +Unfortunately the errors generated by the kernels netlink interface are +not very great. + +When in doubt about your message structure it can always be useful to +look at the message send by iproute2 using `strace -f -esendmsg /bin/ip` +or similar. + +Another (and possibly even more flexible) way would be using `nlmon` and +`wireshark`. nlmod is a special kernel module which allows you to +capture all netlink (not just rtnetlink) traffic inside the kernel. Be +aware that this might be overwhelming on a system with a lot of netlink +traffic. + +``` +# modprobe nlmon +# ip link add type nlmon +# ip link set nlmon0 up +``` + +At this point use wireshark or tcpdump on the nlmon0 interface to view +all netlink traffic. + +Have a look at the examples for common uses of rtnetlink. + +If you have any questions or you'd like some guidance, please join us on +[Gophers Slack](https://invite.slack.golangbridge.org) in the `#networking` +channel! diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/address.go b/vendor/github.com/jsimonetti/rtnetlink/v2/address.go new file mode 100644 index 0000000..b938029 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/address.go @@ -0,0 +1,269 @@ +package rtnetlink + +import ( + "errors" + "fmt" + "net" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + + "github.com/mdlayher/netlink" +) + +var ( + // errInvalidaddressMessage is returned when a AddressMessage is malformed. + errInvalidAddressMessage = errors.New("rtnetlink AddressMessage is invalid or too short") +) + +var _ Message = &AddressMessage{} + +// A AddressMessage is a route netlink address message. +type AddressMessage struct { + // Address family (current unix.AF_INET or unix.AF_INET6) + Family uint8 + + // Prefix length + PrefixLength uint8 + + // Contains address flags + Flags uint8 + + // Address Scope + Scope uint8 + + // Interface index + Index uint32 + + // Optional attributes which are appended when not nil. + Attributes *AddressAttributes +} + +// MarshalBinary marshals a AddressMessage into a byte slice. +func (m *AddressMessage) MarshalBinary() ([]byte, error) { + b := make([]byte, unix.SizeofIfAddrmsg) + + b[0] = m.Family + b[1] = m.PrefixLength + b[2] = m.Flags + b[3] = m.Scope + nativeEndian.PutUint32(b[4:8], m.Index) + + if m.Attributes == nil { + // No attributes to encode. + return b, nil + } + + ae := netlink.NewAttributeEncoder() + err := m.Attributes.encode(ae) + if err != nil { + return nil, err + } + + a, err := ae.Encode() + if err != nil { + return nil, err + } + + return append(b, a...), nil +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a AddressMessage. +func (m *AddressMessage) UnmarshalBinary(b []byte) error { + l := len(b) + if l < unix.SizeofIfAddrmsg { + return errInvalidAddressMessage + } + + m.Family = uint8(b[0]) + m.PrefixLength = uint8(b[1]) + m.Flags = uint8(b[2]) + m.Scope = uint8(b[3]) + m.Index = nativeEndian.Uint32(b[4:8]) + + if l > unix.SizeofIfAddrmsg { + ad, err := netlink.NewAttributeDecoder(b[unix.SizeofIfAddrmsg:]) + if err != nil { + return err + } + + var aa AddressAttributes + if err := aa.decode(ad); err != nil { + return err + } + + // Must consume errors from decoder before returning. + if err := ad.Err(); err != nil { + return fmt.Errorf("invalid address message attributes: %v", err) + } + m.Attributes = &aa + } + + return nil +} + +// rtMessage is an empty method to sattisfy the Message interface. +func (*AddressMessage) rtMessage() {} + +// AddressService is used to retrieve rtnetlink family information. +type AddressService struct { + c *Conn +} + +// New creates a new address using the AddressMessage information. +func (a *AddressService) New(req *AddressMessage) error { + flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl + _, err := a.c.Execute(req, unix.RTM_NEWADDR, flags) + if err != nil { + return err + } + + return nil +} + +// Delete removes an address using the AddressMessage information. +func (a *AddressService) Delete(req *AddressMessage) error { + flags := netlink.Request | netlink.Acknowledge + _, err := a.c.Execute(req, unix.RTM_DELADDR, flags) + if err != nil { + return err + } + + return nil +} + +// List retrieves all addresses. +func (a *AddressService) List() ([]AddressMessage, error) { + req := AddressMessage{} + + flags := netlink.Request | netlink.Dump + msgs, err := a.c.Execute(&req, unix.RTM_GETADDR, flags) + if err != nil { + return nil, err + } + + addresses := make([]AddressMessage, len(msgs)) + for i := range msgs { + addresses[i] = *msgs[i].(*AddressMessage) + } + return addresses, nil +} + +// AddressAttributes contains all attributes for an interface. +type AddressAttributes struct { + Address net.IP // Interface Ip address + Local net.IP // Local Ip address + Label string + Broadcast net.IP // Broadcast Ip address + Anycast net.IP // Anycast Ip address + CacheInfo CacheInfo // Address information + Multicast net.IP // Multicast Ip address + Flags uint32 // Address flags +} + +func (a *AddressAttributes) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.IFA_UNSPEC: + // unused attribute + case unix.IFA_ADDRESS: + ad.Do(decodeIP(&a.Address)) + case unix.IFA_LOCAL: + ad.Do(decodeIP(&a.Local)) + case unix.IFA_LABEL: + a.Label = ad.String() + case unix.IFA_BROADCAST: + ad.Do(decodeIP(&a.Broadcast)) + case unix.IFA_ANYCAST: + ad.Do(decodeIP(&a.Anycast)) + case unix.IFA_CACHEINFO: + ad.Do(a.CacheInfo.decode) + case unix.IFA_MULTICAST: + ad.Do(decodeIP(&a.Multicast)) + case unix.IFA_FLAGS: + a.Flags = ad.Uint32() + } + } + + return nil +} + +func (a *AddressAttributes) encode(ae *netlink.AttributeEncoder) error { + ae.Uint16(unix.IFA_UNSPEC, 0) + ae.Do(unix.IFA_ADDRESS, encodeIP(a.Address)) + if a.Local != nil { + ae.Do(unix.IFA_LOCAL, encodeIP(a.Local)) + } + if a.Broadcast != nil { + ae.Do(unix.IFA_BROADCAST, encodeIP(a.Broadcast)) + } + if a.Anycast != nil { + ae.Do(unix.IFA_ANYCAST, encodeIP(a.Anycast)) + } + if a.Multicast != nil { + ae.Do(unix.IFA_MULTICAST, encodeIP(a.Multicast)) + } + if a.Label != "" { + ae.String(unix.IFA_LABEL, a.Label) + } + ae.Uint32(unix.IFA_FLAGS, a.Flags) + + return nil +} + +// CacheInfo contains address information +type CacheInfo struct { + Preferred uint32 + Valid uint32 + Created uint32 + Updated uint32 +} + +// decode decodes raw bytes into a CacheInfo's fields. +func (c *CacheInfo) decode(b []byte) error { + if len(b) != 16 { + return fmt.Errorf("rtnetlink: incorrect CacheInfo size, want: 16, got: %d", len(b)) + } + + c.Preferred = nativeEndian.Uint32(b[0:4]) + c.Valid = nativeEndian.Uint32(b[4:8]) + c.Created = nativeEndian.Uint32(b[8:12]) + c.Updated = nativeEndian.Uint32(b[12:16]) + + return nil +} + +// encodeIP is a helper for validating and encoding IPv4 and IPv6 addresses as +// appropriate for the specified netlink attribute type. It should be used +// with (*netlink.AttributeEncoder).Do. +func encodeIP(ip net.IP) func() ([]byte, error) { + return func() ([]byte, error) { + // Don't allow nil or non 4/16-byte addresses. + if ip == nil || ip.To16() == nil { + return nil, fmt.Errorf("rtnetlink: cannot encode invalid IP address: %s", ip) + } + + if ip4 := ip.To4(); ip4 != nil { + // IPv4 address. + return ip4, nil + } + + // IPv6 address. + return ip, nil + } +} + +// decodeIP is a helper for validating and decoding IPv4 and IPv6 addresses as +// appropriate for the specified netlink attribute type. It should be used with +// (*netlink.AttributeDecoder).Do. +func decodeIP(ip *net.IP) func(b []byte) error { + return func(b []byte) error { + if l := len(b); l != 4 && l != 16 { + return fmt.Errorf("rtnetlink: invalid IP address length: %d", l) + } + + // We cannot retain b outside the closure, so make a copy into ip. + *ip = make(net.IP, len(b)) + copy(*ip, b) + return nil + } +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/conn.go b/vendor/github.com/jsimonetti/rtnetlink/v2/conn.go new file mode 100644 index 0000000..7bde518 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/conn.go @@ -0,0 +1,197 @@ +package rtnetlink + +import ( + "encoding" + "time" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + + "github.com/mdlayher/netlink" +) + +// A Conn is a route netlink connection. A Conn can be used to send and +// receive route netlink messages to and from netlink. +type Conn struct { + c conn + Link *LinkService + Address *AddressService + Route *RouteService + Neigh *NeighService + Rule *RuleService +} + +var _ conn = &netlink.Conn{} + +// A conn is a netlink connection, which can be swapped for tests. +type conn interface { + Close() error + Send(m netlink.Message) (netlink.Message, error) + Receive() ([]netlink.Message, error) + Execute(m netlink.Message) ([]netlink.Message, error) + SetOption(option netlink.ConnOption, enable bool) error + SetReadDeadline(t time.Time) error +} + +// Dial dials a route netlink connection. Config specifies optional +// configuration for the underlying netlink connection. If config is +// nil, a default configuration will be used. +func Dial(config *netlink.Config) (*Conn, error) { + c, err := netlink.Dial(unix.NETLINK_ROUTE, config) + if err != nil { + return nil, err + } + + return newConn(c), nil +} + +// newConn creates a Conn that wraps an existing *netlink.Conn for +// rtnetlink communications. It is used for testing. +func newConn(c conn) *Conn { + rtc := &Conn{ + c: c, + } + + rtc.Link = &LinkService{c: rtc} + rtc.Address = &AddressService{c: rtc} + rtc.Route = &RouteService{c: rtc} + rtc.Neigh = &NeighService{c: rtc} + rtc.Rule = &RuleService{c: rtc} + + return rtc +} + +// Close closes the connection. +func (c *Conn) Close() error { + return c.c.Close() +} + +// SetOption enables or disables a netlink socket option for the Conn. +func (c *Conn) SetOption(option netlink.ConnOption, enable bool) error { + return c.c.SetOption(option, enable) +} + +// SetReadDeadline sets the read deadline associated with the connection. +func (c *Conn) SetReadDeadline(t time.Time) error { + return c.c.SetReadDeadline(t) +} + +// Send sends a single Message to netlink, wrapping it in a netlink.Message +// using the specified generic netlink family and flags. On success, Send +// returns a copy of the netlink.Message with all parameters populated, for +// later validation. +func (c *Conn) Send(m Message, family uint16, flags netlink.HeaderFlags) (netlink.Message, error) { + nm := netlink.Message{ + Header: netlink.Header{ + Type: netlink.HeaderType(family), + Flags: flags, + }, + } + + mb, err := m.MarshalBinary() + if err != nil { + return netlink.Message{}, err + } + nm.Data = mb + reqnm, err := c.c.Send(nm) + if err != nil { + return netlink.Message{}, err + } + + return reqnm, nil +} + +// Receive receives one or more Messages from netlink. The netlink.Messages +// used to wrap each Message are available for later validation. +func (c *Conn) Receive() ([]Message, []netlink.Message, error) { + msgs, err := c.c.Receive() + if err != nil { + return nil, nil, err + } + + rtmsgs, err := unpackMessages(msgs) + if err != nil { + return nil, nil, err + } + + return rtmsgs, msgs, nil +} + +// Execute sends a single Message to netlink using Send, receives one or more +// replies using Receive, and then checks the validity of the replies against +// the request using netlink.Validate. +// +// Execute acquires a lock for the duration of the function call which blocks +// concurrent calls to Send and Receive, in order to ensure consistency between +// generic netlink request/reply messages. +// +// See the documentation of Send, Receive, and netlink.Validate for details +// about each function. +func (c *Conn) Execute(m Message, family uint16, flags netlink.HeaderFlags) ([]Message, error) { + nm, err := packMessage(m, family, flags) + if err != nil { + return nil, err + } + + msgs, err := c.c.Execute(nm) + if err != nil { + return nil, err + } + + return unpackMessages(msgs) +} + +// Message is the interface used for passing around different kinds of rtnetlink messages +type Message interface { + encoding.BinaryMarshaler + encoding.BinaryUnmarshaler + rtMessage() +} + +// packMessage packs a rtnetlink Message into a netlink.Message with the +// appropriate rtnetlink family and netlink flags. +func packMessage(m Message, family uint16, flags netlink.HeaderFlags) (netlink.Message, error) { + nm := netlink.Message{ + Header: netlink.Header{ + Type: netlink.HeaderType(family), + Flags: flags, + }, + } + + mb, err := m.MarshalBinary() + if err != nil { + return netlink.Message{}, err + } + nm.Data = mb + + return nm, nil +} + +// unpackMessages unpacks rtnetlink Messages from a slice of netlink.Messages. +func unpackMessages(msgs []netlink.Message) ([]Message, error) { + lmsgs := make([]Message, 0, len(msgs)) + + for _, nm := range msgs { + var m Message + switch nm.Header.Type { + case unix.RTM_GETLINK, unix.RTM_NEWLINK, unix.RTM_DELLINK: + m = &LinkMessage{} + case unix.RTM_GETADDR, unix.RTM_NEWADDR, unix.RTM_DELADDR: + m = &AddressMessage{} + case unix.RTM_GETROUTE, unix.RTM_NEWROUTE, unix.RTM_DELROUTE: + m = &RouteMessage{} + case unix.RTM_GETNEIGH, unix.RTM_NEWNEIGH, unix.RTM_DELNEIGH: + m = &NeighMessage{} + case unix.RTM_GETRULE, unix.RTM_NEWRULE, unix.RTM_DELRULE: + m = &RuleMessage{} + default: + continue + } + + if err := (m).UnmarshalBinary(nm.Data); err != nil { + return nil, err + } + lmsgs = append(lmsgs, m) + } + + return lmsgs, nil +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/doc.go b/vendor/github.com/jsimonetti/rtnetlink/v2/doc.go new file mode 100644 index 0000000..e8741db --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/doc.go @@ -0,0 +1,27 @@ +// Package rtnetlink allows the kernel's routing tables to be read and altered. +// Network routes, IP addresses, Link parameters, Neighbor setups, Queueing disciplines, +// Traffic classes and Packet classifiers may all be controlled. +// It is based on netlink messages. +// +// A convenient, high-level API wrapper is available using package rtnl: +// https://godoc.org/github.com/jsimonetti/rtnetlink/rtnl. +// +// The base rtnetlink library xplicitly only exposes a limited low-level API to rtnetlink. +// It is not the intention (nor wish) to create an iproute2 replacement. +// +// When in doubt about your message structure it can always be useful to look at the +// message send by iproute2 using 'strace -f -esendmsg' or similar. +// +// Another (and possibly even more flexible) way would be using 'nlmon' and wireshark. +// nlmod is a special kernel module which allows you to capture all (not just rtnetlink) +// netlink traffic inside the kernel. Be aware that this might be overwhelming on a system +// with a lot of netlink traffic. +// +// # modprobe nlmon +// # ip link add type nlmon +// # ip link set nlmon0 up +// +// At this point use wireshark or tcpdump on the nlmon0 interface to view all netlink traffic. +// +// Have a look at the examples for common uses of rtnetlink. +package rtnetlink diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/endian.go b/vendor/github.com/jsimonetti/rtnetlink/v2/endian.go new file mode 100644 index 0000000..14193d5 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/endian.go @@ -0,0 +1,13 @@ +package rtnetlink + +import ( + "encoding/binary" + + "github.com/mdlayher/netlink/nlenc" +) + +var nativeEndian binary.ByteOrder + +func init() { + nativeEndian = nlenc.NativeEndian() +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/fuzz-shell.nix b/vendor/github.com/jsimonetti/rtnetlink/v2/fuzz-shell.nix new file mode 100644 index 0000000..fb84a35 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/fuzz-shell.nix @@ -0,0 +1,15 @@ +with import { }; +pkgs.mkShell { + name = "go-fuzz"; + buildInputs = [ go ]; + shellHook = '' + echo "Fuzz with commands:" + echo "" + echo "go test -fuzz=AddressMessage - will start fuzzing Address Messages" + echo "go test -fuzz=LinkMessage - will start fuzzing Link Messages" + echo "go test -fuzz=NeighMessage - will start fuzzing Neigh Messages" + echo "go test -fuzz=RouteMessage - will start fuzzing Route Messages" + echo "go test -fuzz=RuleMessage - will start fuzzing Rule Messages" + echo "" + ''; +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_linux.go b/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_linux.go new file mode 100644 index 0000000..008597a --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_linux.go @@ -0,0 +1,218 @@ +//go:build linux +// +build linux + +package unix + +import ( + linux "golang.org/x/sys/unix" +) + +const ( + AF_INET = linux.AF_INET + AF_INET6 = linux.AF_INET6 + AF_UNSPEC = linux.AF_UNSPEC + NETLINK_ROUTE = linux.NETLINK_ROUTE + SizeofIfAddrmsg = linux.SizeofIfAddrmsg + SizeofIfInfomsg = linux.SizeofIfInfomsg + SizeofNdMsg = linux.SizeofNdMsg + SizeofRtMsg = linux.SizeofRtMsg + SizeofRtNexthop = linux.SizeofRtNexthop + RTM_NEWADDR = linux.RTM_NEWADDR + RTM_DELADDR = linux.RTM_DELADDR + RTM_GETADDR = linux.RTM_GETADDR + RTM_NEWLINK = linux.RTM_NEWLINK + RTM_DELLINK = linux.RTM_DELLINK + RTM_GETLINK = linux.RTM_GETLINK + RTM_SETLINK = linux.RTM_SETLINK + RTM_NEWROUTE = linux.RTM_NEWROUTE + RTM_DELROUTE = linux.RTM_DELROUTE + RTM_GETROUTE = linux.RTM_GETROUTE + RTM_NEWNEIGH = linux.RTM_NEWNEIGH + RTM_DELNEIGH = linux.RTM_DELNEIGH + RTM_GETNEIGH = linux.RTM_GETNEIGH + IFA_UNSPEC = linux.IFA_UNSPEC + IFA_ADDRESS = linux.IFA_ADDRESS + IFA_LOCAL = linux.IFA_LOCAL + IFA_LABEL = linux.IFA_LABEL + IFA_BROADCAST = linux.IFA_BROADCAST + IFA_ANYCAST = linux.IFA_ANYCAST + IFA_CACHEINFO = linux.IFA_CACHEINFO + IFA_MULTICAST = linux.IFA_MULTICAST + IFA_FLAGS = linux.IFA_FLAGS + IFF_UP = linux.IFF_UP + IFF_BROADCAST = linux.IFF_BROADCAST + IFF_LOOPBACK = linux.IFF_LOOPBACK + IFF_POINTOPOINT = linux.IFF_POINTOPOINT + IFF_MULTICAST = linux.IFF_MULTICAST + IFLA_UNSPEC = linux.IFLA_UNSPEC + IFLA_ADDRESS = linux.IFLA_ADDRESS + IFLA_BOND_UNSPEC = linux.IFLA_BOND_UNSPEC + IFLA_BOND_MODE = linux.IFLA_BOND_MODE + IFLA_BOND_ACTIVE_SLAVE = linux.IFLA_BOND_ACTIVE_SLAVE + IFLA_BOND_MIIMON = linux.IFLA_BOND_MIIMON + IFLA_BOND_UPDELAY = linux.IFLA_BOND_UPDELAY + IFLA_BOND_DOWNDELAY = linux.IFLA_BOND_DOWNDELAY + IFLA_BOND_USE_CARRIER = linux.IFLA_BOND_USE_CARRIER + IFLA_BOND_ARP_INTERVAL = linux.IFLA_BOND_ARP_INTERVAL + IFLA_BOND_ARP_IP_TARGET = linux.IFLA_BOND_ARP_IP_TARGET + IFLA_BOND_ARP_VALIDATE = linux.IFLA_BOND_ARP_VALIDATE + IFLA_BOND_ARP_ALL_TARGETS = linux.IFLA_BOND_ARP_ALL_TARGETS + IFLA_BOND_PRIMARY = linux.IFLA_BOND_PRIMARY + IFLA_BOND_PRIMARY_RESELECT = linux.IFLA_BOND_PRIMARY_RESELECT + IFLA_BOND_FAIL_OVER_MAC = linux.IFLA_BOND_FAIL_OVER_MAC + IFLA_BOND_XMIT_HASH_POLICY = linux.IFLA_BOND_XMIT_HASH_POLICY + IFLA_BOND_RESEND_IGMP = linux.IFLA_BOND_RESEND_IGMP + IFLA_BOND_NUM_PEER_NOTIF = linux.IFLA_BOND_NUM_PEER_NOTIF + IFLA_BOND_ALL_SLAVES_ACTIVE = linux.IFLA_BOND_ALL_SLAVES_ACTIVE + IFLA_BOND_MIN_LINKS = linux.IFLA_BOND_MIN_LINKS + IFLA_BOND_LP_INTERVAL = linux.IFLA_BOND_LP_INTERVAL + IFLA_BOND_PACKETS_PER_SLAVE = linux.IFLA_BOND_PACKETS_PER_SLAVE + IFLA_BOND_AD_LACP_RATE = linux.IFLA_BOND_AD_LACP_RATE + IFLA_BOND_AD_SELECT = linux.IFLA_BOND_AD_SELECT + IFLA_BOND_AD_INFO = linux.IFLA_BOND_AD_INFO + IFLA_BOND_AD_ACTOR_SYS_PRIO = linux.IFLA_BOND_AD_ACTOR_SYS_PRIO + IFLA_BOND_AD_USER_PORT_KEY = linux.IFLA_BOND_AD_USER_PORT_KEY + IFLA_BOND_AD_ACTOR_SYSTEM = linux.IFLA_BOND_AD_ACTOR_SYSTEM + IFLA_BOND_TLB_DYNAMIC_LB = linux.IFLA_BOND_TLB_DYNAMIC_LB + IFLA_BOND_PEER_NOTIF_DELAY = linux.IFLA_BOND_PEER_NOTIF_DELAY + IFLA_BOND_AD_LACP_ACTIVE = linux.IFLA_BOND_AD_LACP_ACTIVE + IFLA_BOND_MISSED_MAX = linux.IFLA_BOND_MISSED_MAX + IFLA_BOND_NS_IP6_TARGET = linux.IFLA_BOND_NS_IP6_TARGET + IFLA_BOND_AD_INFO_UNSPEC = linux.IFLA_BOND_AD_INFO_UNSPEC + IFLA_BOND_AD_INFO_AGGREGATOR = linux.IFLA_BOND_AD_INFO_AGGREGATOR + IFLA_BOND_AD_INFO_NUM_PORTS = linux.IFLA_BOND_AD_INFO_NUM_PORTS + IFLA_BOND_AD_INFO_ACTOR_KEY = linux.IFLA_BOND_AD_INFO_ACTOR_KEY + IFLA_BOND_AD_INFO_PARTNER_KEY = linux.IFLA_BOND_AD_INFO_PARTNER_KEY + IFLA_BOND_AD_INFO_PARTNER_MAC = linux.IFLA_BOND_AD_INFO_PARTNER_MAC + IFLA_BOND_SLAVE_UNSPEC = linux.IFLA_BOND_SLAVE_UNSPEC + IFLA_BOND_SLAVE_STATE = linux.IFLA_BOND_SLAVE_STATE + IFLA_BOND_SLAVE_MII_STATUS = linux.IFLA_BOND_SLAVE_MII_STATUS + IFLA_BOND_SLAVE_LINK_FAILURE_COUNT = linux.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT + IFLA_BOND_SLAVE_PERM_HWADDR = linux.IFLA_BOND_SLAVE_PERM_HWADDR + IFLA_BOND_SLAVE_QUEUE_ID = linux.IFLA_BOND_SLAVE_QUEUE_ID + IFLA_BOND_SLAVE_AD_AGGREGATOR_ID = linux.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID + IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE = linux.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE + IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE = linux.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE + IFLA_BOND_SLAVE_PRIO = linux.IFLA_BOND_SLAVE_PRIO + IFLA_BROADCAST = linux.IFLA_BROADCAST + IFLA_IFNAME = linux.IFLA_IFNAME + IFLA_MTU = linux.IFLA_MTU + IFLA_LINK = linux.IFLA_LINK + IFLA_QDISC = linux.IFLA_QDISC + IFLA_OPERSTATE = linux.IFLA_OPERSTATE + IFLA_STATS = linux.IFLA_STATS + IFLA_STATS64 = linux.IFLA_STATS64 + IFLA_TXQLEN = linux.IFLA_TXQLEN + IFLA_GROUP = linux.IFLA_GROUP + IFLA_LINKINFO = linux.IFLA_LINKINFO + IFLA_LINKMODE = linux.IFLA_LINKMODE + IFLA_IFALIAS = linux.IFLA_IFALIAS + IFLA_MASTER = linux.IFLA_MASTER + IFLA_CARRIER = linux.IFLA_CARRIER + IFLA_CARRIER_CHANGES = linux.IFLA_CARRIER_CHANGES + IFLA_CARRIER_UP_COUNT = linux.IFLA_CARRIER_UP_COUNT + IFLA_CARRIER_DOWN_COUNT = linux.IFLA_CARRIER_DOWN_COUNT + IFLA_PHYS_PORT_ID = linux.IFLA_PHYS_PORT_ID + IFLA_PHYS_SWITCH_ID = linux.IFLA_PHYS_SWITCH_ID + IFLA_PHYS_PORT_NAME = linux.IFLA_PHYS_PORT_NAME + IFLA_INFO_KIND = linux.IFLA_INFO_KIND + IFLA_INFO_SLAVE_KIND = linux.IFLA_INFO_SLAVE_KIND + IFLA_INFO_DATA = linux.IFLA_INFO_DATA + IFLA_INFO_SLAVE_DATA = linux.IFLA_INFO_SLAVE_DATA + IFLA_NET_NS_PID = linux.IFLA_NET_NS_PID + IFLA_NET_NS_FD = linux.IFLA_NET_NS_FD + IFLA_NETKIT_UNSPEC = linux.IFLA_NETKIT_UNSPEC + IFLA_NETKIT_PEER_INFO = linux.IFLA_NETKIT_PEER_INFO + IFLA_NETKIT_PRIMARY = linux.IFLA_NETKIT_PRIMARY + IFLA_NETKIT_POLICY = linux.IFLA_NETKIT_POLICY + IFLA_NETKIT_PEER_POLICY = linux.IFLA_NETKIT_PEER_POLICY + IFLA_NETKIT_MODE = linux.IFLA_NETKIT_MODE + IFLA_XDP = linux.IFLA_XDP + IFLA_XDP_FD = linux.IFLA_XDP_FD + IFLA_XDP_ATTACHED = linux.IFLA_XDP_ATTACHED + IFLA_XDP_FLAGS = linux.IFLA_XDP_FLAGS + IFLA_XDP_PROG_ID = linux.IFLA_XDP_PROG_ID + IFLA_XDP_EXPECTED_FD = linux.IFLA_XDP_EXPECTED_FD + XDP_FLAGS_DRV_MODE = linux.XDP_FLAGS_DRV_MODE + XDP_FLAGS_SKB_MODE = linux.XDP_FLAGS_SKB_MODE + XDP_FLAGS_HW_MODE = linux.XDP_FLAGS_HW_MODE + XDP_FLAGS_MODES = linux.XDP_FLAGS_MODES + XDP_FLAGS_MASK = linux.XDP_FLAGS_MASK + XDP_FLAGS_REPLACE = linux.XDP_FLAGS_REPLACE + XDP_FLAGS_UPDATE_IF_NOEXIST = linux.XDP_FLAGS_UPDATE_IF_NOEXIST + LWTUNNEL_ENCAP_MPLS = linux.LWTUNNEL_ENCAP_MPLS + MPLS_IPTUNNEL_DST = linux.MPLS_IPTUNNEL_DST + MPLS_IPTUNNEL_TTL = linux.MPLS_IPTUNNEL_TTL + NDA_UNSPEC = linux.NDA_UNSPEC + NDA_DST = linux.NDA_DST + NDA_LLADDR = linux.NDA_LLADDR + NDA_CACHEINFO = linux.NDA_CACHEINFO + NDA_IFINDEX = linux.NDA_IFINDEX + RTA_UNSPEC = linux.RTA_UNSPEC + RTA_DST = linux.RTA_DST + RTA_ENCAP = linux.RTA_ENCAP + RTA_ENCAP_TYPE = linux.RTA_ENCAP_TYPE + RTA_PREFSRC = linux.RTA_PREFSRC + RTA_GATEWAY = linux.RTA_GATEWAY + RTA_OIF = linux.RTA_OIF + RTA_PRIORITY = linux.RTA_PRIORITY + RTA_TABLE = linux.RTA_TABLE + RTA_MARK = linux.RTA_MARK + RTA_EXPIRES = linux.RTA_EXPIRES + RTA_METRICS = linux.RTA_METRICS + RTA_MULTIPATH = linux.RTA_MULTIPATH + RTA_PREF = linux.RTA_PREF + RTAX_ADVMSS = linux.RTAX_ADVMSS + RTAX_FEATURES = linux.RTAX_FEATURES + RTAX_INITCWND = linux.RTAX_INITCWND + RTAX_INITRWND = linux.RTAX_INITRWND + RTAX_MTU = linux.RTAX_MTU + NTF_PROXY = linux.NTF_PROXY + RTN_UNICAST = linux.RTN_UNICAST + RT_TABLE_MAIN = linux.RT_TABLE_MAIN + RTPROT_BOOT = linux.RTPROT_BOOT + RTPROT_STATIC = linux.RTPROT_STATIC + RT_SCOPE_UNIVERSE = linux.RT_SCOPE_UNIVERSE + RT_SCOPE_HOST = linux.RT_SCOPE_HOST + RT_SCOPE_LINK = linux.RT_SCOPE_LINK + RTM_NEWRULE = linux.RTM_NEWRULE + RTM_GETRULE = linux.RTM_GETRULE + RTM_DELRULE = linux.RTM_DELRULE + FRA_UNSPEC = linux.FRA_UNSPEC + FRA_DST = linux.FRA_DST + FRA_SRC = linux.FRA_SRC + FRA_IIFNAME = linux.FRA_IIFNAME + FRA_GOTO = linux.FRA_GOTO + FRA_UNUSED2 = linux.FRA_UNUSED2 + FRA_PRIORITY = linux.FRA_PRIORITY + FRA_UNUSED3 = linux.FRA_UNUSED3 + FRA_UNUSED4 = linux.FRA_UNUSED4 + FRA_UNUSED5 = linux.FRA_UNUSED5 + FRA_FWMARK = linux.FRA_FWMARK + FRA_FLOW = linux.FRA_FLOW + FRA_TUN_ID = linux.FRA_TUN_ID + FRA_SUPPRESS_IFGROUP = linux.FRA_SUPPRESS_IFGROUP + FRA_SUPPRESS_PREFIXLEN = linux.FRA_SUPPRESS_PREFIXLEN + FRA_TABLE = linux.FRA_TABLE + FRA_FWMASK = linux.FRA_FWMASK + FRA_OIFNAME = linux.FRA_OIFNAME + FRA_PAD = linux.FRA_PAD + FRA_L3MDEV = linux.FRA_L3MDEV + FRA_UID_RANGE = linux.FRA_UID_RANGE + FRA_PROTOCOL = linux.FRA_PROTOCOL + FRA_IP_PROTO = linux.FRA_IP_PROTO + FRA_SPORT_RANGE = linux.FRA_SPORT_RANGE + FRA_DPORT_RANGE = linux.FRA_DPORT_RANGE + NETKIT_NEXT = linux.NETKIT_NEXT + NETKIT_PASS = linux.NETKIT_PASS + NETKIT_DROP = linux.NETKIT_DROP + NETKIT_REDIRECT = linux.NETKIT_REDIRECT + NETKIT_L2 = linux.NETKIT_L2 + NETKIT_L3 = linux.NETKIT_L3 + CLONE_NEWNET = linux.CLONE_NEWNET + O_RDONLY = linux.O_RDONLY + O_CLOEXEC = linux.O_CLOEXEC +) + +var Gettid = linux.Gettid +var Unshare = linux.Unshare diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_other.go b/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_other.go new file mode 100644 index 0000000..8a30d79 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/internal/unix/types_other.go @@ -0,0 +1,219 @@ +//go:build !linux +// +build !linux + +package unix + +const ( + AF_INET = 0x2 + AF_INET6 = 0xa + AF_UNSPEC = 0x0 + NETLINK_ROUTE = 0x0 + SizeofIfAddrmsg = 0x8 + SizeofIfInfomsg = 0x10 + SizeofNdMsg = 0xc + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 + RTM_NEWADDR = 0x14 + RTM_DELADDR = 0x15 + RTM_GETADDR = 0x16 + RTM_NEWLINK = 0x10 + RTM_DELLINK = 0x11 + RTM_GETLINK = 0x12 + RTM_SETLINK = 0x13 + RTM_NEWROUTE = 0x18 + RTM_DELROUTE = 0x19 + RTM_GETROUTE = 0x1a + RTM_NEWNEIGH = 0x1c + RTM_DELNEIGH = 0x1d + RTM_GETNEIGH = 0x1e + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFA_FLAGS = 0x8 + IFF_UP = 0x1 + IFF_BROADCAST = 0x2 + IFF_LOOPBACK = 0x8 + IFF_POINTOPOINT = 0x10 + IFF_MULTICAST = 0x1000 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BOND_UNSPEC = 0x0 + IFLA_BOND_MODE = 0x1 + IFLA_BOND_ACTIVE_SLAVE = 0x2 + IFLA_BOND_MIIMON = 0x3 + IFLA_BOND_UPDELAY = 0x4 + IFLA_BOND_DOWNDELAY = 0x5 + IFLA_BOND_USE_CARRIER = 0x6 + IFLA_BOND_ARP_INTERVAL = 0x7 + IFLA_BOND_ARP_IP_TARGET = 0x8 + IFLA_BOND_ARP_VALIDATE = 0x9 + IFLA_BOND_ARP_ALL_TARGETS = 0xa + IFLA_BOND_PRIMARY = 0xb + IFLA_BOND_PRIMARY_RESELECT = 0xc + IFLA_BOND_FAIL_OVER_MAC = 0xd + IFLA_BOND_XMIT_HASH_POLICY = 0xe + IFLA_BOND_RESEND_IGMP = 0xf + IFLA_BOND_NUM_PEER_NOTIF = 0x10 + IFLA_BOND_ALL_SLAVES_ACTIVE = 0x11 + IFLA_BOND_MIN_LINKS = 0x12 + IFLA_BOND_LP_INTERVAL = 0x13 + IFLA_BOND_PACKETS_PER_SLAVE = 0x14 + IFLA_BOND_AD_LACP_RATE = 0x15 + IFLA_BOND_AD_SELECT = 0x16 + IFLA_BOND_AD_INFO = 0x17 + IFLA_BOND_AD_ACTOR_SYS_PRIO = 0x18 + IFLA_BOND_AD_USER_PORT_KEY = 0x19 + IFLA_BOND_AD_ACTOR_SYSTEM = 0x1a + IFLA_BOND_TLB_DYNAMIC_LB = 0x1b + IFLA_BOND_PEER_NOTIF_DELAY = 0x1c + IFLA_BOND_AD_LACP_ACTIVE = 0x1d + IFLA_BOND_MISSED_MAX = 0x1e + IFLA_BOND_NS_IP6_TARGET = 0x1f + IFLA_BOND_AD_INFO_UNSPEC = 0x0 + IFLA_BOND_AD_INFO_AGGREGATOR = 0x1 + IFLA_BOND_AD_INFO_NUM_PORTS = 0x2 + IFLA_BOND_AD_INFO_ACTOR_KEY = 0x3 + IFLA_BOND_AD_INFO_PARTNER_KEY = 0x4 + IFLA_BOND_AD_INFO_PARTNER_MAC = 0x5 + IFLA_BOND_SLAVE_UNSPEC = 0x0 + IFLA_BOND_SLAVE_STATE = 0x1 + IFLA_BOND_SLAVE_MII_STATUS = 0x2 + IFLA_BOND_SLAVE_LINK_FAILURE_COUNT = 0x3 + IFLA_BOND_SLAVE_PERM_HWADDR = 0x4 + IFLA_BOND_SLAVE_QUEUE_ID = 0x5 + IFLA_BOND_SLAVE_AD_AGGREGATOR_ID = 0x6 + IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE = 0x7 + IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE = 0x8 + IFLA_BOND_SLAVE_PRIO = 0x9 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_OPERSTATE = 0x10 + IFLA_STATS = 0x7 + IFLA_STATS64 = 0x17 + IFLA_TXQLEN = 0xd + IFLA_GROUP = 0x1b + IFLA_LINKINFO = 0x12 + IFLA_LINKMODE = 0x11 + IFLA_IFALIAS = 0x14 + IFLA_MASTER = 0xa + IFLA_CARRIER = 0x21 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_CARRIER_UP_COUNT = 0x2f + IFLA_CARRIER_DOWN_COUNT = 0x30 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_INFO_KIND = 0x1 + IFLA_INFO_SLAVE_KIND = 0x4 + IFLA_INFO_DATA = 0x2 + IFLA_INFO_SLAVE_DATA = 0x5 + IFLA_NET_NS_PID = 0x13 + IFLA_NET_NS_FD = 0x1c + IFLA_NETKIT_UNSPEC = 0x0 + IFLA_NETKIT_PEER_INFO = 0x1 + IFLA_NETKIT_PRIMARY = 0x2 + IFLA_NETKIT_POLICY = 0x3 + IFLA_NETKIT_PEER_POLICY = 0x4 + IFLA_NETKIT_MODE = 0x5 + IFLA_XDP = 0x2b + IFLA_XDP_FD = 0x1 + IFLA_XDP_ATTACHED = 0x2 + IFLA_XDP_FLAGS = 0x3 + IFLA_XDP_PROG_ID = 0x4 + IFLA_XDP_EXPECTED_FD = 0x8 + XDP_FLAGS_DRV_MODE = 0x4 + XDP_FLAGS_SKB_MODE = 0x2 + XDP_FLAGS_HW_MODE = 0x8 + XDP_FLAGS_MODES = 0xe + XDP_FLAGS_MASK = 0x1f + XDP_FLAGS_REPLACE = 0x10 + XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1 + LWTUNNEL_ENCAP_MPLS = 0x1 + MPLS_IPTUNNEL_DST = 0x1 + MPLS_IPTUNNEL_TTL = 0x2 + NDA_UNSPEC = 0x0 + NDA_DST = 0x1 + NDA_LLADDR = 0x2 + NDA_CACHEINFO = 0x3 + NDA_IFINDEX = 0x8 + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_ENCAP = 0x16 + RTA_ENCAP_TYPE = 0x15 + RTA_PREFSRC = 0x7 + RTA_GATEWAY = 0x5 + RTA_OIF = 0x4 + RTA_PRIORITY = 0x6 + RTA_TABLE = 0xf + RTA_MARK = 0x10 + RTA_EXPIRES = 0x17 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_PREF = 0x14 + RTAX_ADVMSS = 0x8 + RTAX_FEATURES = 0xc + RTAX_INITCWND = 0xb + RTAX_INITRWND = 0xe + RTAX_MTU = 0x2 + NTF_PROXY = 0x8 + RTN_UNICAST = 0x1 + RT_TABLE_MAIN = 0xfe + RTPROT_BOOT = 0x3 + RTPROT_STATIC = 0x4 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_HOST = 0xfe + RT_SCOPE_LINK = 0xfd + RTM_NEWRULE = 0x20 + RTM_GETRULE = 0x22 + RTM_DELRULE = 0x21 + FRA_UNSPEC = 0x0 + FRA_DST = 0x1 + FRA_SRC = 0x2 + FRA_IIFNAME = 0x3 + FRA_GOTO = 0x4 + FRA_UNUSED2 = 0x5 + FRA_PRIORITY = 0x6 + FRA_UNUSED3 = 0x7 + FRA_UNUSED4 = 0x8 + FRA_UNUSED5 = 0x9 + FRA_FWMARK = 0xa + FRA_FLOW = 0xb + FRA_TUN_ID = 0xc + FRA_SUPPRESS_IFGROUP = 0xd + FRA_SUPPRESS_PREFIXLEN = 0xe + FRA_TABLE = 0xf + FRA_FWMASK = 0x10 + FRA_OIFNAME = 0x11 + FRA_PAD = 0x12 + FRA_L3MDEV = 0x13 + FRA_UID_RANGE = 0x14 + FRA_PROTOCOL = 0x15 + FRA_IP_PROTO = 0x16 + FRA_SPORT_RANGE = 0x17 + FRA_DPORT_RANGE = 0x18 + NETKIT_NEXT = -0x1 + NETKIT_PASS = 0x0 + NETKIT_DROP = 0x2 + NETKIT_REDIRECT = 0x7 + NETKIT_L2 = 0x0 + NETKIT_L3 = 0x1 + CLONE_NEWNET = 0x40000000 + O_RDONLY = 0x0 + O_CLOEXEC = 0x80000 +) + +func Unshare(_ int) error { + return nil +} + +func Gettid() int { + return 0 +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/link.go b/vendor/github.com/jsimonetti/rtnetlink/v2/link.go new file mode 100644 index 0000000..4400d5a --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/link.go @@ -0,0 +1,778 @@ +package rtnetlink + +import ( + "errors" + "fmt" + "net" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + + "github.com/mdlayher/netlink" +) + +var ( + // errInvalidLinkMessage is returned when a LinkMessage is malformed. + errInvalidLinkMessage = errors.New("rtnetlink LinkMessage is invalid or too short") + + // errInvalidLinkMessageAttr is returned when link attributes are malformed. + errInvalidLinkMessageAttr = errors.New("rtnetlink LinkMessage has a wrong attribute data length") +) + +var _ Message = &LinkMessage{} + +// A LinkMessage is a route netlink link message. +type LinkMessage struct { + // Always set to AF_UNSPEC (0) + Family uint16 + + // Device Type + Type uint16 + + // Unique interface index, using a nonzero value with + // NewLink will instruct the kernel to create a + // device with the given index (kernel 3.7+ required) + Index uint32 + + // Contains device flags, see netdevice(7) + Flags uint32 + + // Change Flags, specifies which flags will be affected by the Flags field + Change uint32 + + // Attributes List + Attributes *LinkAttributes +} + +// MarshalBinary marshals a LinkMessage into a byte slice. +func (m *LinkMessage) MarshalBinary() ([]byte, error) { + b := make([]byte, unix.SizeofIfInfomsg) + + b[0] = 0 // Family + b[1] = 0 // reserved + nativeEndian.PutUint16(b[2:4], m.Type) + nativeEndian.PutUint32(b[4:8], m.Index) + nativeEndian.PutUint32(b[8:12], m.Flags) + nativeEndian.PutUint32(b[12:16], m.Change) + + if m.Attributes != nil { + if m.Attributes.Info != nil && m.Attributes.Info.Data != nil { + if verifier, ok := m.Attributes.Info.Data.(LinkDriverVerifier); ok { + if err := verifier.Verify(m); err != nil { + return nil, err + } + } + } + + ae := netlink.NewAttributeEncoder() + ae.ByteOrder = nativeEndian + err := m.Attributes.encode(ae) + if err != nil { + return nil, err + } + + a, err := ae.Encode() + if err != nil { + return nil, err + } + + return append(b, a...), nil + } + + return b, nil +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a LinkMessage. +func (m *LinkMessage) UnmarshalBinary(b []byte) error { + l := len(b) + if l < unix.SizeofIfInfomsg { + return errInvalidLinkMessage + } + + m.Family = nativeEndian.Uint16(b[0:2]) + m.Type = nativeEndian.Uint16(b[2:4]) + m.Index = nativeEndian.Uint32(b[4:8]) + m.Flags = nativeEndian.Uint32(b[8:12]) + m.Change = nativeEndian.Uint32(b[12:16]) + + if l > unix.SizeofIfInfomsg { + m.Attributes = &LinkAttributes{} + ad, err := netlink.NewAttributeDecoder(b[16:]) + if err != nil { + return err + } + ad.ByteOrder = nativeEndian + err = m.Attributes.decode(ad) + if err != nil { + return err + } + } + + return nil +} + +// rtMessage is an empty method to sattisfy the Message interface. +func (*LinkMessage) rtMessage() {} + +// LinkService is used to retrieve rtnetlink family information. +type LinkService struct { + c *Conn +} + +// execute executes the request and returns the messages as a LinkMessage slice +func (l *LinkService) execute(m Message, family uint16, flags netlink.HeaderFlags) ([]LinkMessage, error) { + msgs, err := l.c.Execute(m, family, flags) + + links := make([]LinkMessage, len(msgs)) + for i := range msgs { + links[i] = *msgs[i].(*LinkMessage) + } + + return links, err +} + +// New creates a new interface using the LinkMessage information. +func (l *LinkService) New(req *LinkMessage) error { + flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl + _, err := l.execute(req, unix.RTM_NEWLINK, flags) + + return err +} + +// Delete removes an interface by index. +func (l *LinkService) Delete(index uint32) error { + req := &LinkMessage{ + Index: index, + } + + flags := netlink.Request | netlink.Acknowledge + _, err := l.c.Execute(req, unix.RTM_DELLINK, flags) + + return err +} + +// Get retrieves interface information by index. +func (l *LinkService) Get(index uint32) (LinkMessage, error) { + req := &LinkMessage{ + Index: index, + } + + flags := netlink.Request | netlink.DumpFiltered + links, err := l.execute(req, unix.RTM_GETLINK, flags) + + if len(links) != 1 { + return LinkMessage{}, fmt.Errorf("too many/little matches, expected 1, actual %d", len(links)) + } + + return links[0], err +} + +// Set sets interface attributes according to the LinkMessage information. +// +// ref: https://lwn.net/Articles/236919/ +// We explicitly use RTM_NEWLINK to set link attributes instead of +// RTM_SETLINK because: +// - using RTM_SETLINK is actually an old rtnetlink API, not supporting most +// attributes common today +// - using RTM_NEWLINK is the preferred way to create AND update links +// - RTM_NEWLINK is backward compatible to RTM_SETLINK +func (l *LinkService) Set(req *LinkMessage) error { + flags := netlink.Request | netlink.Acknowledge + _, err := l.c.Execute(req, unix.RTM_NEWLINK, flags) + + return err +} + +func (l *LinkService) list(kind string) ([]LinkMessage, error) { + req := &LinkMessage{} + if kind != "" { + req.Attributes = &LinkAttributes{ + Info: &LinkInfo{Kind: kind}, + } + } + + flags := netlink.Request | netlink.Dump + return l.execute(req, unix.RTM_GETLINK, flags) +} + +// ListByKind retrieves all interfaces of a specific kind. +func (l *LinkService) ListByKind(kind string) ([]LinkMessage, error) { + return l.list(kind) +} + +// List retrieves all interfaces. +func (l *LinkService) List() ([]LinkMessage, error) { + return l.list("") +} + +// LinkAttributes contains all attributes for an interface. +type LinkAttributes struct { + Address net.HardwareAddr // Interface L2 address + Alias *string // Interface alias name + Broadcast net.HardwareAddr // L2 broadcast address + Carrier *uint8 // Current physical link state of the interface. + CarrierChanges *uint32 // Number of times the link has seen a change from UP to DOWN and vice versa + CarrierUpCount *uint32 // Number of times the link has been up + CarrierDownCount *uint32 // Number of times the link has been down + Index *uint32 // System-wide interface unique index identifier + Info *LinkInfo // Detailed Interface Information + LinkMode *uint8 // Interface link mode + MTU uint32 // MTU of the device + Name string // Device name + NetDevGroup *uint32 // Interface network device group + OperationalState OperationalState // Interface operation state + PhysPortID *string // Interface unique physical port identifier within the NIC + PhysPortName *string // Interface physical port name within the NIC + PhysSwitchID *string // Unique physical switch identifier of a switch this port belongs to + QueueDisc string // Queueing discipline + Master *uint32 // Master device index (0 value un-enslaves) + Stats *LinkStats // Interface Statistics + Stats64 *LinkStats64 // Interface Statistics (64 bits version) + TxQueueLen *uint32 // Interface transmit queue len in number of packets + Type uint32 // Link type + XDP *LinkXDP // Express Data Patch Information + NetNS *NetNS // Interface network namespace +} + +// OperationalState represents an interface's operational state. +type OperationalState uint8 + +// Constants that represent operational state of an interface +// +// Adapted from https://elixir.bootlin.com/linux/v4.19.2/source/include/uapi/linux/if.h#L166 +const ( + OperStateUnknown OperationalState = iota // status could not be determined + OperStateNotPresent // down, due to some missing component (typically hardware) + OperStateDown // down, either administratively or due to a fault + OperStateLowerLayerDown // down, due to lower-layer interfaces + OperStateTesting // operationally down, in some test mode + OperStateDormant // down, waiting for some external event + OperStateUp // interface is in a state to send and receive packets +) + +// unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage. +func (a *LinkAttributes) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.IFLA_UNSPEC: + // unused attribute + case unix.IFLA_ADDRESS: + l := len(ad.Bytes()) + if l < 4 || l > 32 { + return errInvalidLinkMessageAttr + } + a.Address = ad.Bytes() + case unix.IFLA_IFALIAS: + v := ad.String() + a.Alias = &v + case unix.IFLA_BROADCAST: + l := len(ad.Bytes()) + if l < 4 || l > 32 { + return errInvalidLinkMessageAttr + } + a.Broadcast = ad.Bytes() + case unix.IFLA_CARRIER: + v := ad.Uint8() + a.Carrier = &v + case unix.IFLA_CARRIER_CHANGES: + v := ad.Uint32() + a.CarrierChanges = &v + case unix.IFLA_CARRIER_UP_COUNT: + v := ad.Uint32() + a.CarrierUpCount = &v + case unix.IFLA_CARRIER_DOWN_COUNT: + v := ad.Uint32() + a.CarrierDownCount = &v + case unix.IFLA_GROUP: + v := ad.Uint32() + a.NetDevGroup = &v + case unix.IFLA_MTU: + a.MTU = ad.Uint32() + case unix.IFLA_IFNAME: + a.Name = ad.String() + case unix.IFLA_LINK: + a.Type = ad.Uint32() + case unix.IFLA_LINKINFO: + a.Info = &LinkInfo{} + ad.Nested(a.Info.decode) + case unix.IFLA_LINKMODE: + v := ad.Uint8() + a.LinkMode = &v + case unix.IFLA_MASTER: + v := ad.Uint32() + a.Master = &v + case unix.IFLA_OPERSTATE: + a.OperationalState = OperationalState(ad.Uint8()) + case unix.IFLA_PHYS_PORT_ID: + v := ad.String() + a.PhysPortID = &v + case unix.IFLA_PHYS_SWITCH_ID: + v := ad.String() + a.PhysSwitchID = &v + case unix.IFLA_PHYS_PORT_NAME: + v := ad.String() + a.PhysPortName = &v + case unix.IFLA_QDISC: + a.QueueDisc = ad.String() + case unix.IFLA_STATS: + a.Stats = &LinkStats{} + err := a.Stats.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + case unix.IFLA_STATS64: + a.Stats64 = &LinkStats64{} + err := a.Stats64.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + case unix.IFLA_TXQLEN: + v := ad.Uint32() + a.TxQueueLen = &v + case unix.IFLA_XDP: + a.XDP = &LinkXDP{} + ad.Nested(a.XDP.decode) + } + } + + return nil +} + +// MarshalBinary marshals a LinkAttributes into a byte slice. +func (a *LinkAttributes) encode(ae *netlink.AttributeEncoder) error { + if a.Name != "" { + ae.String(unix.IFLA_IFNAME, a.Name) + } + + if a.Type != 0 { + ae.Uint32(unix.IFLA_LINK, a.Type) + } + + if a.QueueDisc != "" { + ae.String(unix.IFLA_QDISC, a.QueueDisc) + } + + if a.MTU != 0 { + ae.Uint32(unix.IFLA_MTU, a.MTU) + } + + if len(a.Address) != 0 { + ae.Bytes(unix.IFLA_ADDRESS, a.Address) + } + + if len(a.Broadcast) != 0 { + ae.Bytes(unix.IFLA_BROADCAST, a.Broadcast) + } + + if a.OperationalState != OperStateUnknown { + ae.Uint8(unix.IFLA_OPERSTATE, uint8(a.OperationalState)) + } + + if a.Info != nil { + nae := netlink.NewAttributeEncoder() + nae.ByteOrder = ae.ByteOrder + + err := a.Info.encode(nae) + if err != nil { + return err + } + b, err := nae.Encode() + if err != nil { + return err + } + ae.Bytes(unix.IFLA_LINKINFO, b) + } + + if a.XDP != nil { + nae := netlink.NewAttributeEncoder() + nae.ByteOrder = ae.ByteOrder + + err := a.XDP.encode(nae) + if err != nil { + return err + } + b, err := nae.Encode() + if err != nil { + return err + } + + ae.Bytes(unix.IFLA_XDP, b) + } + + if a.Master != nil { + ae.Uint32(unix.IFLA_MASTER, *a.Master) + } + + if a.NetNS != nil { + ae.Uint32(a.NetNS.value()) + } + + return nil +} + +// LinkStats contains packet statistics +type LinkStats struct { + RXPackets uint32 // total packets received + TXPackets uint32 // total packets transmitted + RXBytes uint32 // total bytes received + TXBytes uint32 // total bytes transmitted + RXErrors uint32 // bad packets received + TXErrors uint32 // packet transmit problems + RXDropped uint32 // no space in linux buffers + TXDropped uint32 // no space available in linux + Multicast uint32 // multicast packets received + Collisions uint32 + + // detailed rx_errors: + RXLengthErrors uint32 + RXOverErrors uint32 // receiver ring buff overflow + RXCRCErrors uint32 // recved pkt with crc error + RXFrameErrors uint32 // recv'd frame alignment error + RXFIFOErrors uint32 // recv'r fifo overrun + RXMissedErrors uint32 // receiver missed packet + + // detailed tx_errors + TXAbortedErrors uint32 + TXCarrierErrors uint32 + TXFIFOErrors uint32 + TXHeartbeatErrors uint32 + TXWindowErrors uint32 + + // for cslip etc + RXCompressed uint32 + TXCompressed uint32 + + RXNoHandler uint32 // dropped, no handler found +} + +// unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage. +func (a *LinkStats) unmarshalBinary(b []byte) error { + l := len(b) + if l != 92 && l != 96 { + return fmt.Errorf("incorrect LinkMessage size, want: 92 or 96, got: %d", len(b)) + } + + a.RXPackets = nativeEndian.Uint32(b[0:4]) + a.TXPackets = nativeEndian.Uint32(b[4:8]) + a.RXBytes = nativeEndian.Uint32(b[8:12]) + a.TXBytes = nativeEndian.Uint32(b[12:16]) + a.RXErrors = nativeEndian.Uint32(b[16:20]) + a.TXErrors = nativeEndian.Uint32(b[20:24]) + a.RXDropped = nativeEndian.Uint32(b[24:28]) + a.TXDropped = nativeEndian.Uint32(b[28:32]) + a.Multicast = nativeEndian.Uint32(b[32:36]) + a.Collisions = nativeEndian.Uint32(b[36:40]) + + a.RXLengthErrors = nativeEndian.Uint32(b[40:44]) + a.RXOverErrors = nativeEndian.Uint32(b[44:48]) + a.RXCRCErrors = nativeEndian.Uint32(b[48:52]) + a.RXFrameErrors = nativeEndian.Uint32(b[52:56]) + a.RXFIFOErrors = nativeEndian.Uint32(b[56:60]) + a.RXMissedErrors = nativeEndian.Uint32(b[60:64]) + + a.TXAbortedErrors = nativeEndian.Uint32(b[64:68]) + a.TXCarrierErrors = nativeEndian.Uint32(b[68:72]) + a.TXFIFOErrors = nativeEndian.Uint32(b[72:76]) + a.TXHeartbeatErrors = nativeEndian.Uint32(b[76:80]) + a.TXWindowErrors = nativeEndian.Uint32(b[80:84]) + + a.RXCompressed = nativeEndian.Uint32(b[84:88]) + a.TXCompressed = nativeEndian.Uint32(b[88:92]) + + if l == 96 { // kernel 4.6+ + a.RXNoHandler = nativeEndian.Uint32(b[92:96]) + } + + return nil +} + +// LinkStats64 contains packet statistics +type LinkStats64 struct { + RXPackets uint64 // total packets received + TXPackets uint64 // total packets transmitted + RXBytes uint64 // total bytes received + TXBytes uint64 // total bytes transmitted + RXErrors uint64 // bad packets received + TXErrors uint64 // packet transmit problems + RXDropped uint64 // no space in linux buffers + TXDropped uint64 // no space available in linux + Multicast uint64 // multicast packets received + Collisions uint64 + + // detailed rx_errors: + RXLengthErrors uint64 + RXOverErrors uint64 // receiver ring buff overflow + RXCRCErrors uint64 // recved pkt with crc error + RXFrameErrors uint64 // recv'd frame alignment error + RXFIFOErrors uint64 // recv'r fifo overrun + RXMissedErrors uint64 // receiver missed packet + + // detailed tx_errors + TXAbortedErrors uint64 + TXCarrierErrors uint64 + TXFIFOErrors uint64 + TXHeartbeatErrors uint64 + TXWindowErrors uint64 + + // for cslip etc + RXCompressed uint64 + TXCompressed uint64 + + RXNoHandler uint64 // dropped, no handler found + + RXOtherhostDropped uint64 // Number of packets dropped due to mismatch in destination MAC address. +} + +// unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage. +func (a *LinkStats64) unmarshalBinary(b []byte) error { + l := len(b) + if l != 184 && l != 192 && l != 200 { + return fmt.Errorf("incorrect size, want: 184 or 192 or 200") + } + + a.RXPackets = nativeEndian.Uint64(b[0:8]) + a.TXPackets = nativeEndian.Uint64(b[8:16]) + a.RXBytes = nativeEndian.Uint64(b[16:24]) + a.TXBytes = nativeEndian.Uint64(b[24:32]) + a.RXErrors = nativeEndian.Uint64(b[32:40]) + a.TXErrors = nativeEndian.Uint64(b[40:48]) + a.RXDropped = nativeEndian.Uint64(b[48:56]) + a.TXDropped = nativeEndian.Uint64(b[56:64]) + a.Multicast = nativeEndian.Uint64(b[64:72]) + a.Collisions = nativeEndian.Uint64(b[72:80]) + + a.RXLengthErrors = nativeEndian.Uint64(b[80:88]) + a.RXOverErrors = nativeEndian.Uint64(b[88:96]) + a.RXCRCErrors = nativeEndian.Uint64(b[96:104]) + a.RXFrameErrors = nativeEndian.Uint64(b[104:112]) + a.RXFIFOErrors = nativeEndian.Uint64(b[112:120]) + a.RXMissedErrors = nativeEndian.Uint64(b[120:128]) + + a.TXAbortedErrors = nativeEndian.Uint64(b[128:136]) + a.TXCarrierErrors = nativeEndian.Uint64(b[136:144]) + a.TXFIFOErrors = nativeEndian.Uint64(b[144:152]) + a.TXHeartbeatErrors = nativeEndian.Uint64(b[152:160]) + a.TXWindowErrors = nativeEndian.Uint64(b[160:168]) + + a.RXCompressed = nativeEndian.Uint64(b[168:176]) + a.TXCompressed = nativeEndian.Uint64(b[176:184]) + + if l > 191 { // kernel 4.6+ + a.RXNoHandler = nativeEndian.Uint64(b[184:192]) + } + + if l > 199 { // kernel 5.19+ + a.RXOtherhostDropped = nativeEndian.Uint64(b[192:200]) + } + + return nil +} + +var ( + // registeredDrivers is the global map of registered drivers + registeredDrivers = make(map[string]LinkDriver) + + // registeredSlaveDrivers is the global map of registered slave drivers + registeredSlaveDrivers = make(map[string]LinkDriver) +) + +// RegisterDriver registers a driver with the link service +// This allows the driver to be used to encode/decode the link data +// +// This function is not threadsafe. This should not be used after Dial +func RegisterDriver(d LinkDriver) error { + if _, ok := d.(LinkSlaveDriver); ok { + if _, ok := registeredSlaveDrivers[d.Kind()]; ok { + return fmt.Errorf("driver %s already registered", d.Kind()) + } + registeredSlaveDrivers[d.Kind()] = d + return nil + } + if _, ok := registeredDrivers[d.Kind()]; ok { + return fmt.Errorf("driver %s already registered", d.Kind()) + } + registeredDrivers[d.Kind()] = d + return nil +} + +// getDriver returns the driver instance for the given kind, and true if the driver is registered +// it returns the default (LinkData) driver, and false if the driver is not registered +func getDriver(kind string, slave bool) (LinkDriver, bool) { + if slave { + if t, ok := registeredSlaveDrivers[kind]; ok { + return t.New(), true + } + + return &LinkData{Name: kind, Slave: true}, false + } + if t, ok := registeredDrivers[kind]; ok { + return t.New(), true + } + + return &LinkData{Name: kind}, false +} + +// LinkDriver is the interface that wraps link-specific Encode, Decode, and Kind methods +type LinkDriver interface { + // New returns a new instance of the LinkDriver + New() LinkDriver + + // Encode the driver data into the netlink message attribute + Encode(*netlink.AttributeEncoder) error + + // Decode the driver data from the netlink message attribute + Decode(*netlink.AttributeDecoder) error + + // Return the driver kind as string, this will be matched with the LinkInfo.Kind to find a driver to decode the data + Kind() string +} + +// LinkSlaveDriver defines a LinkDriver with Slave method +type LinkSlaveDriver interface { + LinkDriver + + // Slave method specifies driver is a slave link info + Slave() +} + +// LinkDriverVerifier defines a LinkDriver with Verify method +type LinkDriverVerifier interface { + LinkDriver + + // Verify function run before Encode function to check for correctness and + // pass related values that otherwise unavailable to the driver + Verify(*LinkMessage) error +} + +// LinkData implements the default LinkDriver interface for not registered drivers +type LinkData struct { + Name string + Data []byte + Slave bool +} + +var _ LinkDriver = &LinkData{} + +func (d *LinkData) New() LinkDriver { + return &LinkData{} +} + +func (d *LinkData) Decode(ad *netlink.AttributeDecoder) error { + d.Data = ad.Bytes() + return nil +} + +func (d *LinkData) Encode(ae *netlink.AttributeEncoder) error { + if len(d.Data) == 0 { + return nil + } + if d.Slave { + ae.Bytes(unix.IFLA_INFO_SLAVE_DATA, d.Data) + } else { + ae.Bytes(unix.IFLA_INFO_DATA, d.Data) + } + return nil +} + +func (d *LinkData) Kind() string { + return d.Name +} + +// LinkInfo contains data for specific network types +type LinkInfo struct { + Kind string // Driver name + Data LinkDriver // Driver specific configuration stored as nested Netlink messages + SlaveKind string // Slave driver name + SlaveData LinkDriver // Slave driver specific configuration +} + +func (i *LinkInfo) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.IFLA_INFO_KIND: + i.Kind = ad.String() + case unix.IFLA_INFO_SLAVE_KIND: + i.SlaveKind = ad.String() + case unix.IFLA_INFO_DATA: + driver, found := getDriver(i.Kind, false) + i.Data = driver + if found { + ad.Nested(i.Data.Decode) + continue + } + _ = i.Data.Decode(ad) + case unix.IFLA_INFO_SLAVE_DATA: + driver, found := getDriver(i.SlaveKind, true) + i.SlaveData = driver + if found { + ad.Nested(i.SlaveData.Decode) + continue + } + _ = i.SlaveData.Decode(ad) + } + } + return nil +} + +func (i *LinkInfo) encode(ae *netlink.AttributeEncoder) error { + ae.String(unix.IFLA_INFO_KIND, i.Kind) + if i.Data != nil { + if i.Kind != i.Data.Kind() { + return fmt.Errorf("driver kind %s is not equal to info kind %s", i.Data.Kind(), i.Kind) + } + if _, ok := i.Data.(*LinkData); ok { + _ = i.Data.Encode(ae) + } else { + ae.Nested(unix.IFLA_INFO_DATA, i.Data.Encode) + } + } + if i.SlaveData != nil { + if i.SlaveKind != i.SlaveData.Kind() { + return fmt.Errorf("slave driver kind %s is not equal to slave info kind %s", i.SlaveData.Kind(), i.SlaveKind) + } + ae.String(unix.IFLA_INFO_SLAVE_KIND, i.SlaveKind) + if _, ok := i.SlaveData.(*LinkData); ok { + _ = i.SlaveData.Encode(ae) + } else { + ae.Nested(unix.IFLA_INFO_SLAVE_DATA, i.SlaveData.Encode) + } + } + + return nil +} + +// LinkXDP holds Express Data Path specific information +type LinkXDP struct { + FD int32 + ExpectedFD int32 + Attached uint8 + Flags uint32 + ProgID uint32 +} + +func (xdp *LinkXDP) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.IFLA_XDP_FD: + xdp.FD = ad.Int32() + case unix.IFLA_XDP_EXPECTED_FD: + xdp.ExpectedFD = ad.Int32() + case unix.IFLA_XDP_ATTACHED: + xdp.Attached = ad.Uint8() + case unix.IFLA_XDP_FLAGS: + xdp.Flags = ad.Uint32() + case unix.IFLA_XDP_PROG_ID: + xdp.ProgID = ad.Uint32() + } + } + return nil +} + +func (xdp *LinkXDP) encode(ae *netlink.AttributeEncoder) error { + ae.Int32(unix.IFLA_XDP_FD, xdp.FD) + ae.Int32(unix.IFLA_XDP_EXPECTED_FD, xdp.ExpectedFD) + ae.Uint32(unix.IFLA_XDP_FLAGS, xdp.Flags) + // XDP_ATTACHED and XDP_PROG_ID are things that can only be returned by the + // kernel, so we don't encode them. source: + // https://elixir.bootlin.com/linux/v5.10.15/source/net/core/rtnetlink.c#L2894 + return nil +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/neigh.go b/vendor/github.com/jsimonetti/rtnetlink/v2/neigh.go new file mode 100644 index 0000000..1394b38 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/neigh.go @@ -0,0 +1,216 @@ +package rtnetlink + +import ( + "errors" + "fmt" + "net" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + + "github.com/mdlayher/netlink" +) + +var ( + // errInvalidNeighMessage is returned when a LinkMessage is malformed. + errInvalidNeighMessage = errors.New("rtnetlink NeighMessage is invalid or too short") +) + +var _ Message = &NeighMessage{} + +// A NeighMessage is a route netlink neighbor message. +type NeighMessage struct { + // Always set to AF_UNSPEC (0) + Family uint16 + + // Unique interface index + Index uint32 + + // Neighbor State is a bitmask of neighbor states (see rtnetlink(7)) + State uint16 + + // Neighbor flags + Flags uint8 + + // Neighbor type + Type uint8 + + // Attributes List + Attributes *NeighAttributes +} + +// MarshalBinary marshals a NeighMessage into a byte slice. +func (m *NeighMessage) MarshalBinary() ([]byte, error) { + b := make([]byte, unix.SizeofNdMsg) + + b[0] = uint8(m.Family) + // bytes 2-4 are padding + nativeEndian.PutUint32(b[4:8], m.Index) + nativeEndian.PutUint16(b[8:10], m.State) + b[10] = m.Flags + b[11] = m.Type + + if m.Attributes != nil { + ae := netlink.NewAttributeEncoder() + ae.ByteOrder = nativeEndian + err := m.Attributes.encode(ae) + if err != nil { + return nil, err + } + + a, err := ae.Encode() + if err != nil { + return nil, err + } + + return append(b, a...), nil + } + return b, nil +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a NeighMessage. +func (m *NeighMessage) UnmarshalBinary(b []byte) error { + l := len(b) + if l < unix.SizeofNdMsg { + return errInvalidNeighMessage + } + + m.Family = uint16(b[0]) + m.Index = nativeEndian.Uint32(b[4:8]) + m.State = nativeEndian.Uint16(b[8:10]) + m.Flags = b[10] + m.Type = b[11] + + if l > unix.SizeofNdMsg { + m.Attributes = &NeighAttributes{} + ad, err := netlink.NewAttributeDecoder(b[unix.SizeofNdMsg:]) + if err != nil { + return err + } + ad.ByteOrder = nativeEndian + err = m.Attributes.decode(ad) + if err != nil { + return err + } + } + + return nil +} + +// rtMessage is an empty method to sattisfy the Message interface. +func (*NeighMessage) rtMessage() {} + +// NeighService is used to retrieve rtnetlink family information. +type NeighService struct { + c *Conn +} + +// New creates a new interface using the LinkMessage information. +func (l *NeighService) New(req *NeighMessage) error { + flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl + _, err := l.c.Execute(req, unix.RTM_NEWNEIGH, flags) + if err != nil { + return err + } + + return nil +} + +// Delete removes an neighbor entry by index. +func (l *NeighService) Delete(index uint32) error { + req := &NeighMessage{} + + flags := netlink.Request | netlink.Acknowledge + _, err := l.c.Execute(req, unix.RTM_DELNEIGH, flags) + if err != nil { + return err + } + + return nil +} + +// List retrieves all neighbors. +func (l *NeighService) List() ([]NeighMessage, error) { + req := NeighMessage{} + + flags := netlink.Request | netlink.Dump + msgs, err := l.c.Execute(&req, unix.RTM_GETNEIGH, flags) + if err != nil { + return nil, err + } + + neighs := make([]NeighMessage, len(msgs)) + for i := range msgs { + neighs[i] = *msgs[i].(*NeighMessage) + } + + return neighs, nil +} + +// NeighCacheInfo contains neigh information +type NeighCacheInfo struct { + Confirmed uint32 + Used uint32 + Updated uint32 + RefCount uint32 +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a NeighMessage. +func (n *NeighCacheInfo) unmarshalBinary(b []byte) error { + if len(b) != 16 { + return fmt.Errorf("incorrect size, want: 16, got: %d", len(b)) + } + + n.Confirmed = nativeEndian.Uint32(b[0:4]) + n.Used = nativeEndian.Uint32(b[4:8]) + n.Updated = nativeEndian.Uint32(b[8:12]) + n.RefCount = nativeEndian.Uint32(b[12:16]) + + return nil +} + +// NeighAttributes contains all attributes for a neighbor. +type NeighAttributes struct { + Address net.IP // a neighbor cache n/w layer destination address + LLAddress net.HardwareAddr // a neighbor cache link layer address + CacheInfo *NeighCacheInfo // cache statistics + IfIndex uint32 +} + +func (a *NeighAttributes) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.NDA_UNSPEC: + // unused attribute + case unix.NDA_DST: + a.Address = ad.Bytes() + case unix.NDA_LLADDR: + // Allow IEEE 802 MAC-48, EUI-48, EUI-64, or 20-octet + // IP over InfiniBand link-layer addresses + l := len(ad.Bytes()) + if l == 0 { + // Ignore empty addresses. + continue + } + a.LLAddress = ad.Bytes() + case unix.NDA_CACHEINFO: + a.CacheInfo = &NeighCacheInfo{} + err := a.CacheInfo.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + case unix.NDA_IFINDEX: + a.IfIndex = ad.Uint32() + } + } + + return nil +} + +func (a *NeighAttributes) encode(ae *netlink.AttributeEncoder) error { + ae.Uint16(unix.NDA_UNSPEC, 0) + ae.Bytes(unix.NDA_DST, a.Address) + ae.Bytes(unix.NDA_LLADDR, a.LLAddress) + ae.Uint32(unix.NDA_IFINDEX, a.IfIndex) + + return nil +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/netns.go b/vendor/github.com/jsimonetti/rtnetlink/v2/netns.go new file mode 100644 index 0000000..55c48c1 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/netns.go @@ -0,0 +1,46 @@ +package rtnetlink + +import ( + "github.com/jsimonetti/rtnetlink/v2/internal/unix" +) + +// NetNS represents a Linux network namespace handle to specify in +// [LinkAttributes]. +// +// Use [NetNSForPID] to create a handle to the network namespace of an existing +// PID, or [NetNSForFD] for a handle to an existing network namespace created by +// another library. +type NetNS struct { + fd *uint32 + pid *uint32 +} + +// NetNSForPID returns a handle to the network namespace of an existing process +// given its pid. The process must be alive when the NetNS is used in any API +// calls. +// +// The resulting NetNS doesn't hold a hard reference to the netns (it doesn't +// increase its refcount) and becomes invalid when the process it points to +// dies. +func NetNSForPID(pid uint32) *NetNS { + return &NetNS{pid: &pid} +} + +// NetNSForFD returns a handle to an existing network namespace created by +// another library. It does not clone fd or manage its lifecycle in any way. +// The caller is responsible for making sure the underlying fd stays alive +// for the duration of any API calls using the NetNS. +func NetNSForFD(fd uint32) *NetNS { + return &NetNS{fd: &fd} +} + +// value returns the type and value of the NetNS for use in netlink attributes. +func (ns *NetNS) value() (uint16, uint32) { + if ns.fd != nil { + return unix.IFLA_NET_NS_FD, *ns.fd + } + if ns.pid != nil { + return unix.IFLA_NET_NS_PID, *ns.pid + } + return 0, 0 +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/route.go b/vendor/github.com/jsimonetti/rtnetlink/v2/route.go new file mode 100644 index 0000000..5b70c68 --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/route.go @@ -0,0 +1,626 @@ +package rtnetlink + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "unsafe" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + + "github.com/mdlayher/netlink" +) + +var ( + // errInvalidRouteMessage is returned when a RouteMessage is malformed. + errInvalidRouteMessage = errors.New("rtnetlink RouteMessage is invalid or too short") + + // errInvalidRouteMessageAttr is returned when link attributes are malformed. + errInvalidRouteMessageAttr = errors.New("rtnetlink RouteMessage has a wrong attribute data length") +) + +var _ Message = &RouteMessage{} + +type RouteMessage struct { + Family uint8 // Address family (current unix.AF_INET or unix.AF_INET6) + DstLength uint8 // Length of destination prefix + SrcLength uint8 // Length of source prefix + Tos uint8 // TOS filter + Table uint8 // Routing table ID + Protocol uint8 // Routing protocol + Scope uint8 // Distance to the destination + Type uint8 // Route type + Flags uint32 + + Attributes RouteAttributes +} + +func (m *RouteMessage) MarshalBinary() ([]byte, error) { + b := make([]byte, unix.SizeofRtMsg) + + b[0] = m.Family + b[1] = m.DstLength + b[2] = m.SrcLength + b[3] = m.Tos + b[4] = m.Table + b[5] = m.Protocol + b[6] = m.Scope + b[7] = m.Type + nativeEndian.PutUint32(b[8:12], m.Flags) + + ae := netlink.NewAttributeEncoder() + err := m.Attributes.encode(ae) + if err != nil { + return nil, err + } + + a, err := ae.Encode() + if err != nil { + return nil, err + } + + return append(b, a...), nil +} + +func (m *RouteMessage) UnmarshalBinary(b []byte) error { + l := len(b) + if l < unix.SizeofRtMsg { + return errInvalidRouteMessage + } + + m.Family = uint8(b[0]) + m.DstLength = uint8(b[1]) + m.SrcLength = uint8(b[2]) + m.Tos = uint8(b[3]) + m.Table = uint8(b[4]) + m.Protocol = uint8(b[5]) + m.Scope = uint8(b[6]) + m.Type = uint8(b[7]) + m.Flags = nativeEndian.Uint32(b[8:12]) + + if l > unix.SizeofRtMsg { + ad, err := netlink.NewAttributeDecoder(b[unix.SizeofRtMsg:]) + if err != nil { + return err + } + + var ra RouteAttributes + if err := ra.decode(ad); err != nil { + return err + } + + // Must consume errors from decoder before returning. + if err := ad.Err(); err != nil { + return fmt.Errorf("invalid route message attributes: %v", err) + } + m.Attributes = ra + } + + return nil +} + +// rtMessage is an empty method to sattisfy the Message interface. +func (*RouteMessage) rtMessage() {} + +type RouteService struct { + c *Conn +} + +func (r *RouteService) execute(m Message, family uint16, flags netlink.HeaderFlags) ([]RouteMessage, error) { + msgs, err := r.c.Execute(m, family, flags) + + routes := make([]RouteMessage, len(msgs)) + for i := range msgs { + routes[i] = *msgs[i].(*RouteMessage) + } + + return routes, err +} + +// Add new route +func (r *RouteService) Add(req *RouteMessage) error { + flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl + _, err := r.c.Execute(req, unix.RTM_NEWROUTE, flags) + + return err +} + +// Replace or add new route +func (r *RouteService) Replace(req *RouteMessage) error { + flags := netlink.Request | netlink.Create | netlink.Replace | netlink.Acknowledge + _, err := r.c.Execute(req, unix.RTM_NEWROUTE, flags) + + return err +} + +// Delete existing route +func (r *RouteService) Delete(req *RouteMessage) error { + flags := netlink.Request | netlink.Acknowledge + _, err := r.c.Execute(req, unix.RTM_DELROUTE, flags) + + return err +} + +// Get Route(s) +func (r *RouteService) Get(req *RouteMessage) ([]RouteMessage, error) { + flags := netlink.Request | netlink.DumpFiltered + return r.execute(req, unix.RTM_GETROUTE, flags) +} + +// List all routes +func (r *RouteService) List() ([]RouteMessage, error) { + flags := netlink.Request | netlink.Dump + return r.execute(&RouteMessage{}, unix.RTM_GETROUTE, flags) +} + +type RouteAttributes struct { + Dst net.IP + Src net.IP + Gateway net.IP + OutIface uint32 + Priority uint32 + Table uint32 + Mark uint32 + Pref *uint8 + Expires *uint32 + Metrics *RouteMetrics + Multipath []NextHop +} + +func (a *RouteAttributes) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.RTA_UNSPEC: + // unused attribute + case unix.RTA_DST: + ad.Do(decodeIP(&a.Dst)) + case unix.RTA_PREFSRC: + ad.Do(decodeIP(&a.Src)) + case unix.RTA_GATEWAY: + ad.Do(decodeIP(&a.Gateway)) + case unix.RTA_OIF: + a.OutIface = ad.Uint32() + case unix.RTA_PRIORITY: + a.Priority = ad.Uint32() + case unix.RTA_TABLE: + a.Table = ad.Uint32() + case unix.RTA_MARK: + a.Mark = ad.Uint32() + case unix.RTA_EXPIRES: + timeout := ad.Uint32() + a.Expires = &timeout + case unix.RTA_METRICS: + a.Metrics = &RouteMetrics{} + ad.Nested(a.Metrics.decode) + case unix.RTA_MULTIPATH: + ad.Do(a.parseMultipath) + case unix.RTA_PREF: + pref := ad.Uint8() + a.Pref = &pref + } + } + + return nil +} + +func (a *RouteAttributes) encode(ae *netlink.AttributeEncoder) error { + if a.Dst != nil { + ae.Do(unix.RTA_DST, encodeIP(a.Dst)) + } + + if a.Src != nil { + ae.Do(unix.RTA_PREFSRC, encodeIP(a.Src)) + } + + if a.Gateway != nil { + ae.Do(unix.RTA_GATEWAY, encodeIP(a.Gateway)) + } + + if a.OutIface != 0 { + ae.Uint32(unix.RTA_OIF, a.OutIface) + } + + if a.Priority != 0 { + ae.Uint32(unix.RTA_PRIORITY, a.Priority) + } + + if a.Table != 0 { + ae.Uint32(unix.RTA_TABLE, a.Table) + } + + if a.Mark != 0 { + ae.Uint32(unix.RTA_MARK, a.Mark) + } + + if a.Pref != nil { + ae.Uint8(unix.RTA_PREF, *a.Pref) + } + + if a.Expires != nil { + ae.Uint32(unix.RTA_EXPIRES, *a.Expires) + } + + if a.Metrics != nil { + ae.Nested(unix.RTA_METRICS, a.Metrics.encode) + } + + if len(a.Multipath) > 0 { + ae.Do(unix.RTA_MULTIPATH, a.encodeMultipath) + } + + return nil +} + +// RouteMetrics holds some advanced metrics for a route +type RouteMetrics struct { + AdvMSS uint32 + Features uint32 + InitCwnd uint32 + InitRwnd uint32 + MTU uint32 +} + +func (rm *RouteMetrics) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.RTAX_ADVMSS: + rm.AdvMSS = ad.Uint32() + case unix.RTAX_FEATURES: + rm.Features = ad.Uint32() + case unix.RTAX_INITCWND: + rm.InitCwnd = ad.Uint32() + case unix.RTAX_INITRWND: + rm.InitRwnd = ad.Uint32() + case unix.RTAX_MTU: + rm.MTU = ad.Uint32() + } + } + + // ad.Err call handled by Nested method in calling attribute decoder. + return nil +} + +func (rm *RouteMetrics) encode(ae *netlink.AttributeEncoder) error { + if rm.AdvMSS != 0 { + ae.Uint32(unix.RTAX_ADVMSS, rm.AdvMSS) + } + + if rm.Features != 0 { + ae.Uint32(unix.RTAX_FEATURES, rm.Features) + } + + if rm.InitCwnd != 0 { + ae.Uint32(unix.RTAX_INITCWND, rm.InitCwnd) + } + + if rm.InitRwnd != 0 { + ae.Uint32(unix.RTAX_INITRWND, rm.InitRwnd) + } + + if rm.MTU != 0 { + ae.Uint32(unix.RTAX_MTU, rm.MTU) + } + + return nil +} + +// TODO(mdlayher): probably eliminate Length field from the API to avoid the +// caller possibly tampering with it since we can compute it. + +// RTNextHop represents the netlink rtnexthop struct (not an attribute) +type RTNextHop struct { + Length uint16 // length of this hop including nested values + Flags uint8 // flags defined in rtnetlink.h line 311 + Hops uint8 + IfIndex uint32 // the interface index number +} + +// NextHop wraps struct rtnexthop to provide access to nested attributes +type NextHop struct { + Hop RTNextHop // a rtnexthop struct + Gateway net.IP // that struct's nested Gateway attribute + MPLS []MPLSNextHop // Any MPLS next hops for a route. +} + +func (a *RouteAttributes) encodeMultipath() ([]byte, error) { + var b []byte + for _, nh := range a.Multipath { + // Encode the attributes first so their total length can be used to + // compute the length of each (rtnexthop, attributes) pair. + ae := netlink.NewAttributeEncoder() + + if nh.Gateway != nil { + ae.Do(unix.RTA_GATEWAY, encodeIP(nh.Gateway)) + } + + if len(nh.MPLS) > 0 { + // TODO(mdlayher): validation over different encapsulation types, + // and ensure that only one can be set. + ae.Uint16(unix.RTA_ENCAP_TYPE, unix.LWTUNNEL_ENCAP_MPLS) + ae.Nested(unix.RTA_ENCAP, nh.encodeEncap) + } + + ab, err := ae.Encode() + if err != nil { + return nil, err + } + + // Assume the caller wants the length updated so they don't have to + // keep track of it themselves when encoding attributes. + nh.Hop.Length = unix.SizeofRtNexthop + uint16(len(ab)) + var nhb [unix.SizeofRtNexthop]byte + + copy( + nhb[:], + (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(&nh.Hop)))[:], + ) + + // rtnexthop first, then attributes. + b = append(b, nhb[:]...) + b = append(b, ab...) + } + + return b, nil +} + +// parseMultipath consumes RTA_MULTIPATH data into RouteAttributes. +func (a *RouteAttributes) parseMultipath(b []byte) error { + // We cannot retain b after the function returns, so make a copy of the + // bytes up front for the multipathParser. + buf := make([]byte, len(b)) + copy(buf, b) + + // Iterate until no more bytes remain in the buffer or an error occurs. + mpp := &multipathParser{b: buf} + for mpp.Next() { + // Each iteration reads a fixed length RTNextHop structure immediately + // followed by its associated netlink attributes with optional data. + nh := NextHop{Hop: mpp.RTNextHop()} + if err := nh.decode(mpp.AttributeDecoder()); err != nil { + return err + } + + // Stop iteration early if the data was malformed, or otherwise append + // this NextHop to the Multipath field. + if err := mpp.Err(); err != nil { + return err + } + + a.Multipath = append(a.Multipath, nh) + } + + // Check the error when Next returns false. + return mpp.Err() +} + +// decode decodes netlink attribute values into a NextHop. +func (nh *NextHop) decode(ad *netlink.AttributeDecoder) error { + if ad == nil { + // Invalid decoder, do nothing. + return nil + } + + // If encapsulation is present, we won't know how to deal with it until we + // identify the right type and then later parse the nested attribute bytes. + var ( + encapType uint16 + encapBuf []byte + ) + + for ad.Next() { + switch ad.Type() { + case unix.RTA_ENCAP: + encapBuf = ad.Bytes() + case unix.RTA_ENCAP_TYPE: + encapType = ad.Uint16() + case unix.RTA_GATEWAY: + ad.Do(decodeIP(&nh.Gateway)) + } + } + + if err := ad.Err(); err != nil { + return err + } + + if encapType != 0 && encapBuf != nil { + // Found encapsulation, start decoding it from the buffer. + return nh.decodeEncap(encapType, encapBuf) + } + + return nil +} + +// An MPLSNextHop is a route next hop using MPLS encapsulation. +type MPLSNextHop struct { + Label int + TrafficClass int + BottomOfStack bool + TTL uint8 +} + +// TODO(mdlayher): MPLSNextHop TTL vs MPLS_IPTUNNEL_TTL. What's the difference? + +// encodeEncap encodes netlink attribute values related to encapsulation from +// a NextHop. +func (nh *NextHop) encodeEncap(ae *netlink.AttributeEncoder) error { + // TODO: this only handles MPLS encapsulation as that is all we support. + + // Allocate enough space for an MPLS label stack. + var ( + i int + b = make([]byte, 4*len(nh.MPLS)) + ) + + for _, mnh := range nh.MPLS { + // Pack the following: + // - label: 20 bits + // - traffic class: 3 bits + // - bottom-of-stack: 1 bit + // - TTL: 8 bits + binary.BigEndian.PutUint32(b[i:i+4], uint32(mnh.Label)<<12) + + b[i+2] |= byte(mnh.TrafficClass) << 1 + + if mnh.BottomOfStack { + b[i+2] |= 1 + } + + b[i+3] = mnh.TTL + + // Advance in the buffer to begin storing the next label. + i += 4 + } + + // Finally store the output bytes. + ae.Bytes(unix.MPLS_IPTUNNEL_DST, b) + return nil +} + +// decodeEncap decodes netlink attribute values related to encapsulation into a +// NextHop. +func (nh *NextHop) decodeEncap(typ uint16, b []byte) error { + if typ != unix.LWTUNNEL_ENCAP_MPLS { + // TODO: handle other encapsulation types as needed. + return nil + } + + // MPLS labels are stored as big endian bytes. + ad, err := netlink.NewAttributeDecoder(b) + if err != nil { + return err + } + + for ad.Next() { + switch ad.Type() { + case unix.MPLS_IPTUNNEL_DST: + // Every 4 bytes stores another MPLS label, so make sure the stored + // bytes are divisible by exactly 4. + b := ad.Bytes() + if len(b)%4 != 0 { + return errInvalidRouteMessageAttr + } + + for i := 0; i < len(b); i += 4 { + n := binary.BigEndian.Uint32(b[i : i+4]) + + // For reference, see: + // https://en.wikipedia.org/wiki/Multiprotocol_Label_Switching#Operation + nh.MPLS = append(nh.MPLS, MPLSNextHop{ + Label: int(n) >> 12, + TrafficClass: int(n & 0xe00 >> 9), + BottomOfStack: n&0x100 != 0, + TTL: uint8(n & 0xff), + }) + } + } + } + + return ad.Err() +} + +// A multipathParser parses packed RTNextHop and netlink attributes into +// multipath attributes for an rtnetlink route. +type multipathParser struct { + // Any errors which occurred during parsing. + err error + + // The underlying buffer and a pointer to the reading position. + b []byte + i int + + // The length of the next set of netlink attributes. + alen int +} + +// Next continues iteration until an error occurs or no bytes remain. +func (mpp *multipathParser) Next() bool { + if mpp.err != nil { + return false + } + + // Are there enough bytes left for another RTNextHop, or 0 for EOF? + n := len(mpp.b[mpp.i:]) + switch { + case n == 0: + // EOF. + return false + case n >= unix.SizeofRtNexthop: + return true + default: + mpp.err = errInvalidRouteMessageAttr + return false + } +} + +// Err returns any errors encountered while parsing. +func (mpp *multipathParser) Err() error { return mpp.err } + +// RTNextHop parses the next RTNextHop structure from the buffer. +func (mpp *multipathParser) RTNextHop() RTNextHop { + if mpp.err != nil { + return RTNextHop{} + } + + if len(mpp.b)-mpp.i < unix.SizeofRtNexthop { + // Out of bounds access, not enough data for a valid RTNextHop. + mpp.err = errInvalidRouteMessageAttr + return RTNextHop{} + } + + // Consume an RTNextHop from the buffer by copying its bytes into an output + // structure while also verifying that the size of each structure is equal + // to avoid any out-of-bounds unsafe memory access. + var rtnh RTNextHop + next := mpp.b[mpp.i : mpp.i+unix.SizeofRtNexthop] + + if unix.SizeofRtNexthop != len(next) { + panic("rtnetlink: invalid RTNextHop structure size, panicking to avoid out-of-bounds unsafe access") + } + + copy( + (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(&rtnh)))[:], + (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(&next[0])))[:], + ) + + if rtnh.Length < unix.SizeofRtNexthop { + // Length value is invalid. + mpp.err = errInvalidRouteMessageAttr + return RTNextHop{} + } + + // Compute the length of the next set of attributes using the Length value + // in the RTNextHop, minus the size of that fixed length structure itself. + // Then, advance the pointer to be ready to read those attributes. + mpp.alen = int(rtnh.Length) - unix.SizeofRtNexthop + mpp.i += unix.SizeofRtNexthop + + return rtnh +} + +// AttributeDecoder returns a netlink.AttributeDecoder pointed at the next set +// of netlink attributes from the buffer. +func (mpp *multipathParser) AttributeDecoder() *netlink.AttributeDecoder { + if mpp.err != nil { + return nil + } + + // Ensure the attributes length value computed while parsing the rtnexthop + // fits within the actual slice. + if len(mpp.b[mpp.i:]) < mpp.alen { + mpp.err = errInvalidRouteMessageAttr + return nil + } + + // Consume the next set of netlink attributes from the buffer and advance + // the pointer to the next RTNextHop or EOF once that is complete. + ad, err := netlink.NewAttributeDecoder(mpp.b[mpp.i : mpp.i+mpp.alen]) + if err != nil { + mpp.err = err + return nil + } + + mpp.i += mpp.alen + + return ad +} diff --git a/vendor/github.com/jsimonetti/rtnetlink/v2/rule.go b/vendor/github.com/jsimonetti/rtnetlink/v2/rule.go new file mode 100644 index 0000000..6e35d8a --- /dev/null +++ b/vendor/github.com/jsimonetti/rtnetlink/v2/rule.go @@ -0,0 +1,394 @@ +package rtnetlink + +import ( + "bytes" + "encoding/binary" + "errors" + "net" + + "github.com/jsimonetti/rtnetlink/v2/internal/unix" + "github.com/mdlayher/netlink" +) + +var ( + // errInvalidRuleMessage is returned when a RuleMessage is malformed. + errInvalidRuleMessage = errors.New("rtnetlink RuleMessage is invalid or too short") + + // errInvalidRuleAttribute is returned when a RuleMessage contains an unknown attribute. + errInvalidRuleAttribute = errors.New("rtnetlink RuleMessage contains an unknown Attribute") +) + +var _ Message = &RuleMessage{} + +// A RuleMessage is a route netlink link message. +type RuleMessage struct { + // Address family + Family uint8 + + // Length of destination prefix + DstLength uint8 + + // Length of source prefix + SrcLength uint8 + + // Rule TOS + TOS uint8 + + // Routing table identifier + Table uint8 + + // Rule action + Action uint8 + + // Rule flags + Flags uint32 + + // Attributes List + Attributes *RuleAttributes +} + +// MarshalBinary marshals a LinkMessage into a byte slice. +func (m *RuleMessage) MarshalBinary() ([]byte, error) { + b := make([]byte, 12) + + // fib_rule_hdr + b[0] = m.Family + b[1] = m.DstLength + b[2] = m.SrcLength + b[3] = m.TOS + b[4] = m.Table + b[7] = m.Action + nativeEndian.PutUint32(b[8:12], m.Flags) + + if m.Attributes != nil { + ae := netlink.NewAttributeEncoder() + ae.ByteOrder = nativeEndian + err := m.Attributes.encode(ae) + if err != nil { + return nil, err + } + + a, err := ae.Encode() + if err != nil { + return nil, err + } + + return append(b, a...), nil + } + + return b, nil +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a LinkMessage. +func (m *RuleMessage) UnmarshalBinary(b []byte) error { + l := len(b) + if l < 12 { + return errInvalidRuleMessage + } + m.Family = b[0] + m.DstLength = b[1] + m.SrcLength = b[2] + m.TOS = b[3] + m.Table = b[4] + // b[5] and b[6] are reserved fields + m.Action = b[7] + m.Flags = nativeEndian.Uint32(b[8:12]) + + if l > 12 { + m.Attributes = &RuleAttributes{} + ad, err := netlink.NewAttributeDecoder(b[12:]) + if err != nil { + return err + } + ad.ByteOrder = nativeEndian + return m.Attributes.decode(ad) + } + return nil +} + +// rtMessage is an empty method to sattisfy the Message interface. +func (*RuleMessage) rtMessage() {} + +// RuleService is used to retrieve rtnetlink family information. +type RuleService struct { + c *Conn +} + +func (r *RuleService) execute(m Message, family uint16, flags netlink.HeaderFlags) ([]RuleMessage, error) { + msgs, err := r.c.Execute(m, family, flags) + + rules := make([]RuleMessage, len(msgs)) + for i := range msgs { + rules[i] = *msgs[i].(*RuleMessage) + } + + return rules, err +} + +// Add new rule +func (r *RuleService) Add(req *RuleMessage) error { + flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl + _, err := r.c.Execute(req, unix.RTM_NEWRULE, flags) + + return err +} + +// Replace or add new rule +func (r *RuleService) Replace(req *RuleMessage) error { + flags := netlink.Request | netlink.Create | netlink.Replace | netlink.Acknowledge + _, err := r.c.Execute(req, unix.RTM_NEWRULE, flags) + + return err +} + +// Delete existing rule +func (r *RuleService) Delete(req *RuleMessage) error { + flags := netlink.Request | netlink.Acknowledge + _, err := r.c.Execute(req, unix.RTM_DELRULE, flags) + + return err +} + +// Get Rule(s) +func (r *RuleService) Get(req *RuleMessage) ([]RuleMessage, error) { + flags := netlink.Request | netlink.DumpFiltered + return r.execute(req, unix.RTM_GETRULE, flags) +} + +// List all rules +func (r *RuleService) List() ([]RuleMessage, error) { + flags := netlink.Request | netlink.Dump + return r.execute(&RuleMessage{}, unix.RTM_GETRULE, flags) +} + +// RuleAttributes contains all attributes for a rule. +type RuleAttributes struct { + Src, Dst *net.IP + IIFName, OIFName *string + Goto *uint32 + Priority *uint32 + FwMark, FwMask *uint32 + SrcRealm *uint16 + DstRealm *uint16 + TunID *uint64 + Table *uint32 + L3MDev *uint8 + Protocol *uint8 + IPProto *uint8 + SuppressPrefixLen *uint32 + SuppressIFGroup *uint32 + UIDRange *RuleUIDRange + SPortRange *RulePortRange + DPortRange *RulePortRange +} + +// unmarshalBinary unmarshals the contents of a byte slice into a RuleMessage. +func (r *RuleAttributes) decode(ad *netlink.AttributeDecoder) error { + for ad.Next() { + switch ad.Type() { + case unix.FRA_UNSPEC: + // unused + continue + case unix.FRA_DST: + r.Dst = &net.IP{} + ad.Do(decodeIP(r.Dst)) + case unix.FRA_SRC: + r.Src = &net.IP{} + ad.Do(decodeIP(r.Src)) + case unix.FRA_IIFNAME: + v := ad.String() + r.IIFName = &v + case unix.FRA_GOTO: + v := ad.Uint32() + r.Goto = &v + case unix.FRA_UNUSED2: + // unused + continue + case unix.FRA_PRIORITY: + v := ad.Uint32() + r.Priority = &v + case unix.FRA_UNUSED3: + // unused + continue + case unix.FRA_UNUSED4: + // unused + continue + case unix.FRA_UNUSED5: + // unused + continue + case unix.FRA_FWMARK: + v := ad.Uint32() + r.FwMark = &v + case unix.FRA_FLOW: + dst32 := ad.Uint32() + src32 := uint32(dst32 >> 16) + src32 &= 0xFFFF + dst32 &= 0xFFFF + src16 := uint16(src32) + dst16 := uint16(dst32) + r.SrcRealm = &src16 + r.DstRealm = &dst16 + case unix.FRA_TUN_ID: + v := ad.Uint64() + r.TunID = &v + case unix.FRA_SUPPRESS_IFGROUP: + v := ad.Uint32() + r.SuppressIFGroup = &v + case unix.FRA_SUPPRESS_PREFIXLEN: + v := ad.Uint32() + r.SuppressPrefixLen = &v + case unix.FRA_TABLE: + v := ad.Uint32() + r.Table = &v + case unix.FRA_FWMASK: + v := ad.Uint32() + r.FwMask = &v + case unix.FRA_OIFNAME: + v := ad.String() + r.OIFName = &v + case unix.FRA_PAD: + // unused + continue + case unix.FRA_L3MDEV: + v := ad.Uint8() + r.L3MDev = &v + case unix.FRA_UID_RANGE: + r.UIDRange = &RuleUIDRange{} + err := r.UIDRange.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + case unix.FRA_PROTOCOL: + v := ad.Uint8() + r.Protocol = &v + case unix.FRA_IP_PROTO: + v := ad.Uint8() + r.IPProto = &v + case unix.FRA_SPORT_RANGE: + r.SPortRange = &RulePortRange{} + err := r.SPortRange.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + case unix.FRA_DPORT_RANGE: + r.DPortRange = &RulePortRange{} + err := r.DPortRange.unmarshalBinary(ad.Bytes()) + if err != nil { + return err + } + default: + return errInvalidRuleAttribute + } + } + return ad.Err() +} + +// MarshalBinary marshals a RuleAttributes into a byte slice. +func (r *RuleAttributes) encode(ae *netlink.AttributeEncoder) error { + if r.Table != nil { + ae.Uint32(unix.FRA_TABLE, *r.Table) + } + if r.Protocol != nil { + ae.Uint8(unix.FRA_PROTOCOL, *r.Protocol) + } + if r.Src != nil { + ae.Do(unix.FRA_SRC, encodeIP(*r.Src)) + } + if r.Dst != nil { + ae.Do(unix.FRA_DST, encodeIP(*r.Dst)) + } + if r.IIFName != nil { + ae.String(unix.FRA_IIFNAME, *r.IIFName) + } + if r.OIFName != nil { + ae.String(unix.FRA_OIFNAME, *r.OIFName) + } + if r.Goto != nil { + ae.Uint32(unix.FRA_GOTO, *r.Goto) + } + if r.Priority != nil { + ae.Uint32(unix.FRA_PRIORITY, *r.Priority) + } + if r.FwMark != nil { + ae.Uint32(unix.FRA_FWMARK, *r.FwMark) + } + if r.FwMask != nil { + ae.Uint32(unix.FRA_FWMASK, *r.FwMask) + } + if r.DstRealm != nil { + value := uint32(*r.DstRealm) + if r.SrcRealm != nil { + value |= (uint32(*r.SrcRealm&0xFFFF) << 16) + } + ae.Uint32(unix.FRA_FLOW, value) + } + if r.TunID != nil { + ae.Uint64(unix.FRA_TUN_ID, *r.TunID) + } + if r.L3MDev != nil { + ae.Uint8(unix.FRA_L3MDEV, *r.L3MDev) + } + if r.IPProto != nil { + ae.Uint8(unix.FRA_IP_PROTO, *r.IPProto) + } + if r.SuppressIFGroup != nil { + ae.Uint32(unix.FRA_SUPPRESS_IFGROUP, *r.SuppressIFGroup) + } + if r.SuppressPrefixLen != nil { + ae.Uint32(unix.FRA_SUPPRESS_PREFIXLEN, *r.SuppressPrefixLen) + } + if r.UIDRange != nil { + data, err := marshalRuleUIDRange(*r.UIDRange) + if err != nil { + return err + } + ae.Bytes(unix.FRA_UID_RANGE, data) + } + if r.SPortRange != nil { + data, err := marshalRulePortRange(*r.SPortRange) + if err != nil { + return err + } + ae.Bytes(unix.FRA_SPORT_RANGE, data) + } + if r.DPortRange != nil { + data, err := marshalRulePortRange(*r.DPortRange) + if err != nil { + return err + } + ae.Bytes(unix.FRA_DPORT_RANGE, data) + } + return nil +} + +// RulePortRange defines start and end ports for a rule +type RulePortRange struct { + Start, End uint16 +} + +func (r *RulePortRange) unmarshalBinary(data []byte) error { + b := bytes.NewReader(data) + return binary.Read(b, nativeEndian, r) +} + +func marshalRulePortRange(s RulePortRange) ([]byte, error) { + var buf bytes.Buffer + err := binary.Write(&buf, nativeEndian, s) + return buf.Bytes(), err +} + +// RuleUIDRange defines the start and end for UID matches +type RuleUIDRange struct { + Start, End uint16 +} + +func (r *RuleUIDRange) unmarshalBinary(data []byte) error { + b := bytes.NewReader(data) + return binary.Read(b, nativeEndian, r) +} + +func marshalRuleUIDRange(s RuleUIDRange) ([]byte, error) { + var buf bytes.Buffer + err := binary.Write(&buf, nativeEndian, s) + return buf.Bytes(), err +} diff --git a/vendor/github.com/mdlayher/netlink/.gitignore b/vendor/github.com/mdlayher/netlink/.gitignore new file mode 100644 index 0000000..efc8a0a --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/.gitignore @@ -0,0 +1,4 @@ +internal/integration/integration.test +netlink.test +netlink-fuzz.zip +testdata/ diff --git a/vendor/github.com/mdlayher/netlink/CHANGELOG.md b/vendor/github.com/mdlayher/netlink/CHANGELOG.md new file mode 100644 index 0000000..eac8e92 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/CHANGELOG.md @@ -0,0 +1,174 @@ +# CHANGELOG + +## v1.7.2 + +- [Improvement]: updated dependencies, test with Go 1.20. + +## v1.7.1 + +- [Bug Fix]: test only changes to avoid failures on big endian machines. + +## v1.7.0 + +**This is the first release of package netlink that only supports Go 1.18+. +Users on older versions of Go must use v1.6.2.** + +- [Improvement]: drop support for older versions of Go so we can begin using + modern versions of `x/sys` and other dependencies. + +## v1.6.2 + +**This is the last release of package netlink that supports Go 1.17 and below.** + +- [Bug Fix] [commit](https://github.com/mdlayher/netlink/commit/9f7f860d9865069cd1a6b4dee32a3095f0b841fc): + undo update to `golang.org/x/sys` which would force the minimum Go version of + this package to Go 1.17 due to use of `unsafe.Slice`. We encourage users to + use the latest stable version of Go where possible, but continue to maintain + some compatibility with older versions of Go as long as it is reasonable to do + so. + +## v1.6.1 + +- [Deprecation] [commit](https://github.com/mdlayher/netlink/commit/d1b69ea8697d721415c259ef8513ab699c6d3e96): + the `netlink.Socket` interface has been marked as deprecated. The abstraction + is awkward to use properly and disables much of the functionality of the Conn + type when the basic interface is implemented. Do not use. + +## v1.6.0 + +**This is the first release of package netlink that only supports Go 1.13+. +Users on older versions of Go must use v1.5.0.** + +- [New API] [commit](https://github.com/mdlayher/netlink/commit/ad9e2c41caa993e3f4b68831d6cb2cb05818275d): + the `netlink.Config.Strict` field can be used to apply a more strict default + set of options to a `netlink.Conn`. This is recommended for applications + running on modern Linux kernels, but cannot be enabled by default because the + options may require a more recent kernel than the minimum kernel version that + Go supports. See the documentation for details. +- [Improvement]: broke some integration tests into a separate Go module so the + default `go.mod` for package `netlink` has fewer dependencies. + +## v1.5.0 + +**This is the last release of package netlink that supports Go 1.12.** + +- [New API] [commit](https://github.com/mdlayher/netlink/commit/53a1c10065e51077659ceedf921c8f0807abe8c0): + the `netlink.Config.PID` field can be used to specify an explicit port ID when + binding the netlink socket. This is intended for advanced use cases and most + callers should leave this field set to 0. +- [Improvement]: more low-level functionality ported to + `github.com/mdlayher/socket`, reducing package complexity. + +## v1.4.2 + +- [Documentation] [commit](https://github.com/mdlayher/netlink/commit/177e6364fb170d465d681c7c8a6283417a6d3e49): + the `netlink.Config.DisableNSLockThread` now properly uses Go's deprecated + identifier convention. This option has been a noop for a long time and should + not be used. +- [Improvement] [#189](https://github.com/mdlayher/netlink/pull/189): the + package now uses Go 1.17's `//go:build` identifiers. Thanks @tklauser. +- [Bug Fix] + [commit](https://github.com/mdlayher/netlink/commit/fe6002e030928bd1f2a446c0b6c65e8f2df4ed5e): + the `netlink.AttributeEncoder`'s `Bytes`, `String`, and `Do` methods now + properly reject byte slices and strings which are too large to fit in the + value of a netlink attribute. Thanks @ubiquitousbyte for the report. + +## v1.4.1 + +- [Improvement]: significant runtime network poller integration cleanup through + the use of `github.com/mdlayher/socket`. + +## v1.4.0 + +- [New API] [#185](https://github.com/mdlayher/netlink/pull/185): the + `netlink.AttributeDecoder` and `netlink.AttributeEncoder` types now have + methods for dealing with signed integers: `Int8`, `Int16`, `Int32`, and + `Int64`. These are necessary for working with rtnetlink's XDP APIs. Thanks + @fbegyn. + +## v1.3.2 + +- [Improvement] + [commit](https://github.com/mdlayher/netlink/commit/ebc6e2e28bcf1a0671411288423d8116ff924d6d): + `github.com/google/go-cmp` is no longer a (non-test) dependency of this module. + +## v1.3.1 + +- [Improvement]: many internal cleanups and simplifications. The library is now + slimmer and features less internal indirection. There are no user-facing + changes in this release. + +## v1.3.0 + +- [New API] [#176](https://github.com/mdlayher/netlink/pull/176): + `netlink.OpError` now has `Message` and `Offset` fields which are populated + when the kernel returns netlink extended acknowledgement data along with an + error code. The caller can turn on this option by using + `netlink.Conn.SetOption(netlink.ExtendedAcknowledge, true)`. +- [New API] + [commit](https://github.com/mdlayher/netlink/commit/beba85e0372133b6d57221191d2c557727cd1499): + the `netlink.GetStrictCheck` option can be used to tell the kernel to be more + strict when parsing requests. This enables more safety checks and can allow + the kernel to perform more advanced request filtering in subsystems such as + route netlink. + +## v1.2.1 + +- [Bug Fix] + [commit](https://github.com/mdlayher/netlink/commit/d81418f81b0bfa2465f33790a85624c63d6afe3d): + `netlink.SetBPF` will no longer panic if an empty BPF filter is set. +- [Improvement] + [commit](https://github.com/mdlayher/netlink/commit/8014f9a7dbf4fd7b84a1783dd7b470db9113ff36): + the library now uses https://github.com/josharian/native to provide the + system's native endianness at compile time, rather than re-computing it many + times at runtime. + +## v1.2.0 + +**This is the first release of package netlink that only supports Go 1.12+. +Users on older versions of Go must use v1.1.1.** + +- [Improvement] [#173](https://github.com/mdlayher/netlink/pull/173): support + for Go 1.11 and below has been dropped. All users are highly recommended to + use a stable and supported release of Go for their applications. +- [Performance] [#171](https://github.com/mdlayher/netlink/pull/171): + `netlink.Conn` no longer requires a locked OS thread for the vast majority of + operations, which should result in a significant speedup for highly concurrent + callers. Thanks @ti-mo. +- [Bug Fix] [#169](https://github.com/mdlayher/netlink/pull/169): calls to + `netlink.Conn.Close` are now able to unblock concurrent calls to + `netlink.Conn.Receive` and other blocking operations. + +## v1.1.1 + +**This is the last release of package netlink that supports Go 1.11.** + +- [Improvement] [#165](https://github.com/mdlayher/netlink/pull/165): + `netlink.Conn` `SetReadBuffer` and `SetWriteBuffer` methods now attempt the + `SO_*BUFFORCE` socket options to possibly ignore system limits given elevated + caller permissions. Thanks @MarkusBauer. +- [Note] + [commit](https://github.com/mdlayher/netlink/commit/c5f8ab79aa345dcfcf7f14d746659ca1b80a0ecc): + `netlink.Conn.Close` has had a long-standing bug + [#162](https://github.com/mdlayher/netlink/pull/162) related to internal + concurrency handling where a call to `Close` is not sufficient to unblock + pending reads. To effectively fix this issue, it is necessary to drop support + for Go 1.11 and below. This will be fixed in a future release, but a + workaround is noted in the method documentation as of now. + +## v1.1.0 + +- [New API] [#157](https://github.com/mdlayher/netlink/pull/157): the + `netlink.AttributeDecoder.TypeFlags` method enables retrieval of the type bits + stored in a netlink attribute's type field, because the existing `Type` method + masks away these bits. Thanks @ti-mo! +- [Performance] [#157](https://github.com/mdlayher/netlink/pull/157): `netlink.AttributeDecoder` + now decodes netlink attributes on demand, enabling callers who only need a + limited number of attributes to exit early from decoding loops. Thanks @ti-mo! +- [Improvement] [#161](https://github.com/mdlayher/netlink/pull/161): `netlink.Conn` + system calls are now ready for Go 1.14+'s changes to goroutine preemption. + See the PR for details. + +## v1.0.0 + +- Initial stable commit. diff --git a/vendor/github.com/mdlayher/netlink/LICENSE.md b/vendor/github.com/mdlayher/netlink/LICENSE.md new file mode 100644 index 0000000..12f7105 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/LICENSE.md @@ -0,0 +1,9 @@ +# MIT License + +Copyright (C) 2016-2022 Matt Layher + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mdlayher/netlink/README.md b/vendor/github.com/mdlayher/netlink/README.md new file mode 100644 index 0000000..768d214 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/README.md @@ -0,0 +1,175 @@ +# netlink [![Test Status](https://github.com/mdlayher/netlink/workflows/Linux%20Test/badge.svg)](https://github.com/mdlayher/netlink/actions) [![Go Reference](https://pkg.go.dev/badge/github.com/mdlayher/netlink.svg)](https://pkg.go.dev/github.com/mdlayher/netlink) [![Go Report Card](https://goreportcard.com/badge/github.com/mdlayher/netlink)](https://goreportcard.com/report/github.com/mdlayher/netlink) + +Package `netlink` provides low-level access to Linux netlink sockets +(`AF_NETLINK`). MIT Licensed. + +For more information about how netlink works, check out my blog series +on [Linux, Netlink, and Go](https://mdlayher.com/blog/linux-netlink-and-go-part-1-netlink/). + +If you have any questions or you'd like some guidance, please join us on +[Gophers Slack](https://invite.slack.golangbridge.org) in the `#networking` +channel! + +## Stability + +See the [CHANGELOG](./CHANGELOG.md) file for a description of changes between +releases. + +This package has a stable v1 API and any future breaking changes will prompt +the release of a new major version. Features and bug fixes will continue to +occur in the v1.x.x series. + +This package only supports the two most recent major versions of Go, mirroring +Go's own release policy. Older versions of Go may lack critical features and bug +fixes which are necessary for this package to function correctly. + +## Design + +A number of netlink packages are already available for Go, but I wasn't able to +find one that aligned with what I wanted in a netlink package: + +- Straightforward, idiomatic API +- Well tested +- Well documented +- Doesn't use package/global variables or state +- Doesn't necessarily need root to work + +My goal for this package is to use it as a building block for the creation +of other netlink family packages. + +## Ecosystem + +Over time, an ecosystem of Go packages has developed around package `netlink`. +Many of these packages provide building blocks for further interactions with +various netlink families, such as `NETLINK_GENERIC` or `NETLINK_ROUTE`. + +To have your package included in this diagram, please send a pull request! + +```mermaid +flowchart LR + netlink["github.com/mdlayher/netlink"] + click netlink "https://github.com/mdlayher/netlink" + + subgraph "NETLINK_CONNECTOR" + direction LR + + garlic["github.com/fearful-symmetry/garlic"] + click garlic "https://github.com/fearful-symmetry/garlic" + end + + subgraph "NETLINK_CRYPTO" + direction LR + + cryptonl["github.com/mdlayher/cryptonl"] + click cryptonl "https://github.com/mdlayher/cryptonl" + end + + subgraph "NETLINK_GENERIC" + direction LR + + genetlink["github.com/mdlayher/genetlink"] + click genetlink "https://github.com/mdlayher/genetlink" + + devlink["github.com/mdlayher/devlink"] + click devlink "https://github.com/mdlayher/devlink" + + ethtool["github.com/mdlayher/ethtool"] + click ethtool "https://github.com/mdlayher/ethtool" + + go-openvswitch["github.com/digitalocean/go-openvswitch"] + click go-openvswitch "https://github.com/digitalocean/go-openvswitch" + + ipvs["github.com/cloudflare/ipvs"] + click ipvs "https://github.com/cloudflare/ipvs" + + l2tp["github.com/axatrax/l2tp"] + click l2tp "https://github.com/axatrax/l2tp" + + nbd["github.com/Merovius/nbd"] + click nbd "https://github.com/Merovius/nbd" + + quota["github.com/mdlayher/quota"] + click quota "https://github.com/mdlayher/quota" + + router7["github.com/rtr7/router7"] + click router7 "https://github.com/rtr7/router7" + + taskstats["github.com/mdlayher/taskstats"] + click taskstats "https://github.com/mdlayher/taskstats" + + u-bmc["github.com/u-root/u-bmc"] + click u-bmc "https://github.com/u-root/u-bmc" + + wgctrl["golang.zx2c4.com/wireguard/wgctrl"] + click wgctrl "https://golang.zx2c4.com/wireguard/wgctrl" + + wifi["github.com/mdlayher/wifi"] + click wifi "https://github.com/mdlayher/wifi" + + devlink & ethtool & go-openvswitch & ipvs --> genetlink + l2tp & nbd & quota & router7 & taskstats --> genetlink + u-bmc & wgctrl & wifi --> genetlink + end + + subgraph "NETLINK_KOBJECT_UEVENT" + direction LR + + kobject["github.com/mdlayher/kobject"] + click kobject "https://github.com/mdlayher/kobject" + end + + subgraph "NETLINK_NETFILTER" + direction LR + + go-conntrack["github.com/florianl/go-conntrack"] + click go-conntrack "https://github.com/florianl/go-conntrack" + + go-nflog["github.com/florianl/go-nflog"] + click go-nflog "https://github.com/florianl/go-nflog" + + go-nfqueue["github.com/florianl/go-nfqueue"] + click go-nfqueue "https://github.com/florianl/go-nfqueue" + + netfilter["github.com/ti-mo/netfilter"] + click netfilter "https://github.com/ti-mo/netfilter" + + nftables["github.com/google/nftables"] + click nftables "https://github.com/google/nftables" + + conntrack["github.com/ti-mo/conntrack"] + click conntrack "https://github.com/ti-mo/conntrack" + + conntrack --> netfilter + end + + subgraph "NETLINK_ROUTE" + direction LR + + go-tc["github.com/florianl/go-tc"] + click go-tc "https://github.com/florianl/go-tc" + + qdisc["github.com/ema/qdisc"] + click qdisc "https://github.com/ema/qdisc" + + rtnetlink["github.com/jsimonetti/rtnetlink"] + click rtnetlink "https://github.com/jsimonetti/rtnetlink" + + rtnl["gitlab.com/mergetb/tech/rtnl"] + click rtnl "https://gitlab.com/mergetb/tech/rtnl" + end + + subgraph "NETLINK_W1" + direction LR + + go-onewire["github.com/SpComb/go-onewire"] + click go-onewire "https://github.com/SpComb/go-onewire" + end + + NETLINK_CONNECTOR --> netlink + NETLINK_CRYPTO --> netlink + NETLINK_GENERIC --> netlink + NETLINK_KOBJECT_UEVENT --> netlink + NETLINK_NETFILTER --> netlink + NETLINK_ROUTE --> netlink + NETLINK_W1 --> netlink +``` diff --git a/vendor/github.com/mdlayher/netlink/align.go b/vendor/github.com/mdlayher/netlink/align.go new file mode 100644 index 0000000..20892c7 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/align.go @@ -0,0 +1,37 @@ +package netlink + +import "unsafe" + +// Functions and values used to properly align netlink messages, headers, +// and attributes. Definitions taken from Linux kernel source. + +// #define NLMSG_ALIGNTO 4U +const nlmsgAlignTo = 4 + +// #define NLMSG_ALIGN(len) ( ((len)+NLMSG_ALIGNTO-1) & ~(NLMSG_ALIGNTO-1) ) +func nlmsgAlign(len int) int { + return ((len) + nlmsgAlignTo - 1) & ^(nlmsgAlignTo - 1) +} + +// #define NLMSG_LENGTH(len) ((len) + NLMSG_HDRLEN) +func nlmsgLength(len int) int { + return len + nlmsgHeaderLen +} + +// #define NLMSG_HDRLEN ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr))) +var nlmsgHeaderLen = nlmsgAlign(int(unsafe.Sizeof(Header{}))) + +// #define NLA_ALIGNTO 4 +const nlaAlignTo = 4 + +// #define NLA_ALIGN(len) (((len) + NLA_ALIGNTO - 1) & ~(NLA_ALIGNTO - 1)) +func nlaAlign(len int) int { + return ((len) + nlaAlignTo - 1) & ^(nlaAlignTo - 1) +} + +// Because this package's Attribute type contains a byte slice, unsafe.Sizeof +// can't be used to determine the correct length. +const sizeofAttribute = 4 + +// #define NLA_HDRLEN ((int) NLA_ALIGN(sizeof(struct nlattr))) +var nlaHeaderLen = nlaAlign(sizeofAttribute) diff --git a/vendor/github.com/mdlayher/netlink/attribute.go b/vendor/github.com/mdlayher/netlink/attribute.go new file mode 100644 index 0000000..4d3cfd3 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/attribute.go @@ -0,0 +1,707 @@ +package netlink + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + + "github.com/josharian/native" + "github.com/mdlayher/netlink/nlenc" +) + +// errInvalidAttribute specifies if an Attribute's length is incorrect. +var errInvalidAttribute = errors.New("invalid attribute; length too short or too large") + +// An Attribute is a netlink attribute. Attributes are packed and unpacked +// to and from the Data field of Message for some netlink families. +type Attribute struct { + // Length of an Attribute, including this field and Type. + Length uint16 + + // The type of this Attribute, typically matched to a constant. Note that + // flags such as Nested and NetByteOrder must be handled manually when + // working with Attribute structures directly. + Type uint16 + + // An arbitrary payload which is specified by Type. + Data []byte +} + +// marshal marshals the contents of a into b and returns the number of bytes +// written to b, including attribute alignment padding. +func (a *Attribute) marshal(b []byte) (int, error) { + if int(a.Length) < nlaHeaderLen { + return 0, errInvalidAttribute + } + + nlenc.PutUint16(b[0:2], a.Length) + nlenc.PutUint16(b[2:4], a.Type) + n := copy(b[nlaHeaderLen:], a.Data) + + return nlaHeaderLen + nlaAlign(n), nil +} + +// unmarshal unmarshals the contents of a byte slice into an Attribute. +func (a *Attribute) unmarshal(b []byte) error { + if len(b) < nlaHeaderLen { + return errInvalidAttribute + } + + a.Length = nlenc.Uint16(b[0:2]) + a.Type = nlenc.Uint16(b[2:4]) + + if int(a.Length) > len(b) { + return errInvalidAttribute + } + + switch { + // No length, no data + case a.Length == 0: + a.Data = make([]byte, 0) + // Not enough length for any data + case int(a.Length) < nlaHeaderLen: + return errInvalidAttribute + // Data present + case int(a.Length) >= nlaHeaderLen: + a.Data = make([]byte, len(b[nlaHeaderLen:a.Length])) + copy(a.Data, b[nlaHeaderLen:a.Length]) + } + + return nil +} + +// MarshalAttributes packs a slice of Attributes into a single byte slice. +// In most cases, the Length field of each Attribute should be set to 0, so it +// can be calculated and populated automatically for each Attribute. +// +// It is recommend to use the AttributeEncoder type where possible instead of +// calling MarshalAttributes and using package nlenc functions directly. +func MarshalAttributes(attrs []Attribute) ([]byte, error) { + // Count how many bytes we should allocate to store each attribute's contents. + var c int + for _, a := range attrs { + c += nlaHeaderLen + nlaAlign(len(a.Data)) + } + + // Advance through b with idx to place attribute data at the correct offset. + var idx int + b := make([]byte, c) + for _, a := range attrs { + // Infer the length of attribute if zero. + if a.Length == 0 { + a.Length = uint16(nlaHeaderLen + len(a.Data)) + } + + // Marshal a into b and advance idx to show many bytes are occupied. + n, err := a.marshal(b[idx:]) + if err != nil { + return nil, err + } + idx += n + } + + return b, nil +} + +// UnmarshalAttributes unpacks a slice of Attributes from a single byte slice. +// +// It is recommend to use the AttributeDecoder type where possible instead of calling +// UnmarshalAttributes and using package nlenc functions directly. +func UnmarshalAttributes(b []byte) ([]Attribute, error) { + ad, err := NewAttributeDecoder(b) + if err != nil { + return nil, err + } + + // Return a nil slice when there are no attributes to decode. + if ad.Len() == 0 { + return nil, nil + } + + attrs := make([]Attribute, 0, ad.Len()) + + for ad.Next() { + if ad.a.Length != 0 { + attrs = append(attrs, ad.a) + } + } + + if err := ad.Err(); err != nil { + return nil, err + } + + return attrs, nil +} + +// An AttributeDecoder provides a safe, iterator-like, API around attribute +// decoding. +// +// It is recommend to use an AttributeDecoder where possible instead of calling +// UnmarshalAttributes and using package nlenc functions directly. +// +// The Err method must be called after the Next method returns false to determine +// if any errors occurred during iteration. +type AttributeDecoder struct { + // ByteOrder defines a specific byte order to use when processing integer + // attributes. ByteOrder should be set immediately after creating the + // AttributeDecoder: before any attributes are parsed. + // + // If not set, the native byte order will be used. + ByteOrder binary.ByteOrder + + // The current attribute being worked on. + a Attribute + + // The slice of input bytes and its iterator index. + b []byte + i int + + length int + + // Any error encountered while decoding attributes. + err error +} + +// NewAttributeDecoder creates an AttributeDecoder that unpacks Attributes +// from b and prepares the decoder for iteration. +func NewAttributeDecoder(b []byte) (*AttributeDecoder, error) { + ad := &AttributeDecoder{ + // By default, use native byte order. + ByteOrder: native.Endian, + + b: b, + } + + var err error + ad.length, err = ad.available() + if err != nil { + return nil, err + } + + return ad, nil +} + +// Next advances the decoder to the next netlink attribute. It returns false +// when no more attributes are present, or an error was encountered. +func (ad *AttributeDecoder) Next() bool { + if ad.err != nil { + // Hit an error, stop iteration. + return false + } + + // Exit if array pointer is at or beyond the end of the slice. + if ad.i >= len(ad.b) { + return false + } + + if err := ad.a.unmarshal(ad.b[ad.i:]); err != nil { + ad.err = err + return false + } + + // Advance the pointer by at least one header's length. + if int(ad.a.Length) < nlaHeaderLen { + ad.i += nlaHeaderLen + } else { + ad.i += nlaAlign(int(ad.a.Length)) + } + + return true +} + +// Type returns the Attribute.Type field of the current netlink attribute +// pointed to by the decoder. +// +// Type masks off the high bits of the netlink attribute type which may contain +// the Nested and NetByteOrder flags. These can be obtained by calling TypeFlags. +func (ad *AttributeDecoder) Type() uint16 { + // Mask off any flags stored in the high bits. + return ad.a.Type & attrTypeMask +} + +// TypeFlags returns the two high bits of the Attribute.Type field of the current +// netlink attribute pointed to by the decoder. +// +// These bits of the netlink attribute type are used for the Nested and NetByteOrder +// flags, available as the Nested and NetByteOrder constants in this package. +func (ad *AttributeDecoder) TypeFlags() uint16 { + return ad.a.Type & ^attrTypeMask +} + +// Len returns the number of netlink attributes pointed to by the decoder. +func (ad *AttributeDecoder) Len() int { return ad.length } + +// count scans the input slice to count the number of netlink attributes +// that could be decoded by Next(). +func (ad *AttributeDecoder) available() (int, error) { + var count int + for i := 0; i < len(ad.b); { + // Make sure there's at least a header's worth + // of data to read on each iteration. + if len(ad.b[i:]) < nlaHeaderLen { + return 0, errInvalidAttribute + } + + // Extract the length of the attribute. + l := int(nlenc.Uint16(ad.b[i : i+2])) + + // Ignore zero-length attributes. + if l != 0 { + count++ + } + + // Advance by at least a header's worth of bytes. + if l < nlaHeaderLen { + l = nlaHeaderLen + } + + i += nlaAlign(l) + } + + return count, nil +} + +// data returns the Data field of the current Attribute pointed to by the decoder. +func (ad *AttributeDecoder) data() []byte { return ad.a.Data } + +// Err returns the first error encountered by the decoder. +func (ad *AttributeDecoder) Err() error { return ad.err } + +// Bytes returns the raw bytes of the current Attribute's data. +func (ad *AttributeDecoder) Bytes() []byte { + src := ad.data() + dest := make([]byte, len(src)) + copy(dest, src) + return dest +} + +// String returns the string representation of the current Attribute's data. +func (ad *AttributeDecoder) String() string { + if ad.err != nil { + return "" + } + + return nlenc.String(ad.data()) +} + +// Uint8 returns the uint8 representation of the current Attribute's data. +func (ad *AttributeDecoder) Uint8() uint8 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 1 { + ad.err = fmt.Errorf("netlink: attribute %d is not a uint8; length: %d", ad.Type(), len(b)) + return 0 + } + + return uint8(b[0]) +} + +// Uint16 returns the uint16 representation of the current Attribute's data. +func (ad *AttributeDecoder) Uint16() uint16 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 2 { + ad.err = fmt.Errorf("netlink: attribute %d is not a uint16; length: %d", ad.Type(), len(b)) + return 0 + } + + return ad.ByteOrder.Uint16(b) +} + +// Uint32 returns the uint32 representation of the current Attribute's data. +func (ad *AttributeDecoder) Uint32() uint32 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 4 { + ad.err = fmt.Errorf("netlink: attribute %d is not a uint32; length: %d", ad.Type(), len(b)) + return 0 + } + + return ad.ByteOrder.Uint32(b) +} + +// Uint64 returns the uint64 representation of the current Attribute's data. +func (ad *AttributeDecoder) Uint64() uint64 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 8 { + ad.err = fmt.Errorf("netlink: attribute %d is not a uint64; length: %d", ad.Type(), len(b)) + return 0 + } + + return ad.ByteOrder.Uint64(b) +} + +// Int8 returns the Int8 representation of the current Attribute's data. +func (ad *AttributeDecoder) Int8() int8 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 1 { + ad.err = fmt.Errorf("netlink: attribute %d is not a int8; length: %d", ad.Type(), len(b)) + return 0 + } + + return int8(b[0]) +} + +// Int16 returns the Int16 representation of the current Attribute's data. +func (ad *AttributeDecoder) Int16() int16 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 2 { + ad.err = fmt.Errorf("netlink: attribute %d is not a int16; length: %d", ad.Type(), len(b)) + return 0 + } + + return int16(ad.ByteOrder.Uint16(b)) +} + +// Int32 returns the Int32 representation of the current Attribute's data. +func (ad *AttributeDecoder) Int32() int32 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 4 { + ad.err = fmt.Errorf("netlink: attribute %d is not a int32; length: %d", ad.Type(), len(b)) + return 0 + } + + return int32(ad.ByteOrder.Uint32(b)) +} + +// Int64 returns the Int64 representation of the current Attribute's data. +func (ad *AttributeDecoder) Int64() int64 { + if ad.err != nil { + return 0 + } + + b := ad.data() + if len(b) != 8 { + ad.err = fmt.Errorf("netlink: attribute %d is not a int64; length: %d", ad.Type(), len(b)) + return 0 + } + + return int64(ad.ByteOrder.Uint64(b)) +} + +// Flag returns a boolean representing the Attribute. +func (ad *AttributeDecoder) Flag() bool { + if ad.err != nil { + return false + } + + b := ad.data() + if len(b) != 0 { + ad.err = fmt.Errorf("netlink: attribute %d is not a flag; length: %d", ad.Type(), len(b)) + return false + } + + return true +} + +// Do is a general purpose function which allows access to the current data +// pointed to by the AttributeDecoder. +// +// Do can be used to allow parsing arbitrary data within the context of the +// decoder. Do is most useful when dealing with nested attributes, attribute +// arrays, or decoding arbitrary types (such as C structures) which don't fit +// cleanly into a typical unsigned integer value. +// +// The function fn should not retain any reference to the data b outside of the +// scope of the function. +func (ad *AttributeDecoder) Do(fn func(b []byte) error) { + if ad.err != nil { + return + } + + b := ad.data() + if err := fn(b); err != nil { + ad.err = err + } +} + +// Nested decodes data into a nested AttributeDecoder to handle nested netlink +// attributes. When calling Nested, the Err method does not need to be called on +// the nested AttributeDecoder. +// +// The nested AttributeDecoder nad inherits the same ByteOrder setting as the +// top-level AttributeDecoder ad. +func (ad *AttributeDecoder) Nested(fn func(nad *AttributeDecoder) error) { + // Because we are wrapping Do, there is no need to check ad.err immediately. + ad.Do(func(b []byte) error { + nad, err := NewAttributeDecoder(b) + if err != nil { + return err + } + nad.ByteOrder = ad.ByteOrder + + if err := fn(nad); err != nil { + return err + } + + return nad.Err() + }) +} + +// An AttributeEncoder provides a safe way to encode attributes. +// +// It is recommended to use an AttributeEncoder where possible instead of +// calling MarshalAttributes or using package nlenc directly. +// +// Errors from intermediate encoding steps are returned in the call to +// Encode. +type AttributeEncoder struct { + // ByteOrder defines a specific byte order to use when processing integer + // attributes. ByteOrder should be set immediately after creating the + // AttributeEncoder: before any attributes are encoded. + // + // If not set, the native byte order will be used. + ByteOrder binary.ByteOrder + + attrs []Attribute + err error +} + +// NewAttributeEncoder creates an AttributeEncoder that encodes Attributes. +func NewAttributeEncoder() *AttributeEncoder { + return &AttributeEncoder{ByteOrder: native.Endian} +} + +// Uint8 encodes uint8 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Uint8(typ uint16, v uint8) { + if ae.err != nil { + return + } + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: []byte{v}, + }) +} + +// Uint16 encodes uint16 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Uint16(typ uint16, v uint16) { + if ae.err != nil { + return + } + + b := make([]byte, 2) + ae.ByteOrder.PutUint16(b, v) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Uint32 encodes uint32 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Uint32(typ uint16, v uint32) { + if ae.err != nil { + return + } + + b := make([]byte, 4) + ae.ByteOrder.PutUint32(b, v) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Uint64 encodes uint64 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Uint64(typ uint16, v uint64) { + if ae.err != nil { + return + } + + b := make([]byte, 8) + ae.ByteOrder.PutUint64(b, v) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Int8 encodes int8 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Int8(typ uint16, v int8) { + if ae.err != nil { + return + } + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: []byte{uint8(v)}, + }) +} + +// Int16 encodes int16 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Int16(typ uint16, v int16) { + if ae.err != nil { + return + } + + b := make([]byte, 2) + ae.ByteOrder.PutUint16(b, uint16(v)) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Int32 encodes int32 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Int32(typ uint16, v int32) { + if ae.err != nil { + return + } + + b := make([]byte, 4) + ae.ByteOrder.PutUint32(b, uint32(v)) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Int64 encodes int64 data into an Attribute specified by typ. +func (ae *AttributeEncoder) Int64(typ uint16, v int64) { + if ae.err != nil { + return + } + + b := make([]byte, 8) + ae.ByteOrder.PutUint64(b, uint64(v)) + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Flag encodes a flag into an Attribute specified by typ. +func (ae *AttributeEncoder) Flag(typ uint16, v bool) { + // Only set flag on no previous error or v == true. + if ae.err != nil || !v { + return + } + + // Flags have no length or data fields. + ae.attrs = append(ae.attrs, Attribute{Type: typ}) +} + +// String encodes string s as a null-terminated string into an Attribute +// specified by typ. +func (ae *AttributeEncoder) String(typ uint16, s string) { + if ae.err != nil { + return + } + + // Length checking, thanks ubiquitousbyte on GitHub. + if len(s) > math.MaxUint16-nlaHeaderLen { + ae.err = errors.New("string is too large to fit in a netlink attribute") + return + } + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: nlenc.Bytes(s), + }) +} + +// Bytes embeds raw byte data into an Attribute specified by typ. +func (ae *AttributeEncoder) Bytes(typ uint16, b []byte) { + if ae.err != nil { + return + } + + if len(b) > math.MaxUint16-nlaHeaderLen { + ae.err = errors.New("byte slice is too large to fit in a netlink attribute") + return + } + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Do is a general purpose function to encode arbitrary data into an attribute +// specified by typ. +// +// Do is especially helpful in encoding nested attributes, attribute arrays, +// or encoding arbitrary types (such as C structures) which don't fit cleanly +// into an unsigned integer value. +func (ae *AttributeEncoder) Do(typ uint16, fn func() ([]byte, error)) { + if ae.err != nil { + return + } + + b, err := fn() + if err != nil { + ae.err = err + return + } + + if len(b) > math.MaxUint16-nlaHeaderLen { + ae.err = errors.New("byte slice produced by Do is too large to fit in a netlink attribute") + return + } + + ae.attrs = append(ae.attrs, Attribute{ + Type: typ, + Data: b, + }) +} + +// Nested embeds data produced by a nested AttributeEncoder and flags that data +// with the Nested flag. When calling Nested, the Encode method should not be +// called on the nested AttributeEncoder. +// +// The nested AttributeEncoder nae inherits the same ByteOrder setting as the +// top-level AttributeEncoder ae. +func (ae *AttributeEncoder) Nested(typ uint16, fn func(nae *AttributeEncoder) error) { + // Because we are wrapping Do, there is no need to check ae.err immediately. + ae.Do(Nested|typ, func() ([]byte, error) { + nae := NewAttributeEncoder() + nae.ByteOrder = ae.ByteOrder + + if err := fn(nae); err != nil { + return nil, err + } + + return nae.Encode() + }) +} + +// Encode returns the encoded bytes representing the attributes. +func (ae *AttributeEncoder) Encode() ([]byte, error) { + if ae.err != nil { + return nil, ae.err + } + + return MarshalAttributes(ae.attrs) +} diff --git a/vendor/github.com/mdlayher/netlink/conn.go b/vendor/github.com/mdlayher/netlink/conn.go new file mode 100644 index 0000000..7138665 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/conn.go @@ -0,0 +1,593 @@ +package netlink + +import ( + "math/rand" + "sync" + "sync/atomic" + "syscall" + "time" + + "golang.org/x/net/bpf" +) + +// A Conn is a connection to netlink. A Conn can be used to send and +// receives messages to and from netlink. +// +// A Conn is safe for concurrent use, but to avoid contention in +// high-throughput applications, the caller should almost certainly create a +// pool of Conns and distribute them among workers. +// +// A Conn is capable of manipulating netlink subsystems from within a specific +// Linux network namespace, but special care must be taken when doing so. See +// the documentation of Config for details. +type Conn struct { + // Atomics must come first. + // + // seq is an atomically incremented integer used to provide sequence + // numbers when Conn.Send is called. + seq uint32 + + // mu serializes access to the netlink socket for the request/response + // transaction within Execute. + mu sync.RWMutex + + // sock is the operating system-specific implementation of + // a netlink sockets connection. + sock Socket + + // pid is the PID assigned by netlink. + pid uint32 + + // d provides debugging capabilities for a Conn if not nil. + d *debugger +} + +// A Socket is an operating-system specific implementation of netlink +// sockets used by Conn. +// +// Deprecated: the intent of Socket was to provide an abstraction layer for +// testing, but this abstraction is awkward to use properly and disables much of +// the functionality of the Conn type. Do not use. +type Socket interface { + Close() error + Send(m Message) error + SendMessages(m []Message) error + Receive() ([]Message, error) +} + +// Dial dials a connection to netlink, using the specified netlink family. +// Config specifies optional configuration for Conn. If config is nil, a default +// configuration will be used. +func Dial(family int, config *Config) (*Conn, error) { + // TODO(mdlayher): plumb in netlink.OpError wrapping? + + // Use OS-specific dial() to create Socket. + c, pid, err := dial(family, config) + if err != nil { + return nil, err + } + + return NewConn(c, pid), nil +} + +// NewConn creates a Conn using the specified Socket and PID for netlink +// communications. +// +// NewConn is primarily useful for tests. Most applications should use +// Dial instead. +func NewConn(sock Socket, pid uint32) *Conn { + // Seed the sequence number using a random number generator. + r := rand.New(rand.NewSource(time.Now().UnixNano())) + seq := r.Uint32() + + // Configure a debugger if arguments are set. + var d *debugger + if len(debugArgs) > 0 { + d = newDebugger(debugArgs) + } + + return &Conn{ + seq: seq, + sock: sock, + pid: pid, + d: d, + } +} + +// debug executes fn with the debugger if the debugger is not nil. +func (c *Conn) debug(fn func(d *debugger)) { + if c.d == nil { + return + } + + fn(c.d) +} + +// Close closes the connection and unblocks any pending read operations. +func (c *Conn) Close() error { + // Close does not acquire a lock because it must be able to interrupt any + // blocked system calls, such as when Receive is waiting on a multicast + // group message. + // + // We rely on the kernel to deal with concurrent operations to the netlink + // socket itself. + return newOpError("close", c.sock.Close()) +} + +// Execute sends a single Message to netlink using Send, receives one or more +// replies using Receive, and then checks the validity of the replies against +// the request using Validate. +// +// Execute acquires a lock for the duration of the function call which blocks +// concurrent calls to Send, SendMessages, and Receive, in order to ensure +// consistency between netlink request/reply messages. +// +// See the documentation of Send, Receive, and Validate for details about +// each function. +func (c *Conn) Execute(m Message) ([]Message, error) { + // Acquire the write lock and invoke the internal implementations of Send + // and Receive which require the lock already be held. + c.mu.Lock() + defer c.mu.Unlock() + + req, err := c.lockedSend(m) + if err != nil { + return nil, err + } + + res, err := c.lockedReceive() + if err != nil { + return nil, err + } + + if err := Validate(req, res); err != nil { + return nil, err + } + + return res, nil +} + +// SendMessages sends multiple Messages to netlink. The handling of +// a Header's Length, Sequence and PID fields is the same as when +// calling Send. +func (c *Conn) SendMessages(msgs []Message) ([]Message, error) { + // Wait for any concurrent calls to Execute to finish before proceeding. + c.mu.RLock() + defer c.mu.RUnlock() + + for i := range msgs { + c.fixMsg(&msgs[i], nlmsgLength(len(msgs[i].Data))) + } + + c.debug(func(d *debugger) { + for _, m := range msgs { + d.debugf(1, "send msgs: %+v", m) + } + }) + + if err := c.sock.SendMessages(msgs); err != nil { + c.debug(func(d *debugger) { + d.debugf(1, "send msgs: err: %v", err) + }) + + return nil, newOpError("send-messages", err) + } + + return msgs, nil +} + +// Send sends a single Message to netlink. In most cases, a Header's Length, +// Sequence, and PID fields should be set to 0, so they can be populated +// automatically before the Message is sent. On success, Send returns a copy +// of the Message with all parameters populated, for later validation. +// +// If Header.Length is 0, it will be automatically populated using the +// correct length for the Message, including its payload. +// +// If Header.Sequence is 0, it will be automatically populated using the +// next sequence number for this connection. +// +// If Header.PID is 0, it will be automatically populated using a PID +// assigned by netlink. +func (c *Conn) Send(m Message) (Message, error) { + // Wait for any concurrent calls to Execute to finish before proceeding. + c.mu.RLock() + defer c.mu.RUnlock() + + return c.lockedSend(m) +} + +// lockedSend implements Send, but must be called with c.mu acquired for reading. +// We rely on the kernel to deal with concurrent reads and writes to the netlink +// socket itself. +func (c *Conn) lockedSend(m Message) (Message, error) { + c.fixMsg(&m, nlmsgLength(len(m.Data))) + + c.debug(func(d *debugger) { + d.debugf(1, "send: %+v", m) + }) + + if err := c.sock.Send(m); err != nil { + c.debug(func(d *debugger) { + d.debugf(1, "send: err: %v", err) + }) + + return Message{}, newOpError("send", err) + } + + return m, nil +} + +// Receive receives one or more messages from netlink. Multi-part messages are +// handled transparently and returned as a single slice of Messages, with the +// final empty "multi-part done" message removed. +// +// If any of the messages indicate a netlink error, that error will be returned. +func (c *Conn) Receive() ([]Message, error) { + // Wait for any concurrent calls to Execute to finish before proceeding. + c.mu.RLock() + defer c.mu.RUnlock() + + return c.lockedReceive() +} + +// lockedReceive implements Receive, but must be called with c.mu acquired for reading. +// We rely on the kernel to deal with concurrent reads and writes to the netlink +// socket itself. +func (c *Conn) lockedReceive() ([]Message, error) { + msgs, err := c.receive() + if err != nil { + c.debug(func(d *debugger) { + d.debugf(1, "recv: err: %v", err) + }) + + return nil, err + } + + c.debug(func(d *debugger) { + for _, m := range msgs { + d.debugf(1, "recv: %+v", m) + } + }) + + // When using nltest, it's possible for zero messages to be returned by receive. + if len(msgs) == 0 { + return msgs, nil + } + + // Trim the final message with multi-part done indicator if + // present. + if m := msgs[len(msgs)-1]; m.Header.Flags&Multi != 0 && m.Header.Type == Done { + return msgs[:len(msgs)-1], nil + } + + return msgs, nil +} + +// receive is the internal implementation of Conn.Receive, which can be called +// recursively to handle multi-part messages. +func (c *Conn) receive() ([]Message, error) { + // NB: All non-nil errors returned from this function *must* be of type + // OpError in order to maintain the appropriate contract with callers of + // this package. + // + // This contract also applies to functions called within this function, + // such as checkMessage. + + var res []Message + for { + msgs, err := c.sock.Receive() + if err != nil { + return nil, newOpError("receive", err) + } + + // If this message is multi-part, we will need to continue looping to + // drain all the messages from the socket. + var multi bool + + for _, m := range msgs { + if err := checkMessage(m); err != nil { + return nil, err + } + + // Does this message indicate a multi-part message? + if m.Header.Flags&Multi == 0 { + // No, check the next messages. + continue + } + + // Does this message indicate the last message in a series of + // multi-part messages from a single read? + multi = m.Header.Type != Done + } + + res = append(res, msgs...) + + if !multi { + // No more messages coming. + return res, nil + } + } +} + +// A groupJoinLeaver is a Socket that supports joining and leaving +// netlink multicast groups. +type groupJoinLeaver interface { + Socket + JoinGroup(group uint32) error + LeaveGroup(group uint32) error +} + +// JoinGroup joins a netlink multicast group by its ID. +func (c *Conn) JoinGroup(group uint32) error { + conn, ok := c.sock.(groupJoinLeaver) + if !ok { + return notSupported("join-group") + } + + return newOpError("join-group", conn.JoinGroup(group)) +} + +// LeaveGroup leaves a netlink multicast group by its ID. +func (c *Conn) LeaveGroup(group uint32) error { + conn, ok := c.sock.(groupJoinLeaver) + if !ok { + return notSupported("leave-group") + } + + return newOpError("leave-group", conn.LeaveGroup(group)) +} + +// A bpfSetter is a Socket that supports setting and removing BPF filters. +type bpfSetter interface { + Socket + bpf.Setter + RemoveBPF() error +} + +// SetBPF attaches an assembled BPF program to a Conn. +func (c *Conn) SetBPF(filter []bpf.RawInstruction) error { + conn, ok := c.sock.(bpfSetter) + if !ok { + return notSupported("set-bpf") + } + + return newOpError("set-bpf", conn.SetBPF(filter)) +} + +// RemoveBPF removes a BPF filter from a Conn. +func (c *Conn) RemoveBPF() error { + conn, ok := c.sock.(bpfSetter) + if !ok { + return notSupported("remove-bpf") + } + + return newOpError("remove-bpf", conn.RemoveBPF()) +} + +// A deadlineSetter is a Socket that supports setting deadlines. +type deadlineSetter interface { + Socket + SetDeadline(time.Time) error + SetReadDeadline(time.Time) error + SetWriteDeadline(time.Time) error +} + +// SetDeadline sets the read and write deadlines associated with the connection. +func (c *Conn) SetDeadline(t time.Time) error { + conn, ok := c.sock.(deadlineSetter) + if !ok { + return notSupported("set-deadline") + } + + return newOpError("set-deadline", conn.SetDeadline(t)) +} + +// SetReadDeadline sets the read deadline associated with the connection. +func (c *Conn) SetReadDeadline(t time.Time) error { + conn, ok := c.sock.(deadlineSetter) + if !ok { + return notSupported("set-read-deadline") + } + + return newOpError("set-read-deadline", conn.SetReadDeadline(t)) +} + +// SetWriteDeadline sets the write deadline associated with the connection. +func (c *Conn) SetWriteDeadline(t time.Time) error { + conn, ok := c.sock.(deadlineSetter) + if !ok { + return notSupported("set-write-deadline") + } + + return newOpError("set-write-deadline", conn.SetWriteDeadline(t)) +} + +// A ConnOption is a boolean option that may be set for a Conn. +type ConnOption int + +// Possible ConnOption values. These constants are equivalent to the Linux +// setsockopt boolean options for netlink sockets. +const ( + PacketInfo ConnOption = iota + BroadcastError + NoENOBUFS + ListenAllNSID + CapAcknowledge + ExtendedAcknowledge + GetStrictCheck +) + +// An optionSetter is a Socket that supports setting netlink options. +type optionSetter interface { + Socket + SetOption(option ConnOption, enable bool) error +} + +// SetOption enables or disables a netlink socket option for the Conn. +func (c *Conn) SetOption(option ConnOption, enable bool) error { + conn, ok := c.sock.(optionSetter) + if !ok { + return notSupported("set-option") + } + + return newOpError("set-option", conn.SetOption(option, enable)) +} + +// A bufferSetter is a Socket that supports setting connection buffer sizes. +type bufferSetter interface { + Socket + SetReadBuffer(bytes int) error + SetWriteBuffer(bytes int) error +} + +// SetReadBuffer sets the size of the operating system's receive buffer +// associated with the Conn. +func (c *Conn) SetReadBuffer(bytes int) error { + conn, ok := c.sock.(bufferSetter) + if !ok { + return notSupported("set-read-buffer") + } + + return newOpError("set-read-buffer", conn.SetReadBuffer(bytes)) +} + +// SetWriteBuffer sets the size of the operating system's transmit buffer +// associated with the Conn. +func (c *Conn) SetWriteBuffer(bytes int) error { + conn, ok := c.sock.(bufferSetter) + if !ok { + return notSupported("set-write-buffer") + } + + return newOpError("set-write-buffer", conn.SetWriteBuffer(bytes)) +} + +// A syscallConner is a Socket that supports syscall.Conn. +type syscallConner interface { + Socket + syscall.Conn +} + +var _ syscall.Conn = &Conn{} + +// SyscallConn returns a raw network connection. This implements the +// syscall.Conn interface. +// +// SyscallConn is intended for advanced use cases, such as getting and setting +// arbitrary socket options using the netlink socket's file descriptor. +// +// Once invoked, it is the caller's responsibility to ensure that operations +// performed using Conn and the syscall.RawConn do not conflict with +// each other. +func (c *Conn) SyscallConn() (syscall.RawConn, error) { + sc, ok := c.sock.(syscallConner) + if !ok { + return nil, notSupported("syscall-conn") + } + + // TODO(mdlayher): mutex or similar to enforce syscall.RawConn contract of + // FD remaining valid for duration of calls? + + return sc.SyscallConn() +} + +// fixMsg updates the fields of m using the logic specified in Send. +func (c *Conn) fixMsg(m *Message, ml int) { + if m.Header.Length == 0 { + m.Header.Length = uint32(nlmsgAlign(ml)) + } + + if m.Header.Sequence == 0 { + m.Header.Sequence = c.nextSequence() + } + + if m.Header.PID == 0 { + m.Header.PID = c.pid + } +} + +// nextSequence atomically increments Conn's sequence number and returns +// the incremented value. +func (c *Conn) nextSequence() uint32 { + return atomic.AddUint32(&c.seq, 1) +} + +// Validate validates one or more reply Messages against a request Message, +// ensuring that they contain matching sequence numbers and PIDs. +func Validate(request Message, replies []Message) error { + for _, m := range replies { + // Check for mismatched sequence, unless: + // - request had no sequence, meaning we are probably validating + // a multicast reply + if m.Header.Sequence != request.Header.Sequence && request.Header.Sequence != 0 { + return newOpError("validate", errMismatchedSequence) + } + + // Check for mismatched PID, unless: + // - request had no PID, meaning we are either: + // - validating a multicast reply + // - netlink has not yet assigned us a PID + // - response had no PID, meaning it's from the kernel as a multicast reply + if m.Header.PID != request.Header.PID && request.Header.PID != 0 && m.Header.PID != 0 { + return newOpError("validate", errMismatchedPID) + } + } + + return nil +} + +// Config contains options for a Conn. +type Config struct { + // Groups is a bitmask which specifies multicast groups. If set to 0, + // no multicast group subscriptions will be made. + Groups uint32 + + // NetNS specifies the network namespace the Conn will operate in. + // + // If set (non-zero), Conn will enter the specified network namespace and + // an error will occur in Dial if the operation fails. + // + // If not set (zero), a best-effort attempt will be made to enter the + // network namespace of the calling thread: this means that any changes made + // to the calling thread's network namespace will also be reflected in Conn. + // If this operation fails (due to lack of permissions or because network + // namespaces are disabled by kernel configuration), Dial will not return + // an error, and the Conn will operate in the default network namespace of + // the process. This enables non-privileged use of Conn in applications + // which do not require elevated privileges. + // + // Entering a network namespace is a privileged operation (root or + // CAP_SYS_ADMIN are required), and most applications should leave this set + // to 0. + NetNS int + + // DisableNSLockThread is a no-op. + // + // Deprecated: internal changes have made this option obsolete and it has no + // effect. Do not use. + DisableNSLockThread bool + + // PID specifies the port ID used to bind the netlink socket. If set to 0, + // the kernel will assign a port ID on the caller's behalf. + // + // Most callers should leave this field set to 0. This option is intended + // for advanced use cases where the kernel expects a fixed unicast address + // destination for netlink messages. + PID uint32 + + // Strict applies a more strict default set of options to the Conn, + // including: + // - ExtendedAcknowledge: true + // - provides more useful error messages when supported by the kernel + // - GetStrictCheck: true + // - more strictly enforces request validation for some families such + // as rtnetlink which were historically misused + // + // If any of the options specified by Strict cannot be configured due to an + // outdated kernel or similar, an error will be returned. + // + // When possible, setting Strict to true is recommended for applications + // running on modern Linux kernels. + Strict bool +} diff --git a/vendor/github.com/mdlayher/netlink/conn_linux.go b/vendor/github.com/mdlayher/netlink/conn_linux.go new file mode 100644 index 0000000..4af18c9 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/conn_linux.go @@ -0,0 +1,251 @@ +//go:build linux +// +build linux + +package netlink + +import ( + "context" + "os" + "syscall" + "time" + "unsafe" + + "github.com/mdlayher/socket" + "golang.org/x/net/bpf" + "golang.org/x/sys/unix" +) + +var _ Socket = &conn{} + +// A conn is the Linux implementation of a netlink sockets connection. +type conn struct { + s *socket.Conn +} + +// dial is the entry point for Dial. dial opens a netlink socket using +// system calls, and returns its PID. +func dial(family int, config *Config) (*conn, uint32, error) { + if config == nil { + config = &Config{} + } + + // Prepare the netlink socket. + s, err := socket.Socket( + unix.AF_NETLINK, + unix.SOCK_RAW, + family, + "netlink", + &socket.Config{NetNS: config.NetNS}, + ) + if err != nil { + return nil, 0, err + } + + return newConn(s, config) +} + +// newConn binds a connection to netlink using the input *socket.Conn. +func newConn(s *socket.Conn, config *Config) (*conn, uint32, error) { + if config == nil { + config = &Config{} + } + + addr := &unix.SockaddrNetlink{ + Family: unix.AF_NETLINK, + Groups: config.Groups, + Pid: config.PID, + } + + // Socket must be closed in the event of any system call errors, to avoid + // leaking file descriptors. + + if err := s.Bind(addr); err != nil { + _ = s.Close() + return nil, 0, err + } + + sa, err := s.Getsockname() + if err != nil { + _ = s.Close() + return nil, 0, err + } + + c := &conn{s: s} + if config.Strict { + // The caller has requested the strict option set. Historically we have + // recommended checking for ENOPROTOOPT if the kernel does not support + // the option in question, but that may result in a silent failure and + // unexpected behavior for the user. + // + // Treat any error here as a fatal error, and require the caller to deal + // with it. + for _, o := range []ConnOption{ExtendedAcknowledge, GetStrictCheck} { + if err := c.SetOption(o, true); err != nil { + _ = c.Close() + return nil, 0, err + } + } + } + + return c, sa.(*unix.SockaddrNetlink).Pid, nil +} + +// SendMessages serializes multiple Messages and sends them to netlink. +func (c *conn) SendMessages(messages []Message) error { + var buf []byte + for _, m := range messages { + b, err := m.MarshalBinary() + if err != nil { + return err + } + + buf = append(buf, b...) + } + + sa := &unix.SockaddrNetlink{Family: unix.AF_NETLINK} + _, err := c.s.Sendmsg(context.Background(), buf, nil, sa, 0) + return err +} + +// Send sends a single Message to netlink. +func (c *conn) Send(m Message) error { + b, err := m.MarshalBinary() + if err != nil { + return err + } + + sa := &unix.SockaddrNetlink{Family: unix.AF_NETLINK} + _, err = c.s.Sendmsg(context.Background(), b, nil, sa, 0) + return err +} + +// Receive receives one or more Messages from netlink. +func (c *conn) Receive() ([]Message, error) { + b := make([]byte, os.Getpagesize()) + for { + // Peek at the buffer to see how many bytes are available. + // + // TODO(mdlayher): deal with OOB message data if available, such as + // when PacketInfo ConnOption is true. + n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, unix.MSG_PEEK) + if err != nil { + return nil, err + } + + // Break when we can read all messages + if n < len(b) { + break + } + + // Double in size if not enough bytes + b = make([]byte, len(b)*2) + } + + // Read out all available messages + n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, 0) + if err != nil { + return nil, err + } + + raw, err := syscall.ParseNetlinkMessage(b[:nlmsgAlign(n)]) + if err != nil { + return nil, err + } + + msgs := make([]Message, 0, len(raw)) + for _, r := range raw { + m := Message{ + Header: sysToHeader(r.Header), + Data: r.Data, + } + + msgs = append(msgs, m) + } + + return msgs, nil +} + +// Close closes the connection. +func (c *conn) Close() error { return c.s.Close() } + +// JoinGroup joins a multicast group by ID. +func (c *conn) JoinGroup(group uint32) error { + return c.s.SetsockoptInt(unix.SOL_NETLINK, unix.NETLINK_ADD_MEMBERSHIP, int(group)) +} + +// LeaveGroup leaves a multicast group by ID. +func (c *conn) LeaveGroup(group uint32) error { + return c.s.SetsockoptInt(unix.SOL_NETLINK, unix.NETLINK_DROP_MEMBERSHIP, int(group)) +} + +// SetBPF attaches an assembled BPF program to a conn. +func (c *conn) SetBPF(filter []bpf.RawInstruction) error { return c.s.SetBPF(filter) } + +// RemoveBPF removes a BPF filter from a conn. +func (c *conn) RemoveBPF() error { return c.s.RemoveBPF() } + +// SetOption enables or disables a netlink socket option for the Conn. +func (c *conn) SetOption(option ConnOption, enable bool) error { + o, ok := linuxOption(option) + if !ok { + // Return the typical Linux error for an unknown ConnOption. + return os.NewSyscallError("setsockopt", unix.ENOPROTOOPT) + } + + var v int + if enable { + v = 1 + } + + return c.s.SetsockoptInt(unix.SOL_NETLINK, o, v) +} + +func (c *conn) SetDeadline(t time.Time) error { return c.s.SetDeadline(t) } +func (c *conn) SetReadDeadline(t time.Time) error { return c.s.SetReadDeadline(t) } +func (c *conn) SetWriteDeadline(t time.Time) error { return c.s.SetWriteDeadline(t) } + +// SetReadBuffer sets the size of the operating system's receive buffer +// associated with the Conn. +func (c *conn) SetReadBuffer(bytes int) error { return c.s.SetReadBuffer(bytes) } + +// SetReadBuffer sets the size of the operating system's transmit buffer +// associated with the Conn. +func (c *conn) SetWriteBuffer(bytes int) error { return c.s.SetWriteBuffer(bytes) } + +// SyscallConn returns a raw network connection. +func (c *conn) SyscallConn() (syscall.RawConn, error) { return c.s.SyscallConn() } + +// linuxOption converts a ConnOption to its Linux value. +func linuxOption(o ConnOption) (int, bool) { + switch o { + case PacketInfo: + return unix.NETLINK_PKTINFO, true + case BroadcastError: + return unix.NETLINK_BROADCAST_ERROR, true + case NoENOBUFS: + return unix.NETLINK_NO_ENOBUFS, true + case ListenAllNSID: + return unix.NETLINK_LISTEN_ALL_NSID, true + case CapAcknowledge: + return unix.NETLINK_CAP_ACK, true + case ExtendedAcknowledge: + return unix.NETLINK_EXT_ACK, true + case GetStrictCheck: + return unix.NETLINK_GET_STRICT_CHK, true + default: + return 0, false + } +} + +// sysToHeader converts a syscall.NlMsghdr to a Header. +func sysToHeader(r syscall.NlMsghdr) Header { + // NB: the memory layout of Header and syscall.NlMsgHdr must be + // exactly the same for this unsafe cast to work + return *(*Header)(unsafe.Pointer(&r)) +} + +// newError converts an error number from netlink into the appropriate +// system call error for Linux. +func newError(errno int) error { + return syscall.Errno(errno) +} diff --git a/vendor/github.com/mdlayher/netlink/conn_others.go b/vendor/github.com/mdlayher/netlink/conn_others.go new file mode 100644 index 0000000..4c5e739 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/conn_others.go @@ -0,0 +1,30 @@ +//go:build !linux +// +build !linux + +package netlink + +import ( + "fmt" + "runtime" +) + +// errUnimplemented is returned by all functions on platforms that +// cannot make use of netlink sockets. +var errUnimplemented = fmt.Errorf("netlink: not implemented on %s/%s", + runtime.GOOS, runtime.GOARCH) + +var _ Socket = &conn{} + +// A conn is the no-op implementation of a netlink sockets connection. +type conn struct{} + +// All cross-platform functions and Socket methods are unimplemented outside +// of Linux. + +func dial(_ int, _ *Config) (*conn, uint32, error) { return nil, 0, errUnimplemented } +func newError(_ int) error { return errUnimplemented } + +func (c *conn) Send(_ Message) error { return errUnimplemented } +func (c *conn) SendMessages(_ []Message) error { return errUnimplemented } +func (c *conn) Receive() ([]Message, error) { return nil, errUnimplemented } +func (c *conn) Close() error { return errUnimplemented } diff --git a/vendor/github.com/mdlayher/netlink/debug.go b/vendor/github.com/mdlayher/netlink/debug.go new file mode 100644 index 0000000..d39d66c --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/debug.go @@ -0,0 +1,69 @@ +package netlink + +import ( + "fmt" + "log" + "os" + "strconv" + "strings" +) + +// Arguments used to create a debugger. +var debugArgs []string + +func init() { + // Is netlink debugging enabled? + s := os.Getenv("NLDEBUG") + if s == "" { + return + } + + debugArgs = strings.Split(s, ",") +} + +// A debugger is used to provide debugging information about a netlink connection. +type debugger struct { + Log *log.Logger + Level int +} + +// newDebugger creates a debugger by parsing key=value arguments. +func newDebugger(args []string) *debugger { + d := &debugger{ + Log: log.New(os.Stderr, "nl: ", 0), + Level: 1, + } + + for _, a := range args { + kv := strings.Split(a, "=") + if len(kv) != 2 { + // Ignore malformed pairs and assume callers wants defaults. + continue + } + + switch kv[0] { + // Select the log level for the debugger. + case "level": + level, err := strconv.Atoi(kv[1]) + if err != nil { + panicf("netlink: invalid NLDEBUG level: %q", a) + } + + d.Level = level + } + } + + return d +} + +// debugf prints debugging information at the specified level, if d.Level is +// high enough to print the message. +func (d *debugger) debugf(level int, format string, v ...interface{}) { + if d.Level >= level { + d.Log.Printf(format, v...) + } +} + +func panicf(format string, a ...interface{}) { + panic(fmt.Sprintf(format, a...)) +} diff --git a/vendor/github.com/mdlayher/netlink/doc.go b/vendor/github.com/mdlayher/netlink/doc.go new file mode 100644 index 0000000..98c744a --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/doc.go @@ -0,0 +1,33 @@ +// Package netlink provides low-level access to Linux netlink sockets +// (AF_NETLINK). +// +// If you have any questions or you'd like some guidance, please join us on +// Gophers Slack (https://invite.slack.golangbridge.org) in the #networking +// channel! +// +// # Network namespaces +// +// This package is aware of Linux network namespaces, and can enter different +// network namespaces either implicitly or explicitly, depending on +// configuration. The Config structure passed to Dial to create a Conn controls +// these behaviors. See the documentation of Config.NetNS for details. +// +// # Debugging +// +// This package supports rudimentary netlink connection debugging support. To +// enable this, run your binary with the NLDEBUG environment variable set. +// Debugging information will be output to stderr with a prefix of "nl:". +// +// To use the debugging defaults, use: +// +// $ NLDEBUG=1 ./nlctl +// +// To configure individual aspects of the debugger, pass key/value options such +// as: +// +// $ NLDEBUG=level=1 ./nlctl +// +// Available key/value debugger options include: +// +// level=N: specify the debugging level (only "1" is currently supported) +package netlink diff --git a/vendor/github.com/mdlayher/netlink/errors.go b/vendor/github.com/mdlayher/netlink/errors.go new file mode 100644 index 0000000..8c0fce7 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/errors.go @@ -0,0 +1,138 @@ +package netlink + +import ( + "errors" + "fmt" + "net" + "os" + "strings" +) + +// Error messages which can be returned by Validate. +var ( + errMismatchedSequence = errors.New("mismatched sequence in netlink reply") + errMismatchedPID = errors.New("mismatched PID in netlink reply") + errShortErrorMessage = errors.New("not enough data for netlink error code") +) + +// Errors which can be returned by a Socket that does not implement +// all exposed methods of Conn. + +var errNotSupported = errors.New("operation not supported") + +// notSupported provides a concise constructor for "not supported" errors. +func notSupported(op string) error { + return newOpError(op, errNotSupported) +} + +// IsNotExist determines if an error is produced as the result of querying some +// file, object, resource, etc. which does not exist. +// +// Deprecated: use errors.Unwrap and/or `errors.Is(err, os.Permission)` in Go +// 1.13+. +func IsNotExist(err error) bool { + switch err := err.(type) { + case *OpError: + // Unwrap the inner error and use the stdlib's logic. + return os.IsNotExist(err.Err) + default: + return os.IsNotExist(err) + } +} + +var ( + _ error = &OpError{} + _ net.Error = &OpError{} + // Ensure compatibility with Go 1.13+ errors package. + _ interface{ Unwrap() error } = &OpError{} +) + +// An OpError is an error produced as the result of a failed netlink operation. +type OpError struct { + // Op is the operation which caused this OpError, such as "send" + // or "receive". + Op string + + // Err is the underlying error which caused this OpError. + // + // If Err was produced by a system call error, Err will be of type + // *os.SyscallError. If Err was produced by an error code in a netlink + // message, Err will contain a raw error value type such as a unix.Errno. + // + // Most callers should inspect Err using errors.Is from the standard + // library. + Err error + + // Message and Offset contain additional error information provided by the + // kernel when the ExtendedAcknowledge option is set on a Conn and the + // kernel indicates the AcknowledgeTLVs flag in a response. If this option + // is not set, both of these fields will be empty. + Message string + Offset int +} + +// newOpError is a small wrapper for creating an OpError. As a convenience, it +// returns nil if the input err is nil: akin to os.NewSyscallError. +func newOpError(op string, err error) error { + if err == nil { + return nil + } + + return &OpError{ + Op: op, + Err: err, + } +} + +func (e *OpError) Error() string { + if e == nil { + return "" + } + + var sb strings.Builder + _, _ = sb.WriteString(fmt.Sprintf("netlink %s: %v", e.Op, e.Err)) + + if e.Message != "" || e.Offset != 0 { + _, _ = sb.WriteString(fmt.Sprintf(", offset: %d, message: %q", + e.Offset, e.Message)) + } + + return sb.String() +} + +// Unwrap unwraps the internal Err field for use with errors.Unwrap. +func (e *OpError) Unwrap() error { return e.Err } + +// Portions of this code taken from the Go standard library: +// +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +type timeout interface { + Timeout() bool +} + +// Timeout reports whether the error was caused by an I/O timeout. +func (e *OpError) Timeout() bool { + if ne, ok := e.Err.(*os.SyscallError); ok { + t, ok := ne.Err.(timeout) + return ok && t.Timeout() + } + t, ok := e.Err.(timeout) + return ok && t.Timeout() +} + +type temporary interface { + Temporary() bool +} + +// Temporary reports whether an operation may succeed if retried. +func (e *OpError) Temporary() bool { + if ne, ok := e.Err.(*os.SyscallError); ok { + t, ok := ne.Err.(temporary) + return ok && t.Temporary() + } + t, ok := e.Err.(temporary) + return ok && t.Temporary() +} diff --git a/vendor/github.com/mdlayher/netlink/fuzz.go b/vendor/github.com/mdlayher/netlink/fuzz.go new file mode 100644 index 0000000..fdd6b64 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/fuzz.go @@ -0,0 +1,82 @@ +//go:build gofuzz +// +build gofuzz + +package netlink + +import "github.com/google/go-cmp/cmp" + +func fuzz(b1 []byte) int { + // 1. unmarshal, marshal, unmarshal again to check m1 and m2 for equality + // after a round trip. checkMessage is also used because there is a fair + // amount of tricky logic around testing for presence of error headers and + // extended acknowledgement attributes. + var m1 Message + if err := m1.UnmarshalBinary(b1); err != nil { + return 0 + } + + if err := checkMessage(m1); err != nil { + return 0 + } + + b2, err := m1.MarshalBinary() + if err != nil { + panicf("failed to marshal m1: %v", err) + } + + var m2 Message + if err := m2.UnmarshalBinary(b2); err != nil { + panicf("failed to unmarshal m2: %v", err) + } + + if err := checkMessage(m2); err != nil { + panicf("failed to check m2: %v", err) + } + + if diff := cmp.Diff(m1, m2); diff != "" { + panicf("unexpected Message (-want +got):\n%s", diff) + } + + // 2. marshal again and compare b2 and b3 (b1 may have reserved bytes set + // which we ignore and fill with zeros when marshaling) for equality. + b3, err := m2.MarshalBinary() + if err != nil { + panicf("failed to marshal m2: %v", err) + } + + if diff := cmp.Diff(b2, b3); diff != "" { + panicf("unexpected message bytes (-want +got):\n%s", diff) + } + + // 3. unmarshal any possible attributes from m1's data and marshal them + // again for comparison. + a1, err := UnmarshalAttributes(m1.Data) + if err != nil { + return 0 + } + + ab1, err := MarshalAttributes(a1) + if err != nil { + panicf("failed to marshal a1: %v", err) + } + + a2, err := UnmarshalAttributes(ab1) + if err != nil { + panicf("failed to unmarshal a2: %v", err) + } + + if diff := cmp.Diff(a1, a2); diff != "" { + panicf("unexpected Attributes (-want +got):\n%s", diff) + } + + ab2, err := MarshalAttributes(a2) + if err != nil { + panicf("failed to marshal a2: %v", err) + } + + if diff := cmp.Diff(ab1, ab2); diff != "" { + panicf("unexpected attribute bytes (-want +got):\n%s", diff) + } + + return 1 +} diff --git a/vendor/github.com/mdlayher/netlink/message.go b/vendor/github.com/mdlayher/netlink/message.go new file mode 100644 index 0000000..5727716 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/message.go @@ -0,0 +1,347 @@ +package netlink + +import ( + "errors" + "fmt" + "unsafe" + + "github.com/mdlayher/netlink/nlenc" +) + +// Flags which may apply to netlink attribute types when communicating with +// certain netlink families. +const ( + Nested uint16 = 0x8000 + NetByteOrder uint16 = 0x4000 + + // attrTypeMask masks off Type bits used for the above flags. + attrTypeMask uint16 = 0x3fff +) + +// Various errors which may occur when attempting to marshal or unmarshal +// a Message to and from its binary form. +var ( + errIncorrectMessageLength = errors.New("netlink message header length incorrect") + errShortMessage = errors.New("not enough data to create a netlink message") + errUnalignedMessage = errors.New("input data is not properly aligned for netlink message") +) + +// HeaderFlags specify flags which may be present in a Header. +type HeaderFlags uint16 + +const ( + // General netlink communication flags. + + // Request indicates a request to netlink. + Request HeaderFlags = 1 + + // Multi indicates a multi-part message, terminated by Done on the + // last message. + Multi HeaderFlags = 2 + + // Acknowledge requests that netlink reply with an acknowledgement + // using Error and, if needed, an error code. + Acknowledge HeaderFlags = 4 + + // Echo requests that netlink echo this request back to the sender. + Echo HeaderFlags = 8 + + // DumpInterrupted indicates that a dump was inconsistent due to a + // sequence change. + DumpInterrupted HeaderFlags = 16 + + // DumpFiltered indicates that a dump was filtered as requested. + DumpFiltered HeaderFlags = 32 + + // Flags used to retrieve data from netlink. + + // Root requests that netlink return a complete table instead of a + // single entry. + Root HeaderFlags = 0x100 + + // Match requests that netlink return a list of all matching entries. + Match HeaderFlags = 0x200 + + // Atomic requests that netlink send an atomic snapshot of its entries. + // Requires CAP_NET_ADMIN or an effective UID of 0. + Atomic HeaderFlags = 0x400 + + // Dump requests that netlink return a complete list of all entries. + Dump HeaderFlags = Root | Match + + // Flags used to create objects. + + // Replace indicates request replaces an existing matching object. + Replace HeaderFlags = 0x100 + + // Excl indicates request does not replace the object if it already exists. + Excl HeaderFlags = 0x200 + + // Create indicates request creates an object if it doesn't already exist. + Create HeaderFlags = 0x400 + + // Append indicates request adds to the end of the object list. + Append HeaderFlags = 0x800 + + // Flags for extended acknowledgements. + + // Capped indicates the size of a request was capped in an extended + // acknowledgement. + Capped HeaderFlags = 0x100 + + // AcknowledgeTLVs indicates the presence of netlink extended + // acknowledgement TLVs in a response. + AcknowledgeTLVs HeaderFlags = 0x200 +) + +// String returns the string representation of a HeaderFlags. +func (f HeaderFlags) String() string { + names := []string{ + "request", + "multi", + "acknowledge", + "echo", + "dumpinterrupted", + "dumpfiltered", + } + + var s string + + left := uint(f) + + for i, name := range names { + if f&(1< 0 { + if s != "" { + s += "|" + } + s += fmt.Sprintf("%#x", left) + } + + return s +} + +// HeaderType specifies the type of a Header. +type HeaderType uint16 + +const ( + // Noop indicates that no action was taken. + Noop HeaderType = 0x1 + + // Error indicates an error code is present, which is also used to indicate + // success when the code is 0. + Error HeaderType = 0x2 + + // Done indicates the end of a multi-part message. + Done HeaderType = 0x3 + + // Overrun indicates that data was lost from this message. + Overrun HeaderType = 0x4 +) + +// String returns the string representation of a HeaderType. +func (t HeaderType) String() string { + switch t { + case Noop: + return "noop" + case Error: + return "error" + case Done: + return "done" + case Overrun: + return "overrun" + default: + return fmt.Sprintf("unknown(%d)", t) + } +} + +// NB: the memory layout of Header and Linux's syscall.NlMsgHdr must be +// exactly the same. Cannot reorder, change data type, add, or remove fields. +// Named types of the same size (e.g. HeaderFlags is a uint16) are okay. + +// A Header is a netlink header. A Header is sent and received with each +// Message to indicate metadata regarding a Message. +type Header struct { + // Length of a Message, including this Header. + Length uint32 + + // Contents of a Message. + Type HeaderType + + // Flags which may be used to modify a request or response. + Flags HeaderFlags + + // The sequence number of a Message. + Sequence uint32 + + // The port ID of the sending process. + PID uint32 +} + +// A Message is a netlink message. It contains a Header and an arbitrary +// byte payload, which may be decoded using information from the Header. +// +// Data is often populated with netlink attributes. For easy encoding and +// decoding of attributes, see the AttributeDecoder and AttributeEncoder types. +type Message struct { + Header Header + Data []byte +} + +// MarshalBinary marshals a Message into a byte slice. +func (m Message) MarshalBinary() ([]byte, error) { + ml := nlmsgAlign(int(m.Header.Length)) + if ml < nlmsgHeaderLen || ml != int(m.Header.Length) { + return nil, errIncorrectMessageLength + } + + b := make([]byte, ml) + + nlenc.PutUint32(b[0:4], m.Header.Length) + nlenc.PutUint16(b[4:6], uint16(m.Header.Type)) + nlenc.PutUint16(b[6:8], uint16(m.Header.Flags)) + nlenc.PutUint32(b[8:12], m.Header.Sequence) + nlenc.PutUint32(b[12:16], m.Header.PID) + copy(b[16:], m.Data) + + return b, nil +} + +// UnmarshalBinary unmarshals the contents of a byte slice into a Message. +func (m *Message) UnmarshalBinary(b []byte) error { + if len(b) < nlmsgHeaderLen { + return errShortMessage + } + if len(b) != nlmsgAlign(len(b)) { + return errUnalignedMessage + } + + // Don't allow misleading length + m.Header.Length = nlenc.Uint32(b[0:4]) + if int(m.Header.Length) != len(b) { + return errShortMessage + } + + m.Header.Type = HeaderType(nlenc.Uint16(b[4:6])) + m.Header.Flags = HeaderFlags(nlenc.Uint16(b[6:8])) + m.Header.Sequence = nlenc.Uint32(b[8:12]) + m.Header.PID = nlenc.Uint32(b[12:16]) + m.Data = b[16:] + + return nil +} + +// checkMessage checks a single Message for netlink errors. +func checkMessage(m Message) error { + // NB: All non-nil errors returned from this function *must* be of type + // OpError in order to maintain the appropriate contract with callers of + // this package. + + // The libnl documentation indicates that type error can + // contain error codes: + // https://www.infradead.org/~tgr/libnl/doc/core.html#core_errmsg. + // + // However, rtnetlink at least seems to also allow errors to occur at the + // end of a multipart message with done/multi and an error number. + var hasHeader bool + switch { + case m.Header.Type == Error: + // Error code followed by nlmsghdr/ext ack attributes. + hasHeader = true + case m.Header.Type == Done && m.Header.Flags&Multi != 0: + // If no data, there must be no error number so just exit early. Some + // of the unit tests hard-coded this but I don't actually know if this + // case occurs in the wild. + if len(m.Data) == 0 { + return nil + } + + // Done|Multi potentially followed by ext ack attributes. + default: + // Neither, nothing to do. + return nil + } + + // Errno occupies 4 bytes. + const endErrno = 4 + if len(m.Data) < endErrno { + return newOpError("receive", errShortErrorMessage) + } + + c := nlenc.Int32(m.Data[:endErrno]) + if c == 0 { + // 0 indicates no error. + return nil + } + + oerr := &OpError{ + Op: "receive", + // Error code is a negative integer, convert it into an OS-specific raw + // system call error, but do not wrap with os.NewSyscallError to signify + // that this error was produced by a netlink message; not a system call. + Err: newError(-1 * int(c)), + } + + // TODO(mdlayher): investigate the Capped flag. + + if m.Header.Flags&AcknowledgeTLVs == 0 { + // No extended acknowledgement. + return oerr + } + + // Flags indicate an extended acknowledgement. The type/flags combination + // checked above determines the offset where the TLVs occur. + var off int + if hasHeader { + // There is an nlmsghdr preceding the TLVs. + if len(m.Data) < endErrno+nlmsgHeaderLen { + return newOpError("receive", errShortErrorMessage) + } + + // The TLVs should be at the offset indicated by the nlmsghdr.length, + // plus the offset where the header began. But make sure the calculated + // offset is still in-bounds. + h := *(*Header)(unsafe.Pointer(&m.Data[endErrno : endErrno+nlmsgHeaderLen][0])) + off = endErrno + int(h.Length) + + if len(m.Data) < off { + return newOpError("receive", errShortErrorMessage) + } + } else { + // There is no nlmsghdr preceding the TLVs, parse them directly. + off = endErrno + } + + ad, err := NewAttributeDecoder(m.Data[off:]) + if err != nil { + // Malformed TLVs, just return the OpError with the info we have. + return oerr + } + + for ad.Next() { + switch ad.Type() { + case 1: // unix.NLMSGERR_ATTR_MSG + oerr.Message = ad.String() + case 2: // unix.NLMSGERR_ATTR_OFFS + oerr.Offset = int(ad.Uint32()) + } + } + + // Explicitly ignore ad.Err: malformed TLVs, just return the OpError with + // the info we have. + return oerr +} diff --git a/vendor/github.com/mdlayher/netlink/nlenc/doc.go b/vendor/github.com/mdlayher/netlink/nlenc/doc.go new file mode 100644 index 0000000..3b42119 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/nlenc/doc.go @@ -0,0 +1,15 @@ +// Package nlenc implements encoding and decoding functions for netlink +// messages and attributes. +package nlenc + +import ( + "encoding/binary" + + "github.com/josharian/native" +) + +// NativeEndian returns the native byte order of this system. +func NativeEndian() binary.ByteOrder { + // TODO(mdlayher): consider deprecating and removing this function for v2. + return native.Endian +} diff --git a/vendor/github.com/mdlayher/netlink/nlenc/int.go b/vendor/github.com/mdlayher/netlink/nlenc/int.go new file mode 100644 index 0000000..d56b018 --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/nlenc/int.go @@ -0,0 +1,150 @@ +package nlenc + +import ( + "fmt" + "unsafe" +) + +// PutUint8 encodes a uint8 into b. +// If b is not exactly 1 byte in length, PutUint8 will panic. +func PutUint8(b []byte, v uint8) { + if l := len(b); l != 1 { + panic(fmt.Sprintf("PutUint8: unexpected byte slice length: %d", l)) + } + + b[0] = v +} + +// PutUint16 encodes a uint16 into b using the host machine's native endianness. +// If b is not exactly 2 bytes in length, PutUint16 will panic. +func PutUint16(b []byte, v uint16) { + if l := len(b); l != 2 { + panic(fmt.Sprintf("PutUint16: unexpected byte slice length: %d", l)) + } + + *(*uint16)(unsafe.Pointer(&b[0])) = v +} + +// PutUint32 encodes a uint32 into b using the host machine's native endianness. +// If b is not exactly 4 bytes in length, PutUint32 will panic. +func PutUint32(b []byte, v uint32) { + if l := len(b); l != 4 { + panic(fmt.Sprintf("PutUint32: unexpected byte slice length: %d", l)) + } + + *(*uint32)(unsafe.Pointer(&b[0])) = v +} + +// PutUint64 encodes a uint64 into b using the host machine's native endianness. +// If b is not exactly 8 bytes in length, PutUint64 will panic. +func PutUint64(b []byte, v uint64) { + if l := len(b); l != 8 { + panic(fmt.Sprintf("PutUint64: unexpected byte slice length: %d", l)) + } + + *(*uint64)(unsafe.Pointer(&b[0])) = v +} + +// PutInt32 encodes a int32 into b using the host machine's native endianness. +// If b is not exactly 4 bytes in length, PutInt32 will panic. +func PutInt32(b []byte, v int32) { + if l := len(b); l != 4 { + panic(fmt.Sprintf("PutInt32: unexpected byte slice length: %d", l)) + } + + *(*int32)(unsafe.Pointer(&b[0])) = v +} + +// Uint8 decodes a uint8 from b. +// If b is not exactly 1 byte in length, Uint8 will panic. +func Uint8(b []byte) uint8 { + if l := len(b); l != 1 { + panic(fmt.Sprintf("Uint8: unexpected byte slice length: %d", l)) + } + + return b[0] +} + +// Uint16 decodes a uint16 from b using the host machine's native endianness. +// If b is not exactly 2 bytes in length, Uint16 will panic. +func Uint16(b []byte) uint16 { + if l := len(b); l != 2 { + panic(fmt.Sprintf("Uint16: unexpected byte slice length: %d", l)) + } + + return *(*uint16)(unsafe.Pointer(&b[0])) +} + +// Uint32 decodes a uint32 from b using the host machine's native endianness. +// If b is not exactly 4 bytes in length, Uint32 will panic. +func Uint32(b []byte) uint32 { + if l := len(b); l != 4 { + panic(fmt.Sprintf("Uint32: unexpected byte slice length: %d", l)) + } + + return *(*uint32)(unsafe.Pointer(&b[0])) +} + +// Uint64 decodes a uint64 from b using the host machine's native endianness. +// If b is not exactly 8 bytes in length, Uint64 will panic. +func Uint64(b []byte) uint64 { + if l := len(b); l != 8 { + panic(fmt.Sprintf("Uint64: unexpected byte slice length: %d", l)) + } + + return *(*uint64)(unsafe.Pointer(&b[0])) +} + +// Int32 decodes an int32 from b using the host machine's native endianness. +// If b is not exactly 4 bytes in length, Int32 will panic. +func Int32(b []byte) int32 { + if l := len(b); l != 4 { + panic(fmt.Sprintf("Int32: unexpected byte slice length: %d", l)) + } + + return *(*int32)(unsafe.Pointer(&b[0])) +} + +// Uint8Bytes encodes a uint8 into a newly-allocated byte slice. It is a +// shortcut for allocating a new byte slice and filling it using PutUint8. +func Uint8Bytes(v uint8) []byte { + b := make([]byte, 1) + PutUint8(b, v) + return b +} + +// Uint16Bytes encodes a uint16 into a newly-allocated byte slice using the +// host machine's native endianness. It is a shortcut for allocating a new +// byte slice and filling it using PutUint16. +func Uint16Bytes(v uint16) []byte { + b := make([]byte, 2) + PutUint16(b, v) + return b +} + +// Uint32Bytes encodes a uint32 into a newly-allocated byte slice using the +// host machine's native endianness. It is a shortcut for allocating a new +// byte slice and filling it using PutUint32. +func Uint32Bytes(v uint32) []byte { + b := make([]byte, 4) + PutUint32(b, v) + return b +} + +// Uint64Bytes encodes a uint64 into a newly-allocated byte slice using the +// host machine's native endianness. It is a shortcut for allocating a new +// byte slice and filling it using PutUint64. +func Uint64Bytes(v uint64) []byte { + b := make([]byte, 8) + PutUint64(b, v) + return b +} + +// Int32Bytes encodes a int32 into a newly-allocated byte slice using the +// host machine's native endianness. It is a shortcut for allocating a new +// byte slice and filling it using PutInt32. +func Int32Bytes(v int32) []byte { + b := make([]byte, 4) + PutInt32(b, v) + return b +} diff --git a/vendor/github.com/mdlayher/netlink/nlenc/string.go b/vendor/github.com/mdlayher/netlink/nlenc/string.go new file mode 100644 index 0000000..c0b166d --- /dev/null +++ b/vendor/github.com/mdlayher/netlink/nlenc/string.go @@ -0,0 +1,18 @@ +package nlenc + +import "bytes" + +// Bytes returns a null-terminated byte slice with the contents of s. +func Bytes(s string) []byte { + return append([]byte(s), 0x00) +} + +// String returns a string with the contents of b from a null-terminated +// byte slice. +func String(b []byte) string { + // If the string has more than one NULL terminator byte, we want to remove + // all of them before returning the string to the caller; hence the use of + // strings.TrimRight instead of strings.TrimSuffix (which previously only + // removed a single NULL). + return string(bytes.TrimRight(b, "\x00")) +} diff --git a/vendor/github.com/mdlayher/socket/CHANGELOG.md b/vendor/github.com/mdlayher/socket/CHANGELOG.md new file mode 100644 index 0000000..f0d0164 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/CHANGELOG.md @@ -0,0 +1,80 @@ +# CHANGELOG + +## v0.4.1 + +- [Bug Fix] [commit](https://github.com/mdlayher/socket/commit/2a14ceef4da279de1f957c5761fffcc6c87bbd3b): + ensure `socket.Conn` can be used with non-socket file descriptors by handling + `ENOTSOCK` in the constructor. + +## v0.4.0 + +**This is the first release of package socket that only supports Go 1.18+. +Users on older versions of Go must use v0.3.0.** + +- [Improvement]: drop support for older versions of Go so we can begin using + modern versions of `x/sys` and other dependencies. + +## v0.3.0 + +**This is the last release of package socket that supports Go 1.17 and below.** + +- [New API/API change] [PR](https://github.com/mdlayher/socket/pull/8): + numerous `socket.Conn` methods now support context cancelation. Future + releases will continue adding support as needed. + - New `ReadContext` and `WriteContext` methods. + - `Connect`, `Recvfrom`, `Recvmsg`, `Sendmsg`, and `Sendto` methods now accept + a context. + - `Sendto` parameter order was also fixed to match the underlying syscall. + +## v0.2.3 + +- [New API] [commit](https://github.com/mdlayher/socket/commit/a425d96e0f772c053164f8ce4c9c825380a98086): + `socket.Conn` has new `Pidfd*` methods for wrapping the `pidfd_*(2)` family of + system calls. + +## v0.2.2 + +- [New API] [commit](https://github.com/mdlayher/socket/commit/a2429f1dfe8ec2586df5a09f50ead865276cd027): + `socket.Conn` has new `IoctlKCM*` methods for wrapping `ioctl(2)` for `AF_KCM` + operations. + +## v0.2.1 + +- [New API] [commit](https://github.com/mdlayher/socket/commit/b18ddbe9caa0e34552b4409a3aa311cb460d2f99): + `socket.Conn` has a new `SetsockoptPacketMreq` method for wrapping + `setsockopt(2)` for `AF_PACKET` socket options. + +## v0.2.0 + +- [New API] [commit](https://github.com/mdlayher/socket/commit/6e912a68523c45e5fd899239f4b46c402dd856da): + `socket.FileConn` can be used to create a `socket.Conn` from an existing + `os.File`, which may be provided by systemd socket activation or another + external mechanism. +- [API change] [commit](https://github.com/mdlayher/socket/commit/66d61f565188c23fe02b24099ddc856d538bf1a7): + `socket.Conn.Connect` now returns the `unix.Sockaddr` value provided by + `getpeername(2)`, since we have to invoke that system call anyway to verify + that a connection to a remote peer was successfully established. +- [Bug Fix] [commit](https://github.com/mdlayher/socket/commit/b60b2dbe0ac3caff2338446a150083bde8c5c19c): + check the correct error from `unix.GetsockoptInt` in the `socket.Conn.Connect` + method. Thanks @vcabbage! + +## v0.1.2 + +- [Bug Fix]: `socket.Conn.Connect` now properly checks the `SO_ERROR` socket + option value after calling `connect(2)` to verify whether or not a connection + could successfully be established. This means that `Connect` should now report + an error for an `AF_INET` TCP connection refused or `AF_VSOCK` connection + reset by peer. +- [New API]: add `socket.Conn.Getpeername` for use in `Connect`, but also for + use by external callers. + +## v0.1.1 + +- [New API]: `socket.Conn` now has `CloseRead`, `CloseWrite`, and `Shutdown` + methods. +- [Improvement]: internal rework to more robustly handle various errors. + +## v0.1.0 + +- Initial unstable release. Most functionality has been developed and ported +from package [`netlink`](https://github.com/mdlayher/netlink). diff --git a/vendor/github.com/mdlayher/socket/LICENSE.md b/vendor/github.com/mdlayher/socket/LICENSE.md new file mode 100644 index 0000000..3ccdb75 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/LICENSE.md @@ -0,0 +1,9 @@ +# MIT License + +Copyright (C) 2021 Matt Layher + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mdlayher/socket/README.md b/vendor/github.com/mdlayher/socket/README.md new file mode 100644 index 0000000..2aa065c --- /dev/null +++ b/vendor/github.com/mdlayher/socket/README.md @@ -0,0 +1,23 @@ +# socket [![Test Status](https://github.com/mdlayher/socket/workflows/Test/badge.svg)](https://github.com/mdlayher/socket/actions) [![Go Reference](https://pkg.go.dev/badge/github.com/mdlayher/socket.svg)](https://pkg.go.dev/github.com/mdlayher/socket) [![Go Report Card](https://goreportcard.com/badge/github.com/mdlayher/socket)](https://goreportcard.com/report/github.com/mdlayher/socket) + +Package `socket` provides a low-level network connection type which integrates +with Go's runtime network poller to provide asynchronous I/O and deadline +support. MIT Licensed. + +This package focuses on UNIX-like operating systems which make use of BSD +sockets system call APIs. It is meant to be used as a foundation for the +creation of operating system-specific socket packages, for socket families such +as Linux's `AF_NETLINK`, `AF_PACKET`, or `AF_VSOCK`. This package should not be +used directly in end user applications. + +Any use of package socket should be guarded by build tags, as one would also +use when importing the `syscall` or `golang.org/x/sys` packages. + +## Stability + +See the [CHANGELOG](./CHANGELOG.md) file for a description of changes between +releases. + +This package only supports the two most recent major versions of Go, mirroring +Go's own release policy. Older versions of Go may lack critical features and bug +fixes which are necessary for this package to function correctly. diff --git a/vendor/github.com/mdlayher/socket/accept.go b/vendor/github.com/mdlayher/socket/accept.go new file mode 100644 index 0000000..47e9d89 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/accept.go @@ -0,0 +1,23 @@ +//go:build !dragonfly && !freebsd && !illumos && !linux +// +build !dragonfly,!freebsd,!illumos,!linux + +package socket + +import ( + "fmt" + "runtime" + + "golang.org/x/sys/unix" +) + +const sysAccept = "accept" + +// accept wraps accept(2). +func accept(fd, flags int) (int, unix.Sockaddr, error) { + if flags != 0 { + // These operating systems have no support for flags to accept(2). + return 0, nil, fmt.Errorf("socket: Conn.Accept flags are ineffective on %s", runtime.GOOS) + } + + return unix.Accept(fd) +} diff --git a/vendor/github.com/mdlayher/socket/accept4.go b/vendor/github.com/mdlayher/socket/accept4.go new file mode 100644 index 0000000..e1016b2 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/accept4.go @@ -0,0 +1,15 @@ +//go:build dragonfly || freebsd || illumos || linux +// +build dragonfly freebsd illumos linux + +package socket + +import ( + "golang.org/x/sys/unix" +) + +const sysAccept = "accept4" + +// accept wraps accept4(2). +func accept(fd, flags int) (int, unix.Sockaddr, error) { + return unix.Accept4(fd, flags) +} diff --git a/vendor/github.com/mdlayher/socket/conn.go b/vendor/github.com/mdlayher/socket/conn.go new file mode 100644 index 0000000..7b3cc7a --- /dev/null +++ b/vendor/github.com/mdlayher/socket/conn.go @@ -0,0 +1,880 @@ +package socket + +import ( + "context" + "errors" + "io" + "os" + "sync" + "sync/atomic" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// Lock in an expected public interface for convenience. +var _ interface { + io.ReadWriteCloser + syscall.Conn + SetDeadline(t time.Time) error + SetReadDeadline(t time.Time) error + SetWriteDeadline(t time.Time) error +} = &Conn{} + +// A Conn is a low-level network connection which integrates with Go's runtime +// network poller to provide asynchronous I/O and deadline support. +// +// Many of a Conn's blocking methods support net.Conn deadlines as well as +// cancelation via context. Note that passing a context with a deadline set will +// override any of the previous deadlines set by calls to the SetDeadline family +// of methods. +type Conn struct { + // Indicates whether or not Conn.Close has been called. Must be accessed + // atomically. Atomics definitions must come first in the Conn struct. + closed uint32 + + // A unique name for the Conn which is also associated with derived file + // descriptors such as those created by accept(2). + name string + + // facts contains information we have determined about Conn to trigger + // alternate behavior in certain functions. + facts facts + + // Provides access to the underlying file registered with the runtime + // network poller, and arbitrary raw I/O calls. + fd *os.File + rc syscall.RawConn +} + +// facts contains facts about a Conn. +type facts struct { + // isStream reports whether this is a streaming descriptor, as opposed to a + // packet-based descriptor like a UDP socket. + isStream bool + + // zeroReadIsEOF reports Whether a zero byte read indicates EOF. This is + // false for a message based socket connection. + zeroReadIsEOF bool +} + +// A Config contains options for a Conn. +type Config struct { + // NetNS specifies the Linux network namespace the Conn will operate in. + // This option is unsupported on other operating systems. + // + // If set (non-zero), Conn will enter the specified network namespace and an + // error will occur in Socket if the operation fails. + // + // If not set (zero), a best-effort attempt will be made to enter the + // network namespace of the calling thread: this means that any changes made + // to the calling thread's network namespace will also be reflected in Conn. + // If this operation fails (due to lack of permissions or because network + // namespaces are disabled by kernel configuration), Socket will not return + // an error, and the Conn will operate in the default network namespace of + // the process. This enables non-privileged use of Conn in applications + // which do not require elevated privileges. + // + // Entering a network namespace is a privileged operation (root or + // CAP_SYS_ADMIN are required), and most applications should leave this set + // to 0. + NetNS int +} + +// High-level methods which provide convenience over raw system calls. + +// Close closes the underlying file descriptor for the Conn, which also causes +// all in-flight I/O operations to immediately unblock and return errors. Any +// subsequent uses of Conn will result in EBADF. +func (c *Conn) Close() error { + // The caller has expressed an intent to close the socket, so immediately + // increment s.closed to force further calls to result in EBADF before also + // closing the file descriptor to unblock any outstanding operations. + // + // Because other operations simply check for s.closed != 0, we will permit + // double Close, which would increment s.closed beyond 1. + if atomic.AddUint32(&c.closed, 1) != 1 { + // Multiple Close calls. + return nil + } + + return os.NewSyscallError("close", c.fd.Close()) +} + +// CloseRead shuts down the reading side of the Conn. Most callers should just +// use Close. +func (c *Conn) CloseRead() error { return c.Shutdown(unix.SHUT_RD) } + +// CloseWrite shuts down the writing side of the Conn. Most callers should just +// use Close. +func (c *Conn) CloseWrite() error { return c.Shutdown(unix.SHUT_WR) } + +// Read reads directly from the underlying file descriptor. +func (c *Conn) Read(b []byte) (int, error) { return c.fd.Read(b) } + +// ReadContext reads from the underlying file descriptor with added support for +// context cancelation. +func (c *Conn) ReadContext(ctx context.Context, b []byte) (int, error) { + if c.facts.isStream && len(b) > maxRW { + b = b[:maxRW] + } + + n, err := readT(c, ctx, "read", func(fd int) (int, error) { + return unix.Read(fd, b) + }) + if n == 0 && err == nil && c.facts.zeroReadIsEOF { + return 0, io.EOF + } + + return n, os.NewSyscallError("read", err) +} + +// Write writes directly to the underlying file descriptor. +func (c *Conn) Write(b []byte) (int, error) { return c.fd.Write(b) } + +// WriteContext writes to the underlying file descriptor with added support for +// context cancelation. +func (c *Conn) WriteContext(ctx context.Context, b []byte) (int, error) { + var ( + n, nn int + err error + ) + + doErr := c.write(ctx, "write", func(fd int) error { + max := len(b) + if c.facts.isStream && max-nn > maxRW { + max = nn + maxRW + } + + n, err = unix.Write(fd, b[nn:max]) + if n > 0 { + nn += n + } + if nn == len(b) { + return err + } + if n == 0 && err == nil { + err = io.ErrUnexpectedEOF + return nil + } + + return err + }) + if doErr != nil { + return 0, doErr + } + + return nn, os.NewSyscallError("write", err) +} + +// SetDeadline sets both the read and write deadlines associated with the Conn. +func (c *Conn) SetDeadline(t time.Time) error { return c.fd.SetDeadline(t) } + +// SetReadDeadline sets the read deadline associated with the Conn. +func (c *Conn) SetReadDeadline(t time.Time) error { return c.fd.SetReadDeadline(t) } + +// SetWriteDeadline sets the write deadline associated with the Conn. +func (c *Conn) SetWriteDeadline(t time.Time) error { return c.fd.SetWriteDeadline(t) } + +// ReadBuffer gets the size of the operating system's receive buffer associated +// with the Conn. +func (c *Conn) ReadBuffer() (int, error) { + return c.GetsockoptInt(unix.SOL_SOCKET, unix.SO_RCVBUF) +} + +// WriteBuffer gets the size of the operating system's transmit buffer +// associated with the Conn. +func (c *Conn) WriteBuffer() (int, error) { + return c.GetsockoptInt(unix.SOL_SOCKET, unix.SO_SNDBUF) +} + +// SetReadBuffer sets the size of the operating system's receive buffer +// associated with the Conn. +// +// When called with elevated privileges on Linux, the SO_RCVBUFFORCE option will +// be used to override operating system limits. Otherwise SO_RCVBUF is used +// (which obeys operating system limits). +func (c *Conn) SetReadBuffer(bytes int) error { return c.setReadBuffer(bytes) } + +// SetWriteBuffer sets the size of the operating system's transmit buffer +// associated with the Conn. +// +// When called with elevated privileges on Linux, the SO_SNDBUFFORCE option will +// be used to override operating system limits. Otherwise SO_SNDBUF is used +// (which obeys operating system limits). +func (c *Conn) SetWriteBuffer(bytes int) error { return c.setWriteBuffer(bytes) } + +// SyscallConn returns a raw network connection. This implements the +// syscall.Conn interface. +// +// SyscallConn is intended for advanced use cases, such as getting and setting +// arbitrary socket options using the socket's file descriptor. If possible, +// those operations should be performed using methods on Conn instead. +// +// Once invoked, it is the caller's responsibility to ensure that operations +// performed using Conn and the syscall.RawConn do not conflict with each other. +func (c *Conn) SyscallConn() (syscall.RawConn, error) { + if atomic.LoadUint32(&c.closed) != 0 { + return nil, os.NewSyscallError("syscallconn", unix.EBADF) + } + + // TODO(mdlayher): mutex or similar to enforce syscall.RawConn contract of + // FD remaining valid for duration of calls? + return c.rc, nil +} + +// Socket wraps the socket(2) system call to produce a Conn. domain, typ, and +// proto are passed directly to socket(2), and name should be a unique name for +// the socket type such as "netlink" or "vsock". +// +// The cfg parameter specifies optional configuration for the Conn. If nil, no +// additional configuration will be applied. +// +// If the operating system supports SOCK_CLOEXEC and SOCK_NONBLOCK, they are +// automatically applied to typ to mirror the standard library's socket flag +// behaviors. +func Socket(domain, typ, proto int, name string, cfg *Config) (*Conn, error) { + if cfg == nil { + cfg = &Config{} + } + + if cfg.NetNS == 0 { + // Non-Linux or no network namespace. + return socket(domain, typ, proto, name) + } + + // Linux only: create Conn in the specified network namespace. + return withNetNS(cfg.NetNS, func() (*Conn, error) { + return socket(domain, typ, proto, name) + }) +} + +// socket is the internal, cross-platform entry point for socket(2). +func socket(domain, typ, proto int, name string) (*Conn, error) { + var ( + fd int + err error + ) + + for { + fd, err = unix.Socket(domain, typ|socketFlags, proto) + switch { + case err == nil: + // Some OSes already set CLOEXEC with typ. + if !flagCLOEXEC { + unix.CloseOnExec(fd) + } + + // No error, prepare the Conn. + return New(fd, name) + case !ready(err): + // System call interrupted or not ready, try again. + continue + case err == unix.EINVAL, err == unix.EPROTONOSUPPORT: + // On Linux, SOCK_NONBLOCK and SOCK_CLOEXEC were introduced in + // 2.6.27. On FreeBSD, both flags were introduced in FreeBSD 10. + // EINVAL and EPROTONOSUPPORT check for earlier versions of these + // OSes respectively. + // + // Mirror what the standard library does when creating file + // descriptors: avoid racing a fork/exec with the creation of new + // file descriptors, so that child processes do not inherit socket + // file descriptors unexpectedly. + // + // For a more thorough explanation, see similar work in the Go tree: + // func sysSocket in net/sock_cloexec.go, as well as the detailed + // comment in syscall/exec_unix.go. + syscall.ForkLock.RLock() + fd, err = unix.Socket(domain, typ, proto) + if err != nil { + syscall.ForkLock.RUnlock() + return nil, os.NewSyscallError("socket", err) + } + unix.CloseOnExec(fd) + syscall.ForkLock.RUnlock() + + return New(fd, name) + default: + // Unhandled error. + return nil, os.NewSyscallError("socket", err) + } + } +} + +// FileConn returns a copy of the network connection corresponding to the open +// file. It is the caller's responsibility to close the file when finished. +// Closing the Conn does not affect the File, and closing the File does not +// affect the Conn. +func FileConn(f *os.File, name string) (*Conn, error) { + // First we'll try to do fctnl(2) with F_DUPFD_CLOEXEC because we can dup + // the file descriptor and set the flag in one syscall. + fd, err := unix.FcntlInt(f.Fd(), unix.F_DUPFD_CLOEXEC, 0) + switch err { + case nil: + // OK, ready to set up non-blocking I/O. + return New(fd, name) + case unix.EINVAL: + // The kernel rejected our fcntl(2), fall back to separate dup(2) and + // setting close on exec. + // + // Mirror what the standard library does when creating file descriptors: + // avoid racing a fork/exec with the creation of new file descriptors, + // so that child processes do not inherit socket file descriptors + // unexpectedly. + syscall.ForkLock.RLock() + fd, err := unix.Dup(fd) + if err != nil { + syscall.ForkLock.RUnlock() + return nil, os.NewSyscallError("dup", err) + } + unix.CloseOnExec(fd) + syscall.ForkLock.RUnlock() + + return New(fd, name) + default: + // Any other errors. + return nil, os.NewSyscallError("fcntl", err) + } +} + +// New wraps an existing file descriptor to create a Conn. name should be a +// unique name for the socket type such as "netlink" or "vsock". +// +// Most callers should use Socket or FileConn to construct a Conn. New is +// intended for integrating with specific system calls which provide a file +// descriptor that supports asynchronous I/O. The file descriptor is immediately +// set to nonblocking mode and registered with Go's runtime network poller for +// future I/O operations. +// +// Unlike FileConn, New does not duplicate the existing file descriptor in any +// way. The returned Conn takes ownership of the underlying file descriptor. +func New(fd int, name string) (*Conn, error) { + // All Conn I/O is nonblocking for integration with Go's runtime network + // poller. Depending on the OS this might already be set but it can't hurt + // to set it again. + if err := unix.SetNonblock(fd, true); err != nil { + return nil, os.NewSyscallError("setnonblock", err) + } + + // os.NewFile registers the non-blocking file descriptor with the runtime + // poller, which is then used for most subsequent operations except those + // that require raw I/O via SyscallConn. + // + // See also: https://golang.org/pkg/os/#NewFile + f := os.NewFile(uintptr(fd), name) + rc, err := f.SyscallConn() + if err != nil { + return nil, err + } + + c := &Conn{ + name: name, + fd: f, + rc: rc, + } + + // Probe the file descriptor for socket settings. + sotype, err := c.GetsockoptInt(unix.SOL_SOCKET, unix.SO_TYPE) + switch { + case err == nil: + // File is a socket, check its properties. + c.facts = facts{ + isStream: sotype == unix.SOCK_STREAM, + zeroReadIsEOF: sotype != unix.SOCK_DGRAM && sotype != unix.SOCK_RAW, + } + case errors.Is(err, unix.ENOTSOCK): + // File is not a socket, treat it as a regular file. + c.facts = facts{ + isStream: true, + zeroReadIsEOF: true, + } + default: + return nil, err + } + + return c, nil +} + +// Low-level methods which provide raw system call access. + +// Accept wraps accept(2) or accept4(2) depending on the operating system, but +// returns a Conn for the accepted connection rather than a raw file descriptor. +// +// If the operating system supports accept4(2) (which allows flags), +// SOCK_CLOEXEC and SOCK_NONBLOCK are automatically applied to flags to mirror +// the standard library's socket flag behaviors. +// +// If the operating system only supports accept(2) (which does not allow flags) +// and flags is not zero, an error will be returned. +// +// Accept obeys context cancelation and uses the deadline set on the context to +// cancel accepting the next connection. If a deadline is set on ctx, this +// deadline will override any previous deadlines set using SetDeadline or +// SetReadDeadline. Upon return, the read deadline is cleared. +func (c *Conn) Accept(ctx context.Context, flags int) (*Conn, unix.Sockaddr, error) { + type ret struct { + nfd int + sa unix.Sockaddr + } + + r, err := readT(c, ctx, sysAccept, func(fd int) (ret, error) { + // Either accept(2) or accept4(2) depending on the OS. + nfd, sa, err := accept(fd, flags|socketFlags) + return ret{nfd, sa}, err + }) + if err != nil { + // internal/poll, context error, or user function error. + return nil, nil, err + } + + // Successfully accepted a connection, wrap it in a Conn for use by the + // caller. + ac, err := New(r.nfd, c.name) + if err != nil { + return nil, nil, err + } + + return ac, r.sa, nil +} + +// Bind wraps bind(2). +func (c *Conn) Bind(sa unix.Sockaddr) error { + return c.control(context.Background(), "bind", func(fd int) error { + return unix.Bind(fd, sa) + }) +} + +// Connect wraps connect(2). In order to verify that the underlying socket is +// connected to a remote peer, Connect calls getpeername(2) and returns the +// unix.Sockaddr from that call. +// +// Connect obeys context cancelation and uses the deadline set on the context to +// cancel connecting to a remote peer. If a deadline is set on ctx, this +// deadline will override any previous deadlines set using SetDeadline or +// SetWriteDeadline. Upon return, the write deadline is cleared. +func (c *Conn) Connect(ctx context.Context, sa unix.Sockaddr) (unix.Sockaddr, error) { + const op = "connect" + + // TODO(mdlayher): it would seem that trying to connect to unbound vsock + // listeners by calling Connect multiple times results in ECONNRESET for the + // first and nil error for subsequent calls. Do we need to memoize the + // error? Check what the stdlib behavior is. + + var ( + // Track progress between invocations of the write closure. We don't + // have an explicit WaitWrite call like internal/poll does, so we have + // to wait until the runtime calls the closure again to indicate we can + // write. + progress uint32 + + // Capture closure sockaddr and error. + rsa unix.Sockaddr + err error + ) + + doErr := c.write(ctx, op, func(fd int) error { + if atomic.AddUint32(&progress, 1) == 1 { + // First call: initiate connect. + return unix.Connect(fd, sa) + } + + // Subsequent calls: the runtime network poller indicates fd is + // writable. Check for errno. + errno, gerr := c.GetsockoptInt(unix.SOL_SOCKET, unix.SO_ERROR) + if gerr != nil { + return gerr + } + if errno != 0 { + // Connection is still not ready or failed. If errno indicates + // the socket is not ready, we will wait for the next write + // event. Otherwise we propagate this errno back to the as a + // permanent error. + uerr := unix.Errno(errno) + err = uerr + return uerr + } + + // According to internal/poll, it's possible for the runtime network + // poller to spuriously wake us and return errno 0 for SO_ERROR. + // Make sure we are actually connected to a peer. + peer, err := c.Getpeername() + if err != nil { + // internal/poll unconditionally goes back to WaitWrite. + // Synthesize an error that will do the same for us. + return unix.EAGAIN + } + + // Connection complete. + rsa = peer + return nil + }) + if doErr != nil { + // internal/poll or context error. + return nil, doErr + } + + if err == unix.EISCONN { + // TODO(mdlayher): is this block obsolete with the addition of the + // getsockopt SO_ERROR check above? + // + // EISCONN is reported if the socket is already established and should + // not be treated as an error. + // - Darwin reports this for at least TCP sockets + // - Linux reports this for at least AF_VSOCK sockets + return rsa, nil + } + + return rsa, os.NewSyscallError(op, err) +} + +// Getsockname wraps getsockname(2). +func (c *Conn) Getsockname() (unix.Sockaddr, error) { + return controlT(c, context.Background(), "getsockname", unix.Getsockname) +} + +// Getpeername wraps getpeername(2). +func (c *Conn) Getpeername() (unix.Sockaddr, error) { + return controlT(c, context.Background(), "getpeername", unix.Getpeername) +} + +// GetsockoptInt wraps getsockopt(2) for integer values. +func (c *Conn) GetsockoptInt(level, opt int) (int, error) { + return controlT(c, context.Background(), "getsockopt", func(fd int) (int, error) { + return unix.GetsockoptInt(fd, level, opt) + }) +} + +// Listen wraps listen(2). +func (c *Conn) Listen(n int) error { + return c.control(context.Background(), "listen", func(fd int) error { + return unix.Listen(fd, n) + }) +} + +// Recvmsg wraps recvmsg(2). +func (c *Conn) Recvmsg(ctx context.Context, p, oob []byte, flags int) (int, int, int, unix.Sockaddr, error) { + type ret struct { + n, oobn, recvflags int + from unix.Sockaddr + } + + r, err := readT(c, ctx, "recvmsg", func(fd int) (ret, error) { + n, oobn, recvflags, from, err := unix.Recvmsg(fd, p, oob, flags) + return ret{n, oobn, recvflags, from}, err + }) + if r.n == 0 && err == nil && c.facts.zeroReadIsEOF { + return 0, 0, 0, nil, io.EOF + } + + return r.n, r.oobn, r.recvflags, r.from, err +} + +// Recvfrom wraps recvfrom(2). +func (c *Conn) Recvfrom(ctx context.Context, p []byte, flags int) (int, unix.Sockaddr, error) { + type ret struct { + n int + addr unix.Sockaddr + } + + out, err := readT(c, ctx, "recvfrom", func(fd int) (ret, error) { + n, addr, err := unix.Recvfrom(fd, p, flags) + return ret{n, addr}, err + }) + if out.n == 0 && err == nil && c.facts.zeroReadIsEOF { + return 0, nil, io.EOF + } + + return out.n, out.addr, err +} + +// Sendmsg wraps sendmsg(2). +func (c *Conn) Sendmsg(ctx context.Context, p, oob []byte, to unix.Sockaddr, flags int) (int, error) { + return writeT(c, ctx, "sendmsg", func(fd int) (int, error) { + return unix.SendmsgN(fd, p, oob, to, flags) + }) +} + +// Sendto wraps sendto(2). +func (c *Conn) Sendto(ctx context.Context, p []byte, flags int, to unix.Sockaddr) error { + return c.write(ctx, "sendto", func(fd int) error { + return unix.Sendto(fd, p, flags, to) + }) +} + +// SetsockoptInt wraps setsockopt(2) for integer values. +func (c *Conn) SetsockoptInt(level, opt, value int) error { + return c.control(context.Background(), "setsockopt", func(fd int) error { + return unix.SetsockoptInt(fd, level, opt, value) + }) +} + +// Shutdown wraps shutdown(2). +func (c *Conn) Shutdown(how int) error { + return c.control(context.Background(), "shutdown", func(fd int) error { + return unix.Shutdown(fd, how) + }) +} + +// Conn low-level read/write/control functions. These functions mirror the +// syscall.RawConn APIs but the input closures return errors rather than +// booleans. + +// read wraps readT to execute a function and capture its error result. This is +// a convenience wrapper for functions which don't return any extra values. +func (c *Conn) read(ctx context.Context, op string, f func(fd int) error) error { + _, err := readT(c, ctx, op, func(fd int) (struct{}, error) { + return struct{}{}, f(fd) + }) + return err +} + +// write executes f, a write function, against the associated file descriptor. +// op is used to create an *os.SyscallError if the file descriptor is closed. +func (c *Conn) write(ctx context.Context, op string, f func(fd int) error) error { + _, err := writeT(c, ctx, op, func(fd int) (struct{}, error) { + return struct{}{}, f(fd) + }) + return err +} + +// readT executes c.rc.Read for op using the input function, returning a newly +// allocated result T. +func readT[T any](c *Conn, ctx context.Context, op string, f func(fd int) (T, error)) (T, error) { + return rwT(c, rwContext[T]{ + Context: ctx, + Type: read, + Op: op, + Do: f, + }) +} + +// writeT executes c.rc.Write for op using the input function, returning a newly +// allocated result T. +func writeT[T any](c *Conn, ctx context.Context, op string, f func(fd int) (T, error)) (T, error) { + return rwT(c, rwContext[T]{ + Context: ctx, + Type: write, + Op: op, + Do: f, + }) +} + +// readWrite indicates if an operation intends to read or write. +type readWrite bool + +// Possible readWrite values. +const ( + read readWrite = false + write readWrite = true +) + +// An rwContext provides arguments to rwT. +type rwContext[T any] struct { + // The caller's context passed for cancelation. + Context context.Context + + // The type of an operation: read or write. + Type readWrite + + // The name of the operation used in errors. + Op string + + // The actual function to perform. + Do func(fd int) (T, error) +} + +// rwT executes c.rc.Read or c.rc.Write (depending on the value of rw.Type) for +// rw.Op using the input function, returning a newly allocated result T. +// +// It obeys context cancelation and the rw.Context must not be nil. +func rwT[T any](c *Conn, rw rwContext[T]) (T, error) { + if atomic.LoadUint32(&c.closed) != 0 { + // If the file descriptor is already closed, do nothing. + return *new(T), os.NewSyscallError(rw.Op, unix.EBADF) + } + + if err := rw.Context.Err(); err != nil { + // Early exit due to context cancel. + return *new(T), os.NewSyscallError(rw.Op, err) + } + + var ( + // The read or write function used to access the runtime network poller. + poll func(func(uintptr) bool) error + + // The read or write function used to set the matching deadline. + deadline func(time.Time) error + ) + + if rw.Type == write { + poll = c.rc.Write + deadline = c.SetWriteDeadline + } else { + poll = c.rc.Read + deadline = c.SetReadDeadline + } + + var ( + // Whether or not the context carried a deadline we are actively using + // for cancelation. + setDeadline bool + + // Signals for the cancelation watcher goroutine. + wg sync.WaitGroup + doneC = make(chan struct{}) + + // Atomic: reports whether we have to disarm the deadline. + // + // TODO(mdlayher): switch back to atomic.Bool when we drop support for + // Go 1.18. + needDisarm int64 + ) + + // On cancel, clean up the watcher. + defer func() { + close(doneC) + wg.Wait() + }() + + if d, ok := rw.Context.Deadline(); ok { + // The context has an explicit deadline. We will use it for cancelation + // but disarm it after poll for the next call. + if err := deadline(d); err != nil { + return *new(T), err + } + setDeadline = true + atomic.AddInt64(&needDisarm, 1) + } else { + // The context does not have an explicit deadline. We have to watch for + // cancelation so we can propagate that signal to immediately unblock + // the runtime network poller. + // + // TODO(mdlayher): is it possible to detect a background context vs a + // context with possible future cancel? + wg.Add(1) + go func() { + defer wg.Done() + + select { + case <-rw.Context.Done(): + // Cancel the operation. Make the caller disarm after poll + // returns. + atomic.AddInt64(&needDisarm, 1) + _ = deadline(time.Unix(0, 1)) + case <-doneC: + // Nothing to do. + } + }() + } + + var ( + t T + err error + ) + + pollErr := poll(func(fd uintptr) bool { + t, err = rw.Do(int(fd)) + return ready(err) + }) + + if atomic.LoadInt64(&needDisarm) > 0 { + _ = deadline(time.Time{}) + } + + if pollErr != nil { + if rw.Context.Err() != nil || (setDeadline && errors.Is(pollErr, os.ErrDeadlineExceeded)) { + // The caller canceled the operation or we set a deadline internally + // and it was reached. + // + // Unpack a plain context error. We wait for the context to be done + // to synchronize state externally. Otherwise we have noticed I/O + // timeout wakeups when we set a deadline but the context was not + // yet marked done. + <-rw.Context.Done() + return *new(T), os.NewSyscallError(rw.Op, rw.Context.Err()) + } + + // Error from syscall.RawConn methods. Conventionally the standard + // library does not wrap internal/poll errors in os.NewSyscallError. + return *new(T), pollErr + } + + // Result from user function. + return t, os.NewSyscallError(rw.Op, err) +} + +// control executes Conn.control for op using the input function. +func (c *Conn) control(ctx context.Context, op string, f func(fd int) error) error { + _, err := controlT(c, ctx, op, func(fd int) (struct{}, error) { + return struct{}{}, f(fd) + }) + return err +} + +// controlT executes c.rc.Control for op using the input function, returning a +// newly allocated result T. +func controlT[T any](c *Conn, ctx context.Context, op string, f func(fd int) (T, error)) (T, error) { + if atomic.LoadUint32(&c.closed) != 0 { + // If the file descriptor is already closed, do nothing. + return *new(T), os.NewSyscallError(op, unix.EBADF) + } + + var ( + t T + err error + ) + + doErr := c.rc.Control(func(fd uintptr) { + // Repeatedly attempt the syscall(s) invoked by f until completion is + // indicated by the return value of ready or the context is canceled. + // + // The last values for t and err are captured outside of the closure for + // use when the loop breaks. + for { + if err = ctx.Err(); err != nil { + // Early exit due to context cancel. + return + } + + t, err = f(int(fd)) + if ready(err) { + return + } + } + }) + if doErr != nil { + // Error from syscall.RawConn methods. Conventionally the standard + // library does not wrap internal/poll errors in os.NewSyscallError. + return *new(T), doErr + } + + // Result from user function. + return t, os.NewSyscallError(op, err) +} + +// ready indicates readiness based on the value of err. +func ready(err error) bool { + switch err { + case unix.EAGAIN, unix.EINPROGRESS, unix.EINTR: + // When a socket is in non-blocking mode, we might see a variety of errors: + // - EAGAIN: most common case for a socket read not being ready + // - EINPROGRESS: reported by some sockets when first calling connect + // - EINTR: system call interrupted, more frequently occurs in Go 1.14+ + // because goroutines can be asynchronously preempted + // + // Return false to let the poller wait for readiness. See the source code + // for internal/poll.FD.RawRead for more details. + return false + default: + // Ready regardless of whether there was an error or no error. + return true + } +} + +// Darwin and FreeBSD can't read or write 2GB+ files at a time, +// even on 64-bit systems. +// The same is true of socket implementations on many systems. +// See golang.org/issue/7812 and golang.org/issue/16266. +// Use 1GB instead of, say, 2GB-1, to keep subsequent reads aligned. +const maxRW = 1 << 30 diff --git a/vendor/github.com/mdlayher/socket/conn_linux.go b/vendor/github.com/mdlayher/socket/conn_linux.go new file mode 100644 index 0000000..37579d4 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/conn_linux.go @@ -0,0 +1,118 @@ +//go:build linux +// +build linux + +package socket + +import ( + "context" + "os" + "unsafe" + + "golang.org/x/net/bpf" + "golang.org/x/sys/unix" +) + +// IoctlKCMClone wraps ioctl(2) for unix.KCMClone values, but returns a Conn +// rather than a raw file descriptor. +func (c *Conn) IoctlKCMClone() (*Conn, error) { + info, err := controlT(c, context.Background(), "ioctl", unix.IoctlKCMClone) + if err != nil { + return nil, err + } + + // Successful clone, wrap in a Conn for use by the caller. + return New(int(info.Fd), c.name) +} + +// IoctlKCMAttach wraps ioctl(2) for unix.KCMAttach values. +func (c *Conn) IoctlKCMAttach(info unix.KCMAttach) error { + return c.control(context.Background(), "ioctl", func(fd int) error { + return unix.IoctlKCMAttach(fd, info) + }) +} + +// IoctlKCMUnattach wraps ioctl(2) for unix.KCMUnattach values. +func (c *Conn) IoctlKCMUnattach(info unix.KCMUnattach) error { + return c.control(context.Background(), "ioctl", func(fd int) error { + return unix.IoctlKCMUnattach(fd, info) + }) +} + +// PidfdGetfd wraps pidfd_getfd(2) for a Conn which wraps a pidfd, but returns a +// Conn rather than a raw file descriptor. +func (c *Conn) PidfdGetfd(targetFD, flags int) (*Conn, error) { + outFD, err := controlT(c, context.Background(), "pidfd_getfd", func(fd int) (int, error) { + return unix.PidfdGetfd(fd, targetFD, flags) + }) + if err != nil { + return nil, err + } + + // Successful getfd, wrap in a Conn for use by the caller. + return New(outFD, c.name) +} + +// PidfdSendSignal wraps pidfd_send_signal(2) for a Conn which wraps a Linux +// pidfd. +func (c *Conn) PidfdSendSignal(sig unix.Signal, info *unix.Siginfo, flags int) error { + return c.control(context.Background(), "pidfd_send_signal", func(fd int) error { + return unix.PidfdSendSignal(fd, sig, info, flags) + }) +} + +// SetBPF attaches an assembled BPF program to a Conn. +func (c *Conn) SetBPF(filter []bpf.RawInstruction) error { + // We can't point to the first instruction in the array if no instructions + // are present. + if len(filter) == 0 { + return os.NewSyscallError("setsockopt", unix.EINVAL) + } + + prog := unix.SockFprog{ + Len: uint16(len(filter)), + Filter: (*unix.SockFilter)(unsafe.Pointer(&filter[0])), + } + + return c.SetsockoptSockFprog(unix.SOL_SOCKET, unix.SO_ATTACH_FILTER, &prog) +} + +// RemoveBPF removes a BPF filter from a Conn. +func (c *Conn) RemoveBPF() error { + // 0 argument is ignored. + return c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_DETACH_FILTER, 0) +} + +// SetsockoptPacketMreq wraps setsockopt(2) for unix.PacketMreq values. +func (c *Conn) SetsockoptPacketMreq(level, opt int, mreq *unix.PacketMreq) error { + return c.control(context.Background(), "setsockopt", func(fd int) error { + return unix.SetsockoptPacketMreq(fd, level, opt, mreq) + }) +} + +// SetsockoptSockFprog wraps setsockopt(2) for unix.SockFprog values. +func (c *Conn) SetsockoptSockFprog(level, opt int, fprog *unix.SockFprog) error { + return c.control(context.Background(), "setsockopt", func(fd int) error { + return unix.SetsockoptSockFprog(fd, level, opt, fprog) + }) +} + +// GetsockoptTpacketStats wraps getsockopt(2) for unix.TpacketStats values. +func (c *Conn) GetsockoptTpacketStats(level, name int) (*unix.TpacketStats, error) { + return controlT(c, context.Background(), "getsockopt", func(fd int) (*unix.TpacketStats, error) { + return unix.GetsockoptTpacketStats(fd, level, name) + }) +} + +// GetsockoptTpacketStatsV3 wraps getsockopt(2) for unix.TpacketStatsV3 values. +func (c *Conn) GetsockoptTpacketStatsV3(level, name int) (*unix.TpacketStatsV3, error) { + return controlT(c, context.Background(), "getsockopt", func(fd int) (*unix.TpacketStatsV3, error) { + return unix.GetsockoptTpacketStatsV3(fd, level, name) + }) +} + +// Waitid wraps waitid(2). +func (c *Conn) Waitid(idType int, info *unix.Siginfo, options int, rusage *unix.Rusage) error { + return c.read(context.Background(), "waitid", func(fd int) error { + return unix.Waitid(idType, fd, info, options, rusage) + }) +} diff --git a/vendor/github.com/mdlayher/socket/doc.go b/vendor/github.com/mdlayher/socket/doc.go new file mode 100644 index 0000000..7d4566c --- /dev/null +++ b/vendor/github.com/mdlayher/socket/doc.go @@ -0,0 +1,13 @@ +// Package socket provides a low-level network connection type which integrates +// with Go's runtime network poller to provide asynchronous I/O and deadline +// support. +// +// This package focuses on UNIX-like operating systems which make use of BSD +// sockets system call APIs. It is meant to be used as a foundation for the +// creation of operating system-specific socket packages, for socket families +// such as Linux's AF_NETLINK, AF_PACKET, or AF_VSOCK. This package should not +// be used directly in end user applications. +// +// Any use of package socket should be guarded by build tags, as one would also +// use when importing the syscall or golang.org/x/sys packages. +package socket diff --git a/vendor/github.com/mdlayher/socket/netns_linux.go b/vendor/github.com/mdlayher/socket/netns_linux.go new file mode 100644 index 0000000..b29115a --- /dev/null +++ b/vendor/github.com/mdlayher/socket/netns_linux.go @@ -0,0 +1,150 @@ +//go:build linux +// +build linux + +package socket + +import ( + "errors" + "fmt" + "os" + "runtime" + + "golang.org/x/sync/errgroup" + "golang.org/x/sys/unix" +) + +// errNetNSDisabled is returned when network namespaces are unavailable on +// a given system. +var errNetNSDisabled = errors.New("socket: Linux network namespaces are not enabled on this system") + +// withNetNS invokes fn within the context of the network namespace specified by +// fd, while also managing the logic required to safely do so by manipulating +// thread-local state. +func withNetNS(fd int, fn func() (*Conn, error)) (*Conn, error) { + var ( + eg errgroup.Group + conn *Conn + ) + + eg.Go(func() error { + // Retrieve and store the calling OS thread's network namespace so the + // thread can be reassigned to it after creating a socket in another network + // namespace. + runtime.LockOSThread() + + ns, err := threadNetNS() + if err != nil { + // No thread-local manipulation, unlock. + runtime.UnlockOSThread() + return err + } + defer ns.Close() + + // Beyond this point, the thread's network namespace is poisoned. Do not + // unlock the OS thread until all network namespace manipulation completes + // to avoid returning to the caller with altered thread-local state. + + // Assign the current OS thread the goroutine is locked to to the given + // network namespace. + if err := ns.Set(fd); err != nil { + return err + } + + // Attempt Conn creation and unconditionally restore the original namespace. + c, err := fn() + if nerr := ns.Restore(); nerr != nil { + // Failed to restore original namespace. Return an error and allow the + // runtime to terminate the thread. + if err == nil { + _ = c.Close() + } + + return nerr + } + + // No more thread-local state manipulation; return the new Conn. + runtime.UnlockOSThread() + conn = c + return nil + }) + + if err := eg.Wait(); err != nil { + return nil, err + } + + return conn, nil +} + +// A netNS is a handle that can manipulate network namespaces. +// +// Operations performed on a netNS must use runtime.LockOSThread before +// manipulating any network namespaces. +type netNS struct { + // The handle to a network namespace. + f *os.File + + // Indicates if network namespaces are disabled on this system, and thus + // operations should become a no-op or return errors. + disabled bool +} + +// threadNetNS constructs a netNS using the network namespace of the calling +// thread. If the namespace is not the default namespace, runtime.LockOSThread +// should be invoked first. +func threadNetNS() (*netNS, error) { + return fileNetNS(fmt.Sprintf("/proc/self/task/%d/ns/net", unix.Gettid())) +} + +// fileNetNS opens file and creates a netNS. fileNetNS should only be called +// directly in tests. +func fileNetNS(file string) (*netNS, error) { + f, err := os.Open(file) + switch { + case err == nil: + return &netNS{f: f}, nil + case os.IsNotExist(err): + // Network namespaces are not enabled on this system. Use this signal + // to return errors elsewhere if the caller explicitly asks for a + // network namespace to be set. + return &netNS{disabled: true}, nil + default: + return nil, err + } +} + +// Close releases the handle to a network namespace. +func (n *netNS) Close() error { + return n.do(func() error { return n.f.Close() }) +} + +// FD returns a file descriptor which represents the network namespace. +func (n *netNS) FD() int { + if n.disabled { + // No reasonable file descriptor value in this case, so specify a + // non-existent one. + return -1 + } + + return int(n.f.Fd()) +} + +// Restore restores the original network namespace for the calling thread. +func (n *netNS) Restore() error { + return n.do(func() error { return n.Set(n.FD()) }) +} + +// Set sets a new network namespace for the current thread using fd. +func (n *netNS) Set(fd int) error { + return n.do(func() error { + return os.NewSyscallError("setns", unix.Setns(fd, unix.CLONE_NEWNET)) + }) +} + +// do runs fn if network namespaces are enabled on this system. +func (n *netNS) do(fn func() error) error { + if n.disabled { + return errNetNSDisabled + } + + return fn() +} diff --git a/vendor/github.com/mdlayher/socket/netns_others.go b/vendor/github.com/mdlayher/socket/netns_others.go new file mode 100644 index 0000000..4cceb3d --- /dev/null +++ b/vendor/github.com/mdlayher/socket/netns_others.go @@ -0,0 +1,14 @@ +//go:build !linux +// +build !linux + +package socket + +import ( + "fmt" + "runtime" +) + +// withNetNS returns an error on non-Linux systems. +func withNetNS(_ int, _ func() (*Conn, error)) (*Conn, error) { + return nil, fmt.Errorf("socket: Linux network namespace support is not available on %s", runtime.GOOS) +} diff --git a/vendor/github.com/mdlayher/socket/setbuffer_linux.go b/vendor/github.com/mdlayher/socket/setbuffer_linux.go new file mode 100644 index 0000000..0d4aa44 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/setbuffer_linux.go @@ -0,0 +1,24 @@ +//go:build linux +// +build linux + +package socket + +import "golang.org/x/sys/unix" + +// setReadBuffer wraps the SO_RCVBUF{,FORCE} setsockopt(2) options. +func (c *Conn) setReadBuffer(bytes int) error { + err := c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, bytes) + if err != nil { + err = c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_RCVBUF, bytes) + } + return err +} + +// setWriteBuffer wraps the SO_SNDBUF{,FORCE} setsockopt(2) options. +func (c *Conn) setWriteBuffer(bytes int) error { + err := c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, bytes) + if err != nil { + err = c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_SNDBUF, bytes) + } + return err +} diff --git a/vendor/github.com/mdlayher/socket/setbuffer_others.go b/vendor/github.com/mdlayher/socket/setbuffer_others.go new file mode 100644 index 0000000..72b36db --- /dev/null +++ b/vendor/github.com/mdlayher/socket/setbuffer_others.go @@ -0,0 +1,16 @@ +//go:build !linux +// +build !linux + +package socket + +import "golang.org/x/sys/unix" + +// setReadBuffer wraps the SO_RCVBUF setsockopt(2) option. +func (c *Conn) setReadBuffer(bytes int) error { + return c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_RCVBUF, bytes) +} + +// setWriteBuffer wraps the SO_SNDBUF setsockopt(2) option. +func (c *Conn) setWriteBuffer(bytes int) error { + return c.SetsockoptInt(unix.SOL_SOCKET, unix.SO_SNDBUF, bytes) +} diff --git a/vendor/github.com/mdlayher/socket/typ_cloexec_nonblock.go b/vendor/github.com/mdlayher/socket/typ_cloexec_nonblock.go new file mode 100644 index 0000000..40e8343 --- /dev/null +++ b/vendor/github.com/mdlayher/socket/typ_cloexec_nonblock.go @@ -0,0 +1,12 @@ +//go:build !darwin +// +build !darwin + +package socket + +import "golang.org/x/sys/unix" + +const ( + // These operating systems support CLOEXEC and NONBLOCK socket options. + flagCLOEXEC = true + socketFlags = unix.SOCK_CLOEXEC | unix.SOCK_NONBLOCK +) diff --git a/vendor/github.com/mdlayher/socket/typ_none.go b/vendor/github.com/mdlayher/socket/typ_none.go new file mode 100644 index 0000000..9bbb1aa --- /dev/null +++ b/vendor/github.com/mdlayher/socket/typ_none.go @@ -0,0 +1,11 @@ +//go:build darwin +// +build darwin + +package socket + +const ( + // These operating systems do not support CLOEXEC and NONBLOCK socket + // options. + flagCLOEXEC = false + socketFlags = 0 +) diff --git a/vendor/modules.txt b/vendor/modules.txt index 453ca27..0f66fba 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,27 @@ # github.com/fsnotify/fsnotify v1.7.0 ## explicit; go 1.17 github.com/fsnotify/fsnotify +# github.com/google/go-cmp v0.6.0 +## explicit; go 1.13 +github.com/google/go-cmp/cmp +github.com/google/go-cmp/cmp/internal/diff +github.com/google/go-cmp/cmp/internal/flags +github.com/google/go-cmp/cmp/internal/function +github.com/google/go-cmp/cmp/internal/value +# github.com/josharian/native v1.1.0 +## explicit; go 1.13 +github.com/josharian/native +# github.com/jsimonetti/rtnetlink/v2 v2.0.2 +## explicit; go 1.20 +github.com/jsimonetti/rtnetlink/v2 +github.com/jsimonetti/rtnetlink/v2/internal/unix +# github.com/mdlayher/netlink v1.7.2 +## explicit; go 1.18 +github.com/mdlayher/netlink +github.com/mdlayher/netlink/nlenc +# github.com/mdlayher/socket v0.4.1 +## explicit; go 1.20 +github.com/mdlayher/socket # github.com/opencontainers/selinux v1.11.0 ## explicit; go 1.19 github.com/opencontainers/selinux/go-selinux