interfaces_linux.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build !android
  4. package interfaces
  5. import (
  6. "bufio"
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "net/netip"
  14. "os"
  15. "os/exec"
  16. "runtime"
  17. "strings"
  18. "sync/atomic"
  19. "github.com/jsimonetti/rtnetlink"
  20. "github.com/mdlayher/netlink"
  21. "go4.org/mem"
  22. "golang.org/x/sys/unix"
  23. "tailscale.com/net/netaddr"
  24. "tailscale.com/util/lineread"
  25. )
  26. func init() {
  27. likelyHomeRouterIP = likelyHomeRouterIPLinux
  28. }
  29. var procNetRouteErr atomic.Bool
  30. // errStopReading is a sentinel error value used internally by
  31. // lineread.File callers to stop reading. It doesn't escape to
  32. // callers/users.
  33. var errStopReading = errors.New("stop reading")
  34. /*
  35. Parse 10.0.0.1 out of:
  36. $ cat /proc/net/route
  37. Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
  38. ens18 00000000 0100000A 0003 0 0 0 00000000 0 0 0
  39. ens18 0000000A 00000000 0001 0 0 0 0000FFFF 0 0 0
  40. */
  41. func likelyHomeRouterIPLinux() (ret netip.Addr, myIP netip.Addr, ok bool) {
  42. if procNetRouteErr.Load() {
  43. // If we failed to read /proc/net/route previously, don't keep trying.
  44. if runtime.GOOS == "android" {
  45. return likelyHomeRouterIPAndroid()
  46. }
  47. return ret, myIP, false
  48. }
  49. lineNum := 0
  50. var f []mem.RO
  51. err := lineread.File(procNetRoutePath, func(line []byte) error {
  52. lineNum++
  53. if lineNum == 1 {
  54. // Skip header line.
  55. return nil
  56. }
  57. if lineNum > maxProcNetRouteRead {
  58. return errStopReading
  59. }
  60. f = mem.AppendFields(f[:0], mem.B(line))
  61. if len(f) < 4 {
  62. return nil
  63. }
  64. gwHex, flagsHex := f[2], f[3]
  65. flags, err := mem.ParseUint(flagsHex, 16, 16)
  66. if err != nil {
  67. return nil // ignore error, skip line and keep going
  68. }
  69. if flags&(unix.RTF_UP|unix.RTF_GATEWAY) != unix.RTF_UP|unix.RTF_GATEWAY {
  70. return nil
  71. }
  72. ipu32, err := mem.ParseUint(gwHex, 16, 32)
  73. if err != nil {
  74. return nil // ignore error, skip line and keep going
  75. }
  76. ip := netaddr.IPv4(byte(ipu32), byte(ipu32>>8), byte(ipu32>>16), byte(ipu32>>24))
  77. if ip.IsPrivate() {
  78. ret = ip
  79. return errStopReading
  80. }
  81. return nil
  82. })
  83. if errors.Is(err, errStopReading) {
  84. err = nil
  85. }
  86. if err != nil {
  87. procNetRouteErr.Store(true)
  88. if runtime.GOOS == "android" {
  89. return likelyHomeRouterIPAndroid()
  90. }
  91. log.Printf("interfaces: failed to read /proc/net/route: %v", err)
  92. }
  93. if ret.IsValid() {
  94. // Try to get the local IP of the interface associated with
  95. // this route to short-circuit finding the IP associated with
  96. // this gateway. This isn't fatal if it fails.
  97. if len(f) > 0 && !disableLikelyHomeRouterIPSelf() {
  98. ForeachInterface(func(ni Interface, pfxs []netip.Prefix) {
  99. // Ensure this is the same interface
  100. if !f[0].EqualString(ni.Name) {
  101. return
  102. }
  103. // Find the first IPv4 address and use it.
  104. for _, pfx := range pfxs {
  105. if addr := pfx.Addr(); addr.Is4() {
  106. myIP = addr
  107. break
  108. }
  109. }
  110. })
  111. }
  112. return ret, myIP, true
  113. }
  114. if lineNum >= maxProcNetRouteRead {
  115. // If we went over our line limit without finding an answer, assume
  116. // we're a big fancy Linux router (or at least not a home system)
  117. // and set the error bit so we stop trying this in the future (and wasting CPU).
  118. // See https://github.com/tailscale/tailscale/issues/7621.
  119. //
  120. // Remember that "likelyHomeRouterIP" exists purely to find the port
  121. // mapping service (UPnP, PMP, PCP) often present on a home router. If we hit
  122. // the route (line) limit without finding an answer, we're unlikely to ever
  123. // find one in the future.
  124. procNetRouteErr.Store(true)
  125. }
  126. return netip.Addr{}, netip.Addr{}, false
  127. }
  128. // Android apps don't have permission to read /proc/net/route, at
  129. // least on Google devices and the Android emulator.
  130. func likelyHomeRouterIPAndroid() (ret netip.Addr, _ netip.Addr, ok bool) {
  131. cmd := exec.Command("/system/bin/ip", "route", "show", "table", "0")
  132. out, err := cmd.StdoutPipe()
  133. if err != nil {
  134. return
  135. }
  136. if err := cmd.Start(); err != nil {
  137. log.Printf("interfaces: running /system/bin/ip: %v", err)
  138. return
  139. }
  140. // Search for line like "default via 10.0.2.2 dev radio0 table 1016 proto static mtu 1500 "
  141. lineread.Reader(out, func(line []byte) error {
  142. const pfx = "default via "
  143. if !mem.HasPrefix(mem.B(line), mem.S(pfx)) {
  144. return nil
  145. }
  146. line = line[len(pfx):]
  147. sp := bytes.IndexByte(line, ' ')
  148. if sp == -1 {
  149. return nil
  150. }
  151. ipb := line[:sp]
  152. if ip, err := netip.ParseAddr(string(ipb)); err == nil && ip.Is4() {
  153. ret = ip
  154. log.Printf("interfaces: found Android default route %v", ip)
  155. }
  156. return nil
  157. })
  158. cmd.Process.Kill()
  159. cmd.Wait()
  160. return ret, netip.Addr{}, ret.IsValid()
  161. }
  162. func defaultRoute() (d DefaultRouteDetails, err error) {
  163. v, err := defaultRouteInterfaceProcNet()
  164. if err == nil {
  165. d.InterfaceName = v
  166. return d, nil
  167. }
  168. // Issue 4038: the default route (such as on Unifi UDM Pro)
  169. // might be in a non-default table, so it won't show up in
  170. // /proc/net/route. Use netlink to find the default route.
  171. //
  172. // TODO(bradfitz): this allocates a fair bit. We should track
  173. // this in net/interfaces/monitor instead and have
  174. // interfaces.GetState take a netmon.Monitor or similar so the
  175. // routing table can be cached and the monitor's existing
  176. // subscription to route changes can update the cached state,
  177. // rather than querying the whole thing every time like
  178. // defaultRouteFromNetlink does.
  179. //
  180. // Then we should just always try to use the cached route
  181. // table from netlink every time, and only use /proc/net/route
  182. // as a fallback for weird environments where netlink might be
  183. // banned but /proc/net/route is emulated (e.g. stuff like
  184. // Cloud Run?).
  185. return defaultRouteFromNetlink()
  186. }
  187. func defaultRouteFromNetlink() (d DefaultRouteDetails, err error) {
  188. c, err := rtnetlink.Dial(&netlink.Config{Strict: true})
  189. if err != nil {
  190. return d, fmt.Errorf("defaultRouteFromNetlink: Dial: %w", err)
  191. }
  192. defer c.Close()
  193. rms, err := c.Route.List()
  194. if err != nil {
  195. return d, fmt.Errorf("defaultRouteFromNetlink: List: %w", err)
  196. }
  197. for _, rm := range rms {
  198. if rm.Attributes.Gateway == nil {
  199. // A default route has a gateway. If it doesn't, skip it.
  200. continue
  201. }
  202. if rm.Attributes.Dst != nil {
  203. // A default route has a nil destination to mean anything
  204. // so ignore any route for a specific destination.
  205. // TODO(bradfitz): better heuristic?
  206. // empirically this seems like enough.
  207. continue
  208. }
  209. // TODO(bradfitz): care about address family, if
  210. // callers ever start caring about v4-vs-v6 default
  211. // route differences.
  212. idx := int(rm.Attributes.OutIface)
  213. if idx == 0 {
  214. continue
  215. }
  216. if iface, err := net.InterfaceByIndex(idx); err == nil {
  217. d.InterfaceName = iface.Name
  218. d.InterfaceIndex = idx
  219. return d, nil
  220. }
  221. }
  222. return d, errNoDefaultRoute
  223. }
  224. var zeroRouteBytes = []byte("00000000")
  225. var procNetRoutePath = "/proc/net/route"
  226. // maxProcNetRouteRead is the max number of lines to read from
  227. // /proc/net/route looking for a default route.
  228. const maxProcNetRouteRead = 1000
  229. var errNoDefaultRoute = errors.New("no default route found")
  230. func defaultRouteInterfaceProcNetInternal(bufsize int) (string, error) {
  231. f, err := os.Open(procNetRoutePath)
  232. if err != nil {
  233. return "", err
  234. }
  235. defer f.Close()
  236. br := bufio.NewReaderSize(f, bufsize)
  237. lineNum := 0
  238. for {
  239. lineNum++
  240. line, err := br.ReadSlice('\n')
  241. if err == io.EOF || lineNum > maxProcNetRouteRead {
  242. return "", errNoDefaultRoute
  243. }
  244. if err != nil {
  245. return "", err
  246. }
  247. if !bytes.Contains(line, zeroRouteBytes) {
  248. continue
  249. }
  250. fields := strings.Fields(string(line))
  251. ifc := fields[0]
  252. ip := fields[1]
  253. netmask := fields[7]
  254. if strings.HasPrefix(ifc, "tailscale") ||
  255. strings.HasPrefix(ifc, "wg") {
  256. continue
  257. }
  258. if ip == "00000000" && netmask == "00000000" {
  259. // default route
  260. return ifc, nil // interface name
  261. }
  262. }
  263. }
  264. // returns string interface name and an error.
  265. // io.EOF: full route table processed, no default route found.
  266. // other io error: something went wrong reading the route file.
  267. func defaultRouteInterfaceProcNet() (string, error) {
  268. rc, err := defaultRouteInterfaceProcNetInternal(128)
  269. if rc == "" && (errors.Is(err, io.EOF) || err == nil) {
  270. // https://github.com/google/gvisor/issues/5732
  271. // On a regular Linux kernel you can read the first 128 bytes of /proc/net/route,
  272. // then come back later to read the next 128 bytes and so on.
  273. //
  274. // In Google Cloud Run, where /proc/net/route comes from gVisor, you have to
  275. // read it all at once. If you read only the first few bytes then the second
  276. // read returns 0 bytes no matter how much originally appeared to be in the file.
  277. //
  278. // At the time of this writing (Mar 2021) Google Cloud Run has eth0 and eth1
  279. // with a 384 byte /proc/net/route. We allocate a large buffer to ensure we'll
  280. // read it all in one call.
  281. return defaultRouteInterfaceProcNetInternal(4096)
  282. }
  283. return rc, err
  284. }