Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion docs/netlink/gotc-status.md

Large diffs are not rendered by default.

225 changes: 225 additions & 0 deletions docs/netlink/upstream/iproute2-tc-monitor.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions internal/goip/imports_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ var goipMayImport = map[string]string{
"pkg/nlparity as the answer. The plan's import set listed only xtcpnl; this is the one addition, and it " +
"satisfies the same §16 property.",
modulePath + "/internal/jsonw": "jsonw_puts, the one string escaper json_writer.c's ports share with gordma; stdlib only",
modulePath + "/internal/nlmon": "rtnl_listen, rtnl_from_file and the capture's notification split, shared with gotc's tc monitor; xtcpnl and x/sys only",
modulePath + "/internal/tnlsys": "the tunnel and tuntap sidecar (8S): the SIOCGET* ioctls, the tun sysfs props and " +
"the /dev/net/tun /proc walk, live or from a tnlsnap snapshot. It imports only pkg/cint and x/sys/unix.",
"github.com/cilium/ebpf": "`encap bpf` and seg6local `endpoint` load an object's program as ip's libbpf does " +
Expand Down Expand Up @@ -175,6 +176,7 @@ func TestGoipImportSetIsHermetic(t *testing.T) {
modulePath + "/pkg/cint": "the C int conversions; stdlib only",
modulePath + "/pkg/strpolicy": "reached through pkg/xtcpnl's congestion-name decoder; stdlib only",
modulePath + "/internal/jsonw": "jsonw_puts, shared with gordma; stdlib only",
modulePath + "/internal/nlmon": "the monitor core, shared with gotc; xtcpnl and x/sys only",
modulePath + "/internal/tnlsys": "the tunnel and tuntap sidecar; pkg/cint and x/sys/unix only",
modulePath + "/gen/go/xtcp_flat_record": "reached through pkg/xtcpnl's inet_diag decoders, which " +
"write into the generated proto. This is where grpc and protobuf enter the closure.",
Expand Down
62 changes: 14 additions & 48 deletions internal/goip/obj_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"

"github.com/randomizedcoder/xtcp2/internal/goip/model"
"github.com/randomizedcoder/xtcp2/internal/goip/render"
"github.com/randomizedcoder/xtcp2/internal/goip/service"
"github.com/randomizedcoder/xtcp2/internal/nlmon"
"github.com/randomizedcoder/xtcp2/pkg/xtcpnl"
"golang.org/x/sys/unix"
)
Expand Down Expand Up @@ -67,8 +67,6 @@ const (
monitorDeletedCst = "Deleted "
monitorAllNsidCst = "all-nsid"
monitorHelpCst = "help"
// monitorBufCst is rtnl_from_file's buffer, the longest message it reads.
monitorBufCst = 16384
// nlmsgTstampCst is NLMSG_TSTAMP (include/libnetlink.h), the record
// rtmon writes ahead of each batch in its file.
nlmsgTstampCst = 15
Expand Down Expand Up @@ -464,17 +462,8 @@ func (m *monitor) headers(label string, nsid int32) string {
// asctimeLayoutCst is asctime's "%.3s %.3s%3d %.2d:%.2d:%.2d %d".
const asctimeLayoutCst = "Mon Jan _2 15:04:05 2006"

// timestampText is print_timestamp: asctime of the local time and the
// microseconds on a line of their own, or under -ts the ISO form in
// brackets ahead of the label.
func timestampText(t time.Time, short bool) string {
t = t.Local()
usec := t.Nanosecond() / 1000
if short {
return fmt.Sprintf("[%s.%06d] ", t.Format("2006-01-02T15:04:05"), usec)
}
return fmt.Sprintf("Timestamp: %s %d usec\n", t.Format(asctimeLayoutCst), usec)
}
// timestampText is print_timestamp (nlmon.Timestamp).
func timestampText(t time.Time, short bool) string { return nlmon.Timestamp(t, short) }

// tstampText is print_nlmsg_timestamp, an NLMSG_TSTAMP record's seconds and
// microseconds, two u32s. `ip` reads them whatever the length; a short body
Expand Down Expand Up @@ -713,40 +702,17 @@ func (m *monitor) fromFile(path string) error {
return monitorReadFile(path, m.accept)
}

// monitorReadFile is rtnl_from_file over path, each message handed to fn,
// as fromFile describes; `ip xfrm monitor file` walks it the same way.
// monitorReadFile is nlmon.ReadFile with goip's sentinels: a file it
// cannot open is ErrMonitorAbort, any other failure ErrMonitorFile.
func monitorReadFile(path string, fn func(monitorMsg) error) error {
data, err := os.ReadFile(path)
if err != nil {
var errno unix.Errno
if errors.As(err, &errno) {
return fmt.Errorf("%w: Cannot fopen: %s", ErrMonitorAbort, errno.Error())
}
return fmt.Errorf("%w: Cannot fopen: %w", ErrMonitorAbort, err)
}
off := 0
for off < len(data) {
if len(data)-off < xtcpnl.NlMsgHdrSizeCst {
return fmt.Errorf("%w: rtnl-from_file: truncated message", ErrMonitorFile)
}
var h xtcpnl.NlMsgHdr
if _, err := xtcpnl.DeserializeNlMsgHdr(data[off:], &h); err != nil {
return fmt.Errorf("%w: %w", ErrMonitorFile, err)
}
if h.Len < xtcpnl.NlMsgHdrSizeCst || h.Len > monitorBufCst {
return fmt.Errorf("%w: !!!malformed message: len=%d @%d", ErrMonitorFile,
int32(h.Len), off+xtcpnl.NlMsgHdrSizeCst)
}
l := int(h.Len) - xtcpnl.NlMsgHdrSizeCst
end := off + xtcpnl.NlMsgHdrSizeCst + nlmsgAlign(l)
if end > len(data) {
return fmt.Errorf("%w: rtnl-from_file: truncated message", ErrMonitorFile)
}
body := data[off+xtcpnl.NlMsgHdrSizeCst : off+xtcpnl.NlMsgHdrSizeCst+l]
if err := fn(monitorMsg{hdr: h, body: body, nsid: -1}); err != nil {
return fmt.Errorf("%w: %w", ErrMonitorFile, err)
}
off = end
err := nlmon.ReadFile(path, func(m nlmon.Msg) error {
return fn(monitorMsg{hdr: m.Hdr, body: m.Body, nsid: m.Nsid})
})
switch {
case err == nil:
return nil
case errors.Is(err, nlmon.ErrOpen):
return fmt.Errorf("%w: %w", ErrMonitorAbort, err)
}
return nil
return fmt.Errorf("%w: %w", ErrMonitorFile, err)
}
2 changes: 1 addition & 1 deletion internal/goip/obj_monitor_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestRunMonitorFile(t *testing.T) {
{"negative: an unknown argument exits 255", "monitor bogus",
result{rc: ExitMinusOne, stderr: "goip: monitor: Argument \"bogus\" is unknown, try \"ip monitor help\"\n"}},
{"negative: no such file exits 255", "monitor file " + file + ".none",
result{rc: ExitMinusOne, stderr: "goip: monitor: Cannot fopen: no such file or directory\n"}},
result{rc: ExitMinusOne, stderr: "goip: monitor: Cannot fopen: No such file or directory\n"}},
{"corner: -j still prints text", "-j monitor file " + file, result{stdout: addr}},
{"negative: a truncated file exits 1, rtnl_from_file's -1 negated", "monitor file " + short16,
result{rc: ExitUsage, stderr: "goip: monitor file: rtnl-from_file: truncated message\n"}},
Expand Down
172 changes: 3 additions & 169 deletions internal/goip/obj_monitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@ package goip

import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/randomizedcoder/xtcp2/pkg/nlparity"
"github.com/randomizedcoder/xtcp2/internal/nlmon"
"github.com/randomizedcoder/xtcp2/pkg/xtcpnl"
"golang.org/x/sys/unix"
)
Expand Down Expand Up @@ -511,13 +509,13 @@ func TestMonitorFromFile(t *testing.T) {
result{errText: "rtnl-from_file: truncated message", exit: ExitUsage}},
{"negative: a length under the header's", monFileRecord(unix.RTM_NEWADDR, nil, 8),
result{errText: "!!!malformed message: len=8 @16", exit: ExitUsage}},
{"boundary: a length over the 16384-byte buffer", monFileRecord(unix.RTM_NEWADDR, nil, monitorBufCst+1),
{"boundary: a length over the 16384-byte buffer", monFileRecord(unix.RTM_NEWADDR, nil, nlmon.RecvBufCst+1),
result{errText: "!!!malformed message: len=16385 @16", exit: ExitUsage}},
{"corner: a short route stops the walk with -1", catBytes(
monFileRecord(unix.RTM_NEWROUTE, make([]byte, 4), 20), rec(addr)),
result{errText: errMonitorStop.Error(), exit: ExitUsage}},
{"negative: no such file is fopen's exit(-1)", nil,
result{errText: "Cannot fopen: no such file or directory", exit: ExitMinusOne}},
result{errText: "Cannot fopen: No such file or directory", exit: ExitMinusOne}},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
Expand All @@ -543,167 +541,3 @@ func TestMonitorFromFile(t *testing.T) {
})
}
}

