interfaces_linux.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package interfaces
  4. import (
  5. "bufio"
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "net/netip"
  13. "os"
  14. "os/exec"
  15. "runtime"
  16. "strings"
  17. "sync/atomic"
  18. "github.com/jsimonetti/rtnetlink"
  19. "github.com/mdlayher/netlink"
  20. "go4.org/mem"
  21. "golang.org/x/sys/unix"
  22. "tailscale.com/net/netaddr"
  23. "tailscale.com/util/lineread"
  24. )
  25. func init() {
  26. likelyHomeRouterIP = likelyHomeRouterIPLinux
  27. }
  28. var procNetRouteErr atomic.Bool
  29. // errStopReading is a sentinel error value used internally by
  30. // lineread.File callers to stop reading. It doesn't escape to
  31. // callers/users.
  32. var errStopReading = errors.New("stop reading")
  33. /*
  34. Parse 10.0.0.1 out of:
  35. $ cat /proc/net/route
  36. Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
  37. ens18 00000000 0100000A 0003 0 0 0 00000000 0 0 0
  38. ens18 0000000A 00000000 0001 0 0 0 0000FFFF 0 0 0
  39. */
  40. func likelyHomeRouterIPLinux() (ret netip.Addr, myIP netip.Addr, ok bool) {
  41. if procNetRouteErr.Load() {
  42. // If we failed to read /proc/net/route previously, don't keep trying.
  43. // But if we're on Android, go into the Android path.
  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. if runtime.GOOS == "android" {
  169. v, err = defaultRouteInterfaceAndroidIPRoute()
  170. d.InterfaceName = v
  171. return d, err
  172. }
  173. // Issue 4038: the default route (such as on Unifi UDM Pro)
  174. // might be in a non-default table, so it won't show up in
  175. // /proc/net/route. Use netlink to find the default route.
  176. //
  177. // TODO(bradfitz): this allocates a fair bit. We should track
  178. // this in net/interfaces/monitor instead and have
  179. // interfaces.GetState take a netmon.Monitor or similar so the
  180. // routing table can be cached and the monitor's existing
  181. // subscription to route changes can update the cached state,
  182. // rather than querying the whole thing every time like
  183. // defaultRouteFromNetlink does.
  184. //
  185. // Then we should just always try to use the cached route
  186. // table from netlink every time, and only use /proc/net/route
  187. // as a fallback for weird environments where netlink might be
  188. // banned but /proc/net/route is emulated (e.g. stuff like
  189. // Cloud Run?).
  190. return defaultRouteFromNetlink()
  191. }
  192. func defaultRouteFromNetlink() (d DefaultRouteDetails, err error) {
  193. c, err := rtnetlink.Dial(&netlink.Config{Strict: true})
  194. if err != nil {
  195. return d, fmt.Errorf("defaultRouteFromNetlink: Dial: %w", err)
  196. }
  197. defer c.Close()
  198. rms, err := c.Route.List()
  199. if err != nil {
  200. return d, fmt.Errorf("defaultRouteFromNetlink: List: %w", err)
  201. }
  202. for _, rm := range rms {
  203. if rm.Attributes.Gateway == nil {
  204. // A default route has a gateway. If it doesn't, skip it.
  205. continue
  206. }
  207. if rm.Attributes.Dst != nil {
  208. // A default route has a nil destination to mean anything
  209. // so ignore any route for a specific destination.
  210. // TODO(bradfitz): better heuristic?
  211. // empirically this seems like enough.
  212. continue
  213. }
  214. // TODO(bradfitz): care about address family, if
  215. // callers ever start caring about v4-vs-v6 default
  216. // route differences.
  217. idx := int(rm.Attributes.OutIface)
  218. if idx == 0 {
  219. continue
  220. }
  221. if iface, err := net.InterfaceByIndex(idx); err == nil {
  222. d.InterfaceName = iface.Name
  223. d.InterfaceIndex = idx
  224. return d, nil
  225. }
  226. }
  227. return d, errNoDefaultRoute
  228. }
  229. var zeroRouteBytes = []byte("00000000")
  230. var procNetRoutePath = "/proc/net/route"
  231. // maxProcNetRouteRead is the max number of lines to read from
  232. // /proc/net/route looking for a default route.
  233. const maxProcNetRouteRead = 1000
  234. var errNoDefaultRoute = errors.New("no default route found")
  235. func defaultRouteInterfaceProcNetInternal(bufsize int) (string, error) {
  236. f, err := os.Open(procNetRoutePath)
  237. if err != nil {
  238. return "", err
  239. }
  240. defer f.Close()
  241. br := bufio.NewReaderSize(f, bufsize)
  242. lineNum := 0
  243. for {
  244. lineNum++
  245. line, err := br.ReadSlice('\n')
  246. if err == io.EOF || lineNum > maxProcNetRouteRead {
  247. return "", errNoDefaultRoute
  248. }
  249. if err != nil {
  250. return "", err
  251. }
  252. if !bytes.Contains(line, zeroRouteBytes) {
  253. continue
  254. }
  255. fields := strings.Fields(string(line))
  256. ifc := fields[0]
  257. ip := fields[1]
  258. netmask := fields[7]
  259. if strings.HasPrefix(ifc, "tailscale") ||
  260. strings.HasPrefix(ifc, "wg") {
  261. continue
  262. }
  263. if ip == "00000000" && netmask == "00000000" {
  264. // default route
  265. return ifc, nil // interface name
  266. }
  267. }
  268. }
  269. // returns string interface name and an error.
  270. // io.EOF: full route table processed, no default route found.
  271. // other io error: something went wrong reading the route file.
  272. func defaultRouteInterfaceProcNet() (string, error) {
  273. rc, err := defaultRouteInterfaceProcNetInternal(128)
  274. if rc == "" && (errors.Is(err, io.EOF) || err == nil) {
  275. // https://github.com/google/gvisor/issues/5732
  276. // On a regular Linux kernel you can read the first 128 bytes of /proc/net/route,
  277. // then come back later to read the next 128 bytes and so on.
  278. //
  279. // In Google Cloud Run, where /proc/net/route comes from gVisor, you have to
  280. // read it all at once. If you read only the first few bytes then the second
  281. // read returns 0 bytes no matter how much originally appeared to be in the file.
  282. //
  283. // At the time of this writing (Mar 2021) Google Cloud Run has eth0 and eth1
  284. // with a 384 byte /proc/net/route. We allocate a large buffer to ensure we'll
  285. // read it all in one call.
  286. return defaultRouteInterfaceProcNetInternal(4096)
  287. }
  288. return rc, err
  289. }
  290. // defaultRouteInterfaceAndroidIPRoute tries to find the machine's default route interface name
  291. // by parsing the "ip route" command output. We use this on Android where /proc/net/route
  292. // can be missing entries or have locked-down permissions.
  293. // See also comments in https://github.com/tailscale/tailscale/pull/666.
  294. func defaultRouteInterfaceAndroidIPRoute() (ifname string, err error) {
  295. cmd := exec.Command("/system/bin/ip", "route", "show", "table", "0")
  296. out, err := cmd.StdoutPipe()
  297. if err != nil {
  298. return "", err
  299. }
  300. if err := cmd.Start(); err != nil {
  301. log.Printf("interfaces: running /system/bin/ip: %v", err)
  302. return "", err
  303. }
  304. // Search for line like "default via 10.0.2.2 dev radio0 table 1016 proto static mtu 1500 "
  305. lineread.Reader(out, func(line []byte) error {
  306. const pfx = "default via "
  307. if !mem.HasPrefix(mem.B(line), mem.S(pfx)) {
  308. return nil
  309. }
  310. ff := strings.Fields(string(line))
  311. for i, v := range ff {
  312. if i > 0 && ff[i-1] == "dev" && ifname == "" {
  313. ifname = v
  314. }
  315. }
  316. return nil
  317. })
  318. cmd.Process.Kill()
  319. cmd.Wait()
  320. if ifname == "" {
  321. return "", errors.New("no default routes found")
  322. }
  323. return ifname, nil
  324. }