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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
30 changes: 30 additions & 0 deletions docs/netlink/gotc-status.md

Large diffs are not rendered by default.

328 changes: 328 additions & 0 deletions docs/netlink/upstream/iproute2-tc-ematch-write.md

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion docs/netlink/upstream/iproute2-tc-filter-write.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
`chain del` go through too), the parse_fopt of u32, fw, route, flow and matchall (`tc/f_*.c`), the filter side of
the actions (`tc/m_action.c` parse_action, `tc/m_gact.c` parse_gact, `tc/tc_util.c` action_a2n and
parse_action_control), and the shared helpers they reach (`lib/utils.c`, `lib/rt_names.c`, `lib/ll_map.c`,
`tc/m_estimator.c`). basic, cgroup and the ematch grammar are increment 21's. Leads continue
`tc/m_estimator.c`). basic, cgroup and the ematch grammar are increment 21's: W123–W155 and K56–K62 are in
[iproute2-tc-ematch-write.md](iproute2-tc-ematch-write.md). Leads continue
[iproute2-tc-write.md](iproute2-tc-write.md)'s numbering at **W64**, so every tc write lead has one number; kernel
notes continue at **K49**.
- **Source:**
Expand Down Expand Up @@ -193,6 +194,8 @@
- **W95.** None of the five parsers checks for a repeated keyword. Each repeated classid, link, divisor, indev, mark,
to, from, keys or rshift adds another attribute, and the kernel's nla_parse keeps the last: `classid 1:1 classid
1:2` installs 1:2 (ec-097). u32's `ht`, `order` and flags take the last value locally.
- **Increment 21:** basic and cgroup don't check either. A second classid or `match` wins (tcematch ec-136), and
with both police and action the kernel keeps the police alone (K59, ec-139) ([iproute2-tc-ematch-write.md](iproute2-tc-ematch-write.md)).

## W96–W109. fw, route, matchall and flow

Expand All @@ -202,6 +205,8 @@
- **W97.** fw, route and flow pass 4096 as addattr's maxlen while the request buffer is MAX_MSG (16384). Past 4096
bytes (a long action list), addattr_l prints `addattr_l ERROR: message exceeded bound of 4096`, the callers ignore
the -1 and the request goes out without that attribute. gotc refuses a request tc would truncate (W6's rule).
- **Increment 21:** a large flow `match` hits the same bound: tcematch ec-137's two 300-rule canids send a 4900-byte
request without MODE, DIVISOR and BASECLASS, and its readback ends in EMSGSIZE (K62, [iproute2-tc-ematch-write.md](iproute2-tc-ematch-write.md)).
- **W98.** route's `order` is shifted and masked into the handle's 0x7F00 without a check: `order 200` is 72 in the
handle, 0xffff4804 (ec-098).
- **W99, W100.** route's explain says `fromif TAG` (a device name) and omits order, police and flowid (ng-023).
Expand Down
6 changes: 6 additions & 0 deletions docs/netlink/upstream/iproute2-tc-filter.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ Under `-p` (pretty), `show_keys` picks a printer by `f_proto`, the last filter's
ahead by parser"). When the ematch is the last word on the line, the parser had nothing to look ahead at, so the
undo backs up onto the ematch itself. `basic_parse_opt` then reads it again: `What is "cmp(...)"?`. The 10C
fixtures put a `classid` or an `action` after every `match` for this reason.
- **Increment 21:** the same undo gives `What is "<tree>"?` for cgroup and flow as well (tcematch ng-019–ng-021).
Its siblings, W127 (the undo lands on `match` and loops) and W146 (the look-ahead takes flow's `and`), are in
[iproute2-tc-ematch-write.md](iproute2-tc-ematch-write.md).

## K1–K4. Kernel notes

Expand All @@ -222,6 +225,9 @@ Under `-p` (pretty), `show_keys` picks a printer by `f_proto`, the last filter's
sequence number.
- **K2:** `cls_cgroup_get` returns NULL, so `tc filter get ... cgroup` is always "Specified filter handle not found",
rc 2. The filter can be listed but never got.
- **Increment 21:** a cgroup is one filter per prio and protocol. Its change is `Need both RTM_NEWTFILTER and
NLM_F_CREATE`, delete-by-handle is `Specified filter handle not found`, a second handle is ENOENT and no handle
is EINVAL (tcematch ng-103–ng-106; [iproute2-tc-ematch-write.md](iproute2-tc-ematch-write.md)).
- **K3:** `tcf_fill_node` returns -EOPNOTSUPP (`cls_op_not_supp`) for a terse dump of a kind without
`terse_dump`. What reaches user space at the end of the dump is EMSGSIZE.
- **K4:** `meta_int_change` stores 8 bytes when the attribute has at least `sizeof(unsigned long)`, and
Expand Down
22 changes: 19 additions & 3 deletions internal/gotc/corpus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,26 @@ var corpusRefused = map[string]string{
"tcfwrite/ec-111": "not implemented: tc filter fw police",
"tcfwrite/ec-112": "not implemented: tc filter u32 police",
"tcfwrite/ec-113": "not implemented: tc filter action kind mirred",
"tcfwrite/ec-114": "not implemented: tc filter write of kind basic",
"tcfwrite/ec-115": "not implemented: tc filter write of kind cgroup",
"tcfwrite/ec-116": "not implemented: tc filter write of kind flower",
"tcfwrite/ec-117": "not implemented: tc filter write of kind bpf",
"tcfwrite/ec-118": "not implemented: tc filter flow match",
"tcfwrite/ng-033": "uninitialised tc_gact_p (W110)",
// 21W: where tc writes or reads memory it does not own, police and the
// two ematch kinds refused by name, and trees past their bound, which
// tc truncates and sends (W97, W151).
"tcematch/ec-104": "quoted run past strbuf (W123)",
"tcematch/ng-100": "quoted run past strbuf (W123)",
"tcematch/ng-101": "quoted run past strbuf (W123)",
"tcematch/ng-068": "meta mask walk past its NUL (W125)",
"tcematch/ng-016": "kind of 63 bytes or more (W126)",
"tcematch/ng-017": "kind of 63 bytes or more (W126)",
"tcematch/ec-138": "not implemented: tc filter basic police",
"tcematch/ec-139": "not implemented: tc filter basic police",
"tcematch/ec-140": "not implemented: tc filter cgroup police",
"tcematch/ng-108": "not implemented: tc filter write of ematch kind ipt",
"tcematch/ng-109": "not implemented: tc filter write of ematch kind ipset",
"tcematch/ng-110": "not implemented: tc filter write of ematch kind ipset",
"tcematch/ec-137": "addattr_l exceeded its bound of 4096",
"tcematch/ng-095": "addraw_l exceeded its bound of 16384",
}

// qwriteSent are the corpusWrites rows the gotc_write build sends and
Expand Down Expand Up @@ -259,6 +273,8 @@ func TestGotcCorpus(t *testing.T) {
corpusRows["tcawrite"] = 160
spaces = append(spaces, "tcfwrite")
corpusRows["tcfwrite"] = 183
spaces = append(spaces, "tcematch")
corpusRows["tcematch"] = 257
}
for _, sp := range spaces {
more, err := filepath.Glob("../../pkg/xtcpnl/testdata/*/ws/" + sp)
Expand Down
18 changes: 9 additions & 9 deletions internal/gotc/ematch.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ type emPrinter func(r *runner, data []byte) int

// ematchUtils are the ematches tc links (tc/Makefile) by kind name.
var ematchUtils = map[string]emPrinter{
"cmp": printEmCmp,
"nbyte": printEmNbyte,
wordU32: printEmU32,
"meta": printEmMeta,
"canid": printEmCanid,
emNameCmp: printEmCmp,
emNameNbyte: printEmNbyte,
wordU32: printEmU32,
emNameMeta: printEmMeta,
emNameCanid: printEmCanid,
}

// printEmatch is print_ematch. Its return is ignored by every filter
Expand Down Expand Up @@ -145,7 +145,7 @@ func (r *runner) ematchKind(kind uint16) (string, emPrinter, error) {
if err != nil {
return "", nil, nil
}
if name == "ipset" || name == "ipt" {
if name == emNameIpset || name == emNameIpt {
return "", nil, fmt.Errorf("%w: ematch %q", errNotImplemented, name)
}
return name, ematchUtils[name], nil
Expand Down Expand Up @@ -312,11 +312,11 @@ var metaNames = []struct {
id uint16
name string
}{
{0, "Generic"}, {1, "random"}, {2, "loadavg_1"}, {3, "loadavg_5"}, {4, "loadavg_15"},
{0, "Generic"}, {1, wordRandom}, {2, "loadavg_1"}, {3, "loadavg_5"}, {4, "loadavg_15"},
{0, "Interfaces"}, {5, "dev"}, {0, "Packet attributes"}, {6, wordPriority}, {7, wordProtocol},
{8, "pkt_type"}, {9, "pkt_len"}, {10, "data_len"}, {11, "mac_len"}, {0, "Netfilter"},
{12, "nf_mark"}, {12, "fwmark"}, {0, "Traffic Control"}, {13, "tc_index"}, {0, "Routing"},
{14, "rt_classid"}, {15, "rt_iif"}, {48, "vlan"}, {0, "Sockets"}, {16, "sk_family"},
{12, "nf_mark"}, {12, wordFwmark}, {0, "Traffic Control"}, {13, "tc_index"}, {0, "Routing"},
{14, "rt_classid"}, {15, "rt_iif"}, {46, "vlan"}, {0, "Sockets"}, {16, "sk_family"},
{17, "sk_state"}, {18, "sk_reuse"}, {19, "sk_bind_if"}, {20, "sk_refcnt"}, {21, "sk_shutdown"},
{22, "sk_proto"}, {23, "sk_type"}, {24, "sk_rcvbuf"}, {25, "sk_rmem"}, {26, "sk_wmem"},
{27, "sk_omem"}, {28, "sk_wmem_queue"}, {30, "sk_snd_queue"}, {29, "sk_rcv_queue"},
Expand Down
80 changes: 80 additions & 0 deletions internal/gotc/ematch_readback_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package gotc

import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)

// TestGotcEmatchReadbacks replays each tcematch row's readback (`tc -d
// filter show`, captured after the write) through gotc's read side and
// holds its stdout to tc's: every tree tc wrote and the kernel kept prints
// as tc prints it (21W).
//
// go test ./internal/gotc/ -run TestGotcEmatchReadbacks
func TestGotcEmatchReadbacks(t *testing.T) {
dirs, err := filepath.Glob("../../pkg/xtcpnl/testdata/*/ws/tcematch/*")
if err != nil {
t.Fatal(err)
}
if len(dirs) == 0 {
t.Fatal("no tcematch corpus")
}
pschedContent = readFile(t, pschedRow)
n := 0
for _, dir := range dirs {
dir, err := filepath.Abs(dir)
if err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(dir, "cmd.json"))
if err != nil {
t.Fatal(err)
}
var c struct {
ID string `json:"id"`
Readback []struct {
Cmd string `json:"cmd"`
Name string `json:"name"`
} `json:"readback"`
}
if err := json.Unmarshal(b, &c); err != nil {
t.Fatal(err)
}
if len(c.Readback) != 1 {
continue
}
pcap := filepath.Join(dir, "netlink_route_"+c.Readback[0].Name+".pcap")
if _, err := os.Stat(pcap); err != nil {
continue
}
n++
t.Run(c.ID, func(t *testing.T) {
src, err := NewReplaySource(pcap)
if err != nil {
t.Fatal(err)
}
args := shellWords(c.Readback[0].Cmd)[1:]
var out, errb bytes.Buffer
t.Chdir(dir)
rc := run(config{src: src, sys: testSys(t, dir)}, args, &out, &errb)
want := readFile(t, filepath.Join(dir, c.Readback[0].Name+".out"))
// stdout only: dump.out holds no stderr or rc. ec-137's dump
// ends in the kernel's "Buffer too small for object" (EMSGSIZE),
// rc 1, for tc and gotc alike.
if out.String() != want {
t.Fatalf("%s: rc %d stderr %q\n got %q\n want %q", c.Readback[0].Cmd, rc, errb.String(), out.String(), want)
}
if strings.Contains(errb.String(), "not implemented") {
t.Fatalf("refused: %s", errb.String())
}
})
}
if n == 0 {
t.Fatal("no readbacks")
}
t.Logf("replayed %d readbacks", n)
}
4 changes: 2 additions & 2 deletions internal/gotc/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func ematchTree(matches ...[]byte) []byte {
}