// TestMonitorDatagram is rtnl_listen's walk of one datagram: each message
// to the callback with the datagram's nsid, and the malformed and remnant
// refusals.
//
// go test ./internal/goip/ -run TestMonitorDatagram
func TestMonitorDatagram(t *testing.T) {
msg := func(typ uint16, body []byte) []byte {
return monFileRecord(typ, body, uint32(xtcpnl.NlMsgHdrSizeCst+len(body)))
}
type result struct {
types string
errText string
}
tests := []struct {
description string
datagram []byte
expected result
}{
{"positive: two messages", catBytes(msg(unix.RTM_NEWLINK, le32(1)), msg(unix.RTM_NEWADDR, nil)),
result{types: "16/5 20/5 "}},
{"boundary: an empty datagram", nil, result{}},
{"positive: the last body unpadded", msg(unix.RTM_NEWLINK, []byte{1})[:17], result{types: "16/5 "}},
{"negative: a length past the datagram", monFileRecord(unix.RTM_NEWLINK, nil, 64),
result{errText: "!!!malformed message: len=64"}},
{"negative: a length under the header's", monFileRecord(unix.RTM_NEWLINK, nil, 4),
result{errText: "!!!malformed message: len=4"}},
{"corner: a remnant under a header", catBytes(msg(unix.RTM_NEWLINK, nil), []byte{1, 2, 3, 4}),
result{types: "16/5 ", errText: "!!!Remnant of size 4"}},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
var types strings.Builder
err := monitorDatagram(tc.datagram, 5, func(m monitorMsg) error {
fmt.Fprintf(&types, "%d/%d ", m.hdr.Type, m.nsid)
return nil
})
got := result{types: types.String()}
if err != nil {
got.errText = err.Error()
}
if got != tc.expected {
t.Errorf("got %+v, want %+v", got, tc.expected)
}
})
}
}

