diff --git a/Dockerfile b/Dockerfile index db255c6..8d64d5c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,13 +16,11 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GOARM=${TARGETVARIANT#v} go build -trimpath -ldflags "-s -w" -o app ./cmd/app -# The binary reads protocol and table names from /etc/iproute2, but the Alpine -# package installs them to /usr/share/iproute2, so they are copied over. Alpine +# The binary reads protocol and table names from the iproute2 package. Alpine # also keeps a shell and ip for debugging. FROM alpine:3.24 AS release -RUN apk add --no-cache iproute2 \ - && cp -r /usr/share/iproute2 /etc/iproute2 +RUN apk add --no-cache iproute2 WORKDIR /app diff --git a/lib/iproute2mapping/mapping.go b/lib/iproute2mapping/mapping.go index 2af4edb..42c7ebe 100644 --- a/lib/iproute2mapping/mapping.go +++ b/lib/iproute2mapping/mapping.go @@ -2,8 +2,11 @@ package iproute2mapping import ( "bufio" + "errors" "fmt" + "io/fs" "os" + "path/filepath" "strconv" "strings" ) @@ -18,43 +21,83 @@ const ( TABLE ) -// Paths -var filePaths = map[int]string{ - PROTOCOL: "/etc/iproute2/rt_protos", - TABLE: "/etc/iproute2/rt_tables", +// Mapping file of each type, relative to the directories in roots. +// A directory .d next to it may hold additional *.conf files. +var fileNames = map[int]string{ + PROTOCOL: "rt_protos", + TABLE: "rt_tables", } +// Directories holding the mapping files. Later entries override earlier ones, +// like iproute2 lets /etc override the distribution defaults in /usr/share. +var roots = []string{"/usr/share/iproute2", "/etc/iproute2"} + // Export error-check var Errors []error func init() { - var err error - for mapType, filePath := range filePaths { - ByName[mapType], ById[mapType], err = readFromFile(filePath) - if err != nil { - Errors = append(Errors, - fmt.Errorf("failed reading mapping-file '%s': %w", filePath, err), - ) - } + for mapType, fileName := range fileNames { + m := load(roots, fileName) + ByName[mapType], ById[mapType] = m.byName, m.byId + Errors = append(Errors, m.errs...) } } -func readFromFile(filePath string) (mapByName map[string]int, mapById map[int]string, err error) { +type mapping struct { + byName map[string]int + byId map[int]string + errs []error +} + +// load reads the mapping file and its .d directory from every root. +// Roots or files that do not exist are skipped, unless none exists at all. +func load(roots []string, fileName string) *mapping { + m := &mapping{ + byName: make(map[string]int), + byId: make(map[int]string), + } + + found := false + for _, root := range roots { + paths := []string{filepath.Join(root, fileName)} + confs, err := filepath.Glob(filepath.Join(root, fileName+".d", "*.conf")) + if err != nil { + m.errs = append(m.errs, err) + } + paths = append(paths, confs...) + + for _, path := range paths { + err := m.readFile(path) + if errors.Is(err, fs.ErrNotExist) { + continue + } + found = true + if err != nil { + m.errs = append(m.errs, fmt.Errorf("failed reading mapping-file '%s': %w", path, err)) + } + } + } + + if !found { + m.errs = append(m.errs, fmt.Errorf("no mapping-file '%s' found in %s", fileName, strings.Join(roots, ", "))) + } + return m +} + +// readFile adds all valid entries of the file to the mapping. +// Invalid lines are added to the errors and skipped. +func (m *mapping) readFile(filePath string) error { file, err := os.Open(filePath) if err != nil { - return nil, nil, err + return err } defer file.Close() scanner := bufio.NewScanner(file) - scanner.Split(bufio.ScanLines) - - mapByName = make(map[string]int) - mapById = make(map[int]string) // Go through file line-by-line for scanner.Scan() { - text := scanner.Text() + text := strings.TrimSpace(scanner.Text()) if text == "" || strings.HasPrefix(text, "#") { continue } @@ -62,29 +105,38 @@ func readFromFile(filePath string) (mapByName map[string]int, mapById map[int]st id, name, err := getMappingFromText(text) if err != nil { // Only warn as we can continue processing the file - Errors = append(Errors, - fmt.Errorf("mappig-data invalid '%s': %w", text, err), + m.errs = append(m.errs, + fmt.Errorf("mapping-data invalid in '%s': '%s': %w", filePath, text, err), ) continue } - mapByName[name] = id - mapById[id] = name + m.byName[name] = id + m.byId[id] = name } - return + return scanner.Err() } +// getMappingFromText parses " " with any whitespace in between. +// The id is decimal or hexadecimal with a 0x prefix, anything after the name is ignored. func getMappingFromText(text string) (int, string, error) { - // Split and read/convert data - data := strings.Split(text, "\t") + data := strings.Fields(text) + if len(data) < 2 { + return 0, "", fmt.Errorf("expected ' '") + } - id, err := strconv.Atoi(data[0]) + idStr, base := data[0], 10 + if len(idStr) > 2 && (idStr[:2] == "0x" || idStr[:2] == "0X") { + idStr, base = idStr[2:], 16 + } + // 31 bits so that the id also fits into an int on 32-bit platforms + id, err := strconv.ParseUint(idStr, base, 31) if err != nil { return 0, "", err } - return id, data[1], nil + return int(id), data[1], nil } // Try getting an id from a name (or a string containing an id) with a specified type diff --git a/lib/iproute2mapping/mapping_test.go b/lib/iproute2mapping/mapping_test.go index 1e4cc25..e9e37aa 100644 --- a/lib/iproute2mapping/mapping_test.go +++ b/lib/iproute2mapping/mapping_test.go @@ -1 +1,144 @@ package iproute2mapping + +import ( + "maps" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestGetMappingFromText(t *testing.T) { + tests := []struct { + name string + text string + wantId int + wantName string + wantErr bool + }{ + {name: "tab", text: "254\tmain", wantId: 254, wantName: "main"}, + {name: "space", text: "254 main", wantId: 254, wantName: "main"}, + {name: "many spaces", text: "254 main", wantId: 254, wantName: "main"}, + {name: "mixed whitespace", text: "254 \t main", wantId: 254, wantName: "main"}, + {name: "trailing comment", text: "100 mytable # my table", wantId: 100, wantName: "mytable"}, + {name: "hex", text: "0x10 hextable", wantId: 16, wantName: "hextable"}, + {name: "leading zeros are decimal", text: "010 oct", wantId: 10, wantName: "oct"}, + {name: "only a number", text: "254", wantErr: true}, + {name: "only a name", text: "main", wantErr: true}, + {name: "name before number", text: "main 254", wantErr: true}, + {name: "negative", text: "-1 neg", wantErr: true}, + {name: "too large", text: "99999999999 big", wantErr: true}, + {name: "empty hex", text: "0x hex", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + id, name, err := getMappingFromText(tt.text) + if (err != nil) != tt.wantErr { + t.Fatalf("error = %v, wantErr %v", err, tt.wantErr) + } + if err == nil && (id != tt.wantId || name != tt.wantName) { + t.Errorf("got (%d, %q), want (%d, %q)", id, name, tt.wantId, tt.wantName) + } + }) + } +} + +func writeFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestLoad(t *testing.T) { + usr, etc := t.TempDir(), t.TempDir() + + writeFile(t, filepath.Join(usr, "rt_tables"), + "# comment\n\n255\tlocal\n254 main\n253 default\n0\tunspec\n") + writeFile(t, filepath.Join(usr, "rt_tables.d", "extra.conf"), "200 extra\n") + writeFile(t, filepath.Join(usr, "rt_tables.d", "ignored.txt"), "201 ignored\n") + // etc overrides usr + writeFile(t, filepath.Join(etc, "rt_tables"), " 100 custom \n254 mainoverride\n") + writeFile(t, filepath.Join(etc, "rt_tables.d", "more.conf"), "101 more\n") + + m := load([]string{usr, etc}, "rt_tables") + if len(m.errs) != 0 { + t.Errorf("unexpected errors: %v", m.errs) + } + + wantByName := map[string]int{ + "local": 255, "main": 254, "default": 253, "unspec": 0, + "extra": 200, "custom": 100, "mainoverride": 254, "more": 101, + } + if !maps.Equal(m.byName, wantByName) { + t.Errorf("byName = %v, want %v", m.byName, wantByName) + } + if m.byId[254] != "mainoverride" || m.byId[100] != "custom" || m.byId[200] != "extra" { + t.Errorf("byId = %v", m.byId) + } +} + +func TestLoadMissingRootIsFine(t *testing.T) { + usr := t.TempDir() + writeFile(t, filepath.Join(usr, "rt_protos"), "2 kernel\n") + + m := load([]string{usr, filepath.Join(usr, "does-not-exist")}, "rt_protos") + if len(m.errs) != 0 { + t.Errorf("unexpected errors: %v", m.errs) + } + if m.byName["kernel"] != 2 { + t.Errorf("byName = %v", m.byName) + } +} + +func TestLoadNothingFound(t *testing.T) { + m := load([]string{filepath.Join(t.TempDir(), "a"), filepath.Join(t.TempDir(), "b")}, "rt_tables") + if len(m.errs) != 1 || !strings.Contains(m.errs[0].Error(), "no mapping-file") { + t.Errorf("errs = %v", m.errs) + } +} + +func TestLoadMalformedLinesAreSkipped(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "rt_tables"), "254\nfoo bar\n100 ok\n300\n") + + m := load([]string{dir}, "rt_tables") + if len(m.errs) != 3 { + t.Errorf("want 3 errors, got %v", m.errs) + } + if !maps.Equal(m.byName, map[string]int{"ok": 100}) { + t.Errorf("byName = %v", m.byName) + } +} + +func TestTryGetId(t *testing.T) { + origByName := ByName + t.Cleanup(func() { ByName = origByName }) + ByName = map[int]map[string]int{TABLE: {"main": 254}} + + tests := []struct { + name string + input string + want int + wantErr bool + }{ + {name: "name", input: "main", want: 254}, + {name: "number", input: "100", want: 100}, + {name: "negative number", input: "-1", want: -1}, + {name: "unknown name", input: "nope", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := TryGetId(TABLE, tt.input) + if (err != nil) != tt.wantErr { + t.Fatalf("error = %v, wantErr %v", err, tt.wantErr) + } + if err == nil && got != tt.want { + t.Errorf("got %d, want %d", got, tt.want) + } + }) + } +}