// shareSys is a root whose CONF_USR_DIR has the workbench tc's ematch_map.
func shareSys(t *testing.T) sysFS {
func shareSys(t testing.TB) sysFS {
t.Helper()
s := emptySys(t)
b, err := os.ReadFile(filepath.Join("testdata", "share-iproute2", ematchMapName))
Expand Down Expand Up @@ -120,7 +120,7 @@ func TestGotcFilterUnit(t *testing.T) {
description string
args []string
stdin string
sys func(*testing.T) sysFS
sys func(testing.TB) sysFS
replies []Reply
info uint32 // when non-zero, the last request's tcm_info
expected result
Expand Down
165 changes: 165 additions & 0 deletions internal/gotc/fw_basic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//go:build gotc_write

package gotc

import (
"errors"
"math"

"github.com/randomizedcoder/xtcp2/pkg/cint"
"github.com/randomizedcoder/xtcp2/pkg/xtcpnl"
)

// The parse_fopt of basic (tc/f_basic.c) and cgroup (tc/f_cgroup.c) at
// iproute2 v7.2.0: an ematch tree, actions, and for basic a classid.

// basicExplain is f_basic.c explain, u32's SELECTOR and FILTERID copied in
// and police and flowid left out (W150).
func (r *runner) basicExplain() {
r.errf("%s", "Usage: ... basic [ match EMATCH_TREE ]\n"+
" [ action ACTION_SPEC ] [ classid CLASSID ]\n"+
"\n"+
"Where:\tSELECTOR := SAMPLE SAMPLE ...\n"+
"\tFILTERID := X:Y:Z\n"+
"\tACTION_SPEC := ... look at individual actions\n"+
"\n"+
"NOTE: CLASSID is parsed as hexadecimal input.\n")
}

// cgroupExplain is f_cgroup.c explain.
func (r *runner) cgroupExplain() {
r.errf("%s", "Usage: ... cgroup [ match EMATCH_TREE ]\n"+
" [ action ACTION_SPEC ]\n")
}

// emHandle is basic's and cgroup's handle: strtol base 0 with only
// LONG_MIN and LONG_MAX refused, so junk is 0 and the long is narrowed to
// the u32 (W147).
func (r *runner) emHandle(m *fmod) error {
if !m.a.hasHandle {
return nil
}
h := strtol(m.handle)
if h == math.MinInt64 || h == math.MaxInt64 {
r.errf("Illegal handle \"%s\", must be numeric.\n", m.handle)
return errKindParse
}
m.w.Handle = cint.LongBits(h)
return nil
}

// emMatchArm is the match arm both share, and flow's: NEXT_ARG, then
// parse_ematch, whose failure is `Illegal "ematch"`.
func (r *runner) emMatchArm(m *fmod, args []string, tcaID uint16) ([]string, error) {
if _, err := r.nextArg(args); err != nil {
return nil, err
}
rest, err := r.parseEmatch(m, args, tcaID)
if errors.Is(err, errEmatch) {
r.errf("Illegal \"ematch\"\n")
return nil, errKindParse
}
return rest, err
}

// emActionArm is the action arm: NEXT_ARG, then parse_action.
func (r *runner) emActionArm(m *fmod, args []string, tcaID uint16) ([]string, error) {
v, err := r.nextArg(args)
if err != nil {
return nil, err
}
rest, ok, err := r.parseAction(m, v, tcaID)
if err != nil {
return nil, err
}
if !ok {
r.errf("Illegal \"action\"\n")
return nil, errKindParse
}
return rest, nil
}

// parseBasicFopt is f_basic.c basic_parse_opt. With no words it sends no
// TCA_OPTIONS at all, which the kernel refuses (W148).
func parseBasicFopt(r *runner, m *fmod) error {
if err := r.emHandle(m); err != nil {
return err
}
args := m.rest
if len(args) == 0 {
return nil
}
tail := m.ops.begin(maxMsg, xtcpnl.TcaOptions)
for len(args) > 0 {
a := args[0]
var err error
switch {
case matches(a, "match"):
if args, err = r.emMatchArm(m, args, xtcpnl.TcaBasicEmatches); err != nil {
return err
}
continue
case matches(a, wordClassid) || a == wordFlowid:
if args, err = r.nextArg(args); err != nil {
return err
}
c, ok := tcClassid(args[0])
if !ok {
r.errf("Illegal \"classid\"\n")
return errKindParse
}
m.ops.u32(maxMsg, xtcpnl.TcaBasicClassid, c)
case matches(a, wordAction):
if args, err = r.emActionArm(m, args, xtcpnl.TcaBasicAct); err != nil {
return err
}
continue
case matches(a, "police"):
return r.policeArm(args, xtcpnl.TcFKindBasic)
case a == helpWord: // strcmp: "h" is not help (W150)
r.basicExplain()
return errKindParse
default:
r.errf("What is \"%s\"?\n", a)
r.basicExplain()
return errKindParse
}
args = args[1:]
}
m.ops.end(tail)
return nil
}

// parseCgroupFopt is f_cgroup.c cgroup_parse_opt: the nest always, even
// empty.
func parseCgroupFopt(r *runner, m *fmod) error {
if err := r.emHandle(m); err != nil {
return err
}
tail := m.ops.begin(maxMsg, xtcpnl.TcaOptions)
args := m.rest
for len(args) > 0 {
a := args[0]
var err error
switch {
case matches(a, "match"):
args, err = r.emMatchArm(m, args, xtcpnl.TcaCgroupEmatches)
case matches(a, wordAction):
args, err = r.emActionArm(m, args, xtcpnl.TcaCgroupAct)
case matches(a, "police"):
return r.policeArm(args, xtcpnl.TcFKindCgroup)
case a == helpWord:
r.cgroupExplain()
return errKindParse
default:
r.errf("What is \"%s\"?\n", a)
r.cgroupExplain()
return errKindParse
}
if err != nil {
return err
}
}
m.ops.end(tail)
return nil
}
Loading