// TestListenNsid is the nsid a NETLINK_LISTEN_ALL_NSID control message
// carries.
//
// go test ./internal/goip/ -run TestListenNsid
func TestListenNsid(t *testing.T) {
// cmsg is a cmsghdr on a 64-bit host, its length a size_t, then data
// padded to 8 bytes.
cmsg := func(level, typ int32, data []byte) []byte {
b := catBytes(binary.LittleEndian.AppendUint64(nil, uint64(unix.CmsgLen(len(data)))),
le32(uint32(level)), le32(uint32(typ)), data)
return append(b, make([]byte, unix.CmsgSpace(len(data))-len(b))...)
}
tests := []struct {
description string
oob []byte
expected int32
}{
{"positive: nsid 9", cmsg(unix.SOL_NETLINK, unix.NETLINK_LISTEN_ALL_NSID, le32(9)), 9},
{"boundary: none is -1", nil, -1},
{"negative: another level is -1", cmsg(unix.SOL_SOCKET, unix.NETLINK_LISTEN_ALL_NSID, le32(9)), -1},
{"negative: a short value is -1", cmsg(unix.SOL_NETLINK, unix.NETLINK_LISTEN_ALL_NSID, []byte{9}), -1},
{"corner: the last of two", catBytes(cmsg(unix.SOL_NETLINK, unix.NETLINK_LISTEN_ALL_NSID, le32(9)),
cmsg(unix.SOL_NETLINK, unix.NETLINK_LISTEN_ALL_NSID, le32(2))), 2},
{"negative: garbage is -1", []byte{1, 2, 3}, -1},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
if got := listenNsid(tc.oob); got != tc.expected {
t.Errorf("got %d, want %d", got, tc.expected)
}
})
}
}

