// Package hostaddrs lists the addresses on this host's interfaces, for // the instance inventory (equipo/chat/instance_inventory.go): the // addresses no request to the public web may reach. // // net.InterfaceAddrs asks the kernel over a netlink socket. CARLOS's // instance units allow only AF_INET, AF_INET6 and AF_UNIX sockets // (RestrictAddressFamilies=), so there it fails ("route ip+net: // netlinkrib: address family not supported by protocol"). The same // addresses are then read from procfs, as CARLOS reads its boxes' own // (platform internal/instancectl/localaddrs.go): IPv4 from fib_trie's // LOCAL routes, IPv6 from if_inet6. The directory is /proc/self/net, not // /proc/net: the units mount /proc with ProcSubset=pid, which hides the // /proc/net link and leaves the process's own directory. An instance // shares the box's network namespace, so these are the box's addresses. // // A list that can't be read whole is an error, never a shorter list. package hostaddrs import ( "bufio" "bytes" "encoding/hex" "errors" "fmt" "io/fs" "net" "net/netip" "os" "path/filepath" "slices" "strconv" "strings" "amadan.net/oficina/equipo/internal/websource" ) // ProcSelfNet is where the procfs sources are read. const ProcSelfNet = "/proc/self/net" // Public is the host's interface addresses a request could otherwise // reach: those websource.PublicAddress accepts. Every other address the // guarded client refuses before it asks the inventory (as Research's site // inventory, internal/runner/thin/research.go), so listing it would only // ask an owner to confirm prefixes for addresses nothing dials. // Canonical, once each, sorted. netlink nil is net.InterfaceAddrs; // procNet "" is ProcSelfNet. func Public(netlink func() ([]net.Addr, error), procNet string) ([]netip.Addr, error) { all, err := All(netlink, procNet) if err != nil { return nil, err } var out []netip.Addr for _, a := range all { if a = a.Unmap(); websource.PublicAddress(a) && !slices.Contains(out, a) { out = append(out, a) } } slices.SortFunc(out, func(a, b netip.Addr) int { return a.Compare(b) }) return out, nil } // All lists every address on the host's interfaces: netlink, or procfs // where netlink is refused. Both failing is both errors. func All(netlink func() ([]net.Addr, error), procNet string) ([]netip.Addr, error) { if netlink == nil { netlink = net.InterfaceAddrs } raw, nlErr := netlink() if nlErr == nil { var out []netip.Addr for _, a := range raw { n, ok := a.(*net.IPNet) if !ok { continue } if addr, ok := netip.AddrFromSlice(n.IP); ok { out = append(out, addr) } } return out, nil } if procNet == "" { procNet = ProcSelfNet } out, err := procfs(procNet) if err != nil { return nil, errors.Join(nlErr, err) } return out, nil } // procfs reads dir's fib_trie and if_inet6. No if_inet6 is a kernel // without IPv6, so no IPv6 address. func procfs(dir string) ([]netip.Addr, error) { b, err := os.ReadFile(filepath.Join(dir, "fib_trie")) if err != nil { return nil, err } out, err := parseFibTrie(b) if err != nil { return nil, fmt.Errorf("fib_trie: %w", err) } b, err = os.ReadFile(filepath.Join(dir, "if_inet6")) switch { case errors.Is(err, fs.ErrNotExist): return out, nil case err != nil: return nil, err } v6, err := parseIfInet6(b) if err != nil { return nil, fmt.Errorf("if_inet6: %w", err) } return append(out, v6...), nil } // parseFibTrie reads fib_trie: a leaf line "|-- " is followed by // one line per route at it, "/ ", with " tos=" // after it when the route has a TOS (the kernel's fib_trie_seq_show). A // LOCAL route is a destination the box answers for itself; one for a // single address is an interface address. Refused: a LOCAL route with // anything else after its type; one for a range (the box answering for // every address in it) unless it is loopback's, since the inventory holds // addresses and a range left out would be reachable; and a file with no // LOCAL route at all, since every kernel has 127.0.0.1 and so it isn't // the file this parser knows. func parseFibTrie(b []byte) ([]netip.Addr, error) { var out []netip.Addr var leaf netip.Addr local := false sc := bufio.NewScanner(bytes.NewReader(b)) for sc.Scan() { line := strings.TrimSpace(sc.Text()) if a, ok := strings.CutPrefix(line, "|-- "); ok { leaf, _ = netip.ParseAddr(strings.TrimSpace(a)) continue } f := strings.Fields(line) if len(f) < 3 || !strings.HasPrefix(f[0], "/") || f[2] != "LOCAL" || !leaf.IsValid() { continue } bits, err := strconv.Atoi(f[0][1:]) if err != nil || slices.ContainsFunc(f[3:], func(x string) bool { return !strings.HasPrefix(x, "tos=") }) { return nil, fmt.Errorf("%q is not a route", line) } local = true p, err := leaf.Prefix(bits) switch { case err != nil: return nil, fmt.Errorf("%q is not a route", line) case p.IsSingleIP(): out = append(out, leaf) case !p.Addr().IsLoopback(): return nil, fmt.Errorf("a local route for %s", p) } } if err := sc.Err(); err != nil { return nil, err } if !local { return nil, errors.New("no local route") } return out, nil } // parseIfInet6 reads if_inet6: each line starts with an address as 32 // hex digits. func parseIfInet6(b []byte) ([]netip.Addr, error) { var out []netip.Addr sc := bufio.NewScanner(bytes.NewReader(b)) for sc.Scan() { f := strings.Fields(sc.Text()) if len(f) == 0 { continue } raw, err := hex.DecodeString(f[0]) if err != nil || len(raw) != 16 { return nil, fmt.Errorf("%q is not an address", f[0]) } out = append(out, netip.AddrFrom16([16]byte(raw))) } return out, sc.Err() }