| 1 | // Package hostaddrs lists the addresses on this host's interfaces, for |
| 2 | // the instance inventory (equipo/chat/instance_inventory.go): the |
| 3 | // addresses no request to the public web may reach. |
| 4 | // |
| 5 | // net.InterfaceAddrs asks the kernel over a netlink socket. CARLOS's |
| 6 | // instance units allow only AF_INET, AF_INET6 and AF_UNIX sockets |
| 7 | // (RestrictAddressFamilies=), so there it fails ("route ip+net: |
| 8 | // netlinkrib: address family not supported by protocol"). The same |
| 9 | // addresses are then read from procfs, as CARLOS reads its boxes' own |
| 10 | // (platform internal/instancectl/localaddrs.go): IPv4 from fib_trie's |
| 11 | // LOCAL routes, IPv6 from if_inet6. The directory is /proc/self/net, not |
| 12 | // /proc/net: the units mount /proc with ProcSubset=pid, which hides the |
| 13 | // /proc/net link and leaves the process's own directory. An instance |
| 14 | // shares the box's network namespace, so these are the box's addresses. |
| 15 | // |
| 16 | // A list that can't be read whole is an error, never a shorter list. |
| 17 | package hostaddrs |
| 18 | |
| 19 | import ( |
| 20 | "bufio" |
| 21 | "bytes" |
| 22 | "encoding/hex" |
| 23 | "errors" |
| 24 | "fmt" |
| 25 | "io/fs" |
| 26 | "net" |
| 27 | "net/netip" |
| 28 | "os" |
| 29 | "path/filepath" |
| 30 | "slices" |
| 31 | "strconv" |
| 32 | "strings" |
| 33 | |
| 34 | "amadan.net/oficina/equipo/internal/websource" |
| 35 | ) |
| 36 | |
| 37 | // ProcSelfNet is where the procfs sources are read. |
| 38 | const ProcSelfNet = "/proc/self/net" |
| 39 | |
| 40 | // Public is the host's interface addresses a request could otherwise |
| 41 | // reach: those websource.PublicAddress accepts. Every other address the |
| 42 | // guarded client refuses before it asks the inventory (as Research's site |
| 43 | // inventory, internal/runner/thin/research.go), so listing it would only |
| 44 | // ask an owner to confirm prefixes for addresses nothing dials. |
| 45 | // Canonical, once each, sorted. netlink nil is net.InterfaceAddrs; |
| 46 | // procNet "" is ProcSelfNet. |
| 47 | func Public(netlink func() ([]net.Addr, error), procNet string) ([]netip.Addr, error) { |
| 48 | all, err := All(netlink, procNet) |
| 49 | if err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | var out []netip.Addr |
| 53 | for _, a := range all { |
| 54 | if a = a.Unmap(); websource.PublicAddress(a) && !slices.Contains(out, a) { |
| 55 | out = append(out, a) |
| 56 | } |
| 57 | } |
| 58 | slices.SortFunc(out, func(a, b netip.Addr) int { return a.Compare(b) }) |
| 59 | return out, nil |
| 60 | } |
| 61 | |
| 62 | // All lists every address on the host's interfaces: netlink, or procfs |
| 63 | // where netlink is refused. Both failing is both errors. |
| 64 | func All(netlink func() ([]net.Addr, error), procNet string) ([]netip.Addr, error) { |
| 65 | if netlink == nil { |
| 66 | netlink = net.InterfaceAddrs |
| 67 | } |
| 68 | raw, nlErr := netlink() |
| 69 | if nlErr == nil { |
| 70 | var out []netip.Addr |
| 71 | for _, a := range raw { |
| 72 | n, ok := a.(*net.IPNet) |
| 73 | if !ok { |
| 74 | continue |
| 75 | } |
| 76 | if addr, ok := netip.AddrFromSlice(n.IP); ok { |
| 77 | out = append(out, addr) |
| 78 | } |
| 79 | } |
| 80 | return out, nil |
| 81 | } |
| 82 | if procNet == "" { |
| 83 | procNet = ProcSelfNet |
| 84 | } |
| 85 | out, err := procfs(procNet) |
| 86 | if err != nil { |
| 87 | return nil, errors.Join(nlErr, err) |
| 88 | } |
| 89 | return out, nil |
| 90 | } |
| 91 | |
| 92 | // procfs reads dir's fib_trie and if_inet6. No if_inet6 is a kernel |
| 93 | // without IPv6, so no IPv6 address. |
| 94 | func procfs(dir string) ([]netip.Addr, error) { |
| 95 | b, err := os.ReadFile(filepath.Join(dir, "fib_trie")) |
| 96 | if err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | out, err := parseFibTrie(b) |
| 100 | if err != nil { |
| 101 | return nil, fmt.Errorf("fib_trie: %w", err) |
| 102 | } |
| 103 | b, err = os.ReadFile(filepath.Join(dir, "if_inet6")) |
| 104 | switch { |
| 105 | case errors.Is(err, fs.ErrNotExist): |
| 106 | return out, nil |
| 107 | case err != nil: |
| 108 | return nil, err |
| 109 | } |
| 110 | v6, err := parseIfInet6(b) |
| 111 | if err != nil { |
| 112 | return nil, fmt.Errorf("if_inet6: %w", err) |
| 113 | } |
| 114 | return append(out, v6...), nil |
| 115 | } |
| 116 | |
| 117 | // parseFibTrie reads fib_trie: a leaf line "|-- <addr>" is followed by |
| 118 | // one line per route at it, "/<len> <scope> <type>", with " tos=<n>" |
| 119 | // after it when the route has a TOS (the kernel's fib_trie_seq_show). A |
| 120 | // LOCAL route is a destination the box answers for itself; one for a |
| 121 | // single address is an interface address. Refused: a LOCAL route with |
| 122 | // anything else after its type; one for a range (the box answering for |
| 123 | // every address in it) unless it is loopback's, since the inventory holds |
| 124 | // addresses and a range left out would be reachable; and a file with no |
| 125 | // LOCAL route at all, since every kernel has 127.0.0.1 and so it isn't |
| 126 | // the file this parser knows. |
| 127 | func parseFibTrie(b []byte) ([]netip.Addr, error) { |
| 128 | var out []netip.Addr |
| 129 | var leaf netip.Addr |
| 130 | local := false |
| 131 | sc := bufio.NewScanner(bytes.NewReader(b)) |
| 132 | for sc.Scan() { |
| 133 | line := strings.TrimSpace(sc.Text()) |
| 134 | if a, ok := strings.CutPrefix(line, "|-- "); ok { |
| 135 | leaf, _ = netip.ParseAddr(strings.TrimSpace(a)) |
| 136 | continue |
| 137 | } |
| 138 | f := strings.Fields(line) |
| 139 | if len(f) < 3 || !strings.HasPrefix(f[0], "/") || f[2] != "LOCAL" || !leaf.IsValid() { |
| 140 | continue |
| 141 | } |
| 142 | bits, err := strconv.Atoi(f[0][1:]) |
| 143 | if err != nil || slices.ContainsFunc(f[3:], func(x string) bool { return !strings.HasPrefix(x, "tos=") }) { |
| 144 | return nil, fmt.Errorf("%q is not a route", line) |
| 145 | } |
| 146 | local = true |
| 147 | p, err := leaf.Prefix(bits) |
| 148 | switch { |
| 149 | case err != nil: |
| 150 | return nil, fmt.Errorf("%q is not a route", line) |
| 151 | case p.IsSingleIP(): |
| 152 | out = append(out, leaf) |
| 153 | case !p.Addr().IsLoopback(): |
| 154 | return nil, fmt.Errorf("a local route for %s", p) |
| 155 | } |
| 156 | } |
| 157 | if err := sc.Err(); err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | if !local { |
| 161 | return nil, errors.New("no local route") |
| 162 | } |
| 163 | return out, nil |
| 164 | } |
| 165 | |
| 166 | // parseIfInet6 reads if_inet6: each line starts with an address as 32 |
| 167 | // hex digits. |
| 168 | func parseIfInet6(b []byte) ([]netip.Addr, error) { |
| 169 | var out []netip.Addr |
| 170 | sc := bufio.NewScanner(bytes.NewReader(b)) |
| 171 | for sc.Scan() { |
| 172 | f := strings.Fields(sc.Text()) |
| 173 | if len(f) == 0 { |
| 174 | continue |
| 175 | } |
| 176 | raw, err := hex.DecodeString(f[0]) |
| 177 | if err != nil || len(raw) != 16 { |
| 178 | return nil, fmt.Errorf("%q is not an address", f[0]) |
| 179 | } |
| 180 | out = append(out, netip.AddrFrom16([16]byte(raw))) |
| 181 | } |
| 182 | return out, sc.Err() |
| 183 | } |
| 184 | |