// TestReplayNotifications is which of a capture's messages a subscriber
// was sent: requests, dump parts, errors and a get's answer left out.
//
// go test ./internal/goip/ -run TestReplayNotifications
func TestReplayNotifications(t *testing.T) {
m := func(typ, flags uint16, seq, pid uint32, body ...byte) nlparity.Msg {
return nlparity.Msg{Hdr: xtcpnl.NlMsgHdr{Type: typ, Flags: flags, Seq: seq, Pid: pid}, Body: body}
}
errFor := func(typ uint16, seq uint32) nlparity.Msg {
return m(unix.NLMSG_ERROR, 0, seq, 100, catBytes(le32(0), monHdr(typ, seq, xtcpnl.NlMsgHdrSizeCst))...)
}
const (
req = unix.NLM_F_REQUEST
dump = unix.NLM_F_REQUEST | unix.NLM_F_DUMP
)
tests := []struct {
description string
msgs []nlparity.Msg
expected []int
}{
{"positive: notifications alone", []nlparity.Msg{m(unix.RTM_NEWADDR, 0, 0, 0), m(unix.RTM_DELADDR, 0, 0, 0)},
[]int{0, 1}},
{"negative: a dump and its parts", []nlparity.Msg{m(unix.RTM_GETLINK, dump, 1, 0),
m(unix.RTM_NEWLINK, unix.NLM_F_MULTI, 1, 100), m(unix.NLMSG_DONE, unix.NLM_F_MULTI, 1, 100),
m(unix.RTM_NEWLINK, 0, 0, 0)}, []int{3}},
{"positive: a nexthop event carries REQUEST and the requester's port", []nlparity.Msg{
m(unix.RTM_NEWNEXTHOP, req|unix.NLM_F_CREATE, 5, 0), errFor(unix.RTM_NEWNEXTHOP, 5),
m(unix.RTM_NEWNEXTHOP, req|unix.NLM_F_CREATE, 5, 4242)}, []int{2}},
{"negative: a get's answer", []nlparity.Msg{m(unix.RTM_GETNSID, req, 7, 0), m(unix.RTM_NEWNSID, 0, 7, 100),
m(unix.RTM_NEWNSID, 0, 0, 0)}, []int{2}},
{"corner: a get's answer is the first of its type and seq alone", []nlparity.Msg{
m(unix.RTM_GETNSID, req, 7, 0), m(unix.RTM_NEWADDR, 0, 7, 0), m(unix.RTM_NEWNSID, 0, 7, 100),
m(unix.RTM_NEWNSID, 0, 7, 100)}, []int{1, 3}},
{"corner: a refused get waits for no answer", []nlparity.Msg{m(unix.RTM_GETNSID, req, 7, 0),
errFor(unix.RTM_GETNSID, 7), m(unix.RTM_NEWNSID, 0, 7, 0)}, []int{2}},
{"boundary: a short error names nothing", []nlparity.Msg{m(unix.RTM_GETNSID, req, 7, 0),
m(unix.NLMSG_ERROR, 0, 7, 0, 0, 0, 0, 0), m(unix.RTM_NEWNSID, 0, 7, 0)}, nil},
{"boundary: none", nil, nil},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
got := replayNotifications(tc.msgs)
if fmt.Sprint(got) != fmt.Sprint(tc.expected) {
t.Errorf("got %v, want %v", got, tc.expected)
}
})
}
}

// TestReplayDumpEnd is the index past a recorded dump's NLMSG_DONE, where a
// replayed monitor's notifications begin.
//
// go test ./internal/goip/ -run TestReplayDumpEnd
func TestReplayDumpEnd(t *testing.T) {
m := func(typ, flags uint16, seq, pid uint32) nlparity.Msg {
return nlparity.Msg{Hdr: xtcpnl.NlMsgHdr{Type: typ, Flags: flags, Seq: seq, Pid: pid}}
}
dump := uint16(unix.NLM_F_REQUEST | unix.NLM_F_DUMP)
tests := []struct {
description string
msgs []nlparity.Msg
expected int
}{
{"positive: past the DONE", []nlparity.Msg{m(unix.RTM_NEWADDR, 0, 0, 0), m(unix.RTM_GETLINK, dump, 3, 0),
m(unix.RTM_NEWADDR, 0, 0, 0), m(unix.NLMSG_DONE, 2, 3, 100), m(unix.RTM_NEWADDR, 0, 0, 0)}, 4},
{"negative: no dump is 0", []nlparity.Msg{m(unix.RTM_NEWADDR, 0, 0, 0)}, 0},
{"negative: a dump with no DONE is 0", []nlparity.Msg{m(unix.RTM_GETLINK, dump, 3, 0)}, 0},
{"corner: a DONE of another seq is not the dump's", []nlparity.Msg{m(unix.RTM_GETLINK, dump, 3, 0),
m(unix.NLMSG_DONE, 2, 2, 100), m(unix.NLMSG_DONE, 2, 3, 100)}, 3},
{"corner: a get of the type is not a dump", []nlparity.Msg{m(unix.RTM_GETLINK, unix.NLM_F_REQUEST, 3, 0),
m(unix.NLMSG_DONE, 2, 3, 100)}, 0},
{"boundary: a reply from the kernel is not the request", []nlparity.Msg{m(unix.RTM_GETLINK, dump, 3, 100),
m(unix.NLMSG_DONE, 2, 3, 100)}, 0},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
if got := replayDumpEnd(tc.msgs, unix.RTM_GETLINK); got != tc.expected {
t.Errorf("got %d, want %d", got, tc.expected)
}
})
}
}
8 changes: 2 additions & 6 deletions internal/goip/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strconv"
"time"

"github.com/randomizedcoder/xtcp2/internal/nlmon"
"github.com/randomizedcoder/xtcp2/pkg/nlparity"
"github.com/randomizedcoder/xtcp2/pkg/xtcpnl"
"golang.org/x/sys/unix"
Expand Down Expand Up @@ -517,9 +518,4 @@ func nowFromEnv() time.Time {

// nowFuncFromEnv is the clock a monitor stamps each message with: GOIP_NOW's
// instant when it parses, for a replay, else the wall clock, read per message.
func nowFuncFromEnv() func() time.Time {
if t, err := time.Parse(time.RFC3339, os.Getenv("GOIP_NOW")); err == nil {
return func() time.Time { return t }
}
return time.Now
}
func nowFuncFromEnv() func() time.Time { return nlmon.NowFunc("GOIP_NOW") }
Loading