interfaces_linux.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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, 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, 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. return ret, true
  95. }
  96. if lineNum >= maxProcNetRouteRead {
  97. // If we went over our line limit without finding an answer, assume
  98. // we're a big fancy Linux router (or at least not a home system)
  99. // and set the error bit so we stop trying this in the future (and wasting CPU).
  100. // See https://github.com/tailscale/tailscale/issues/7621.
  101. //
  102. // Remember that "likelyHomeRouterIP" exists purely to find the port
  103. // mapping service (UPnP, PMP, PCP) often present on a home router. If we hit
  104. // the route (line) limit without finding an answer, we're unlikely to ever
  105. // find one in the future.
  106. procNetRouteErr.Store(true)
  107. }
  108. return netip.Addr{}, false
  109. }
  110. // Android apps don't have permission to read /proc/net/route, at
  111. // least on Google devices and the Android emulator.
  112. func likelyHomeRouterIPAndroid() (ret netip.Addr, ok bool) {
  113. cmd := exec.Command("/system/bin/ip", "route", "show", "table", "0")
  114. out, err := cmd.StdoutPipe()
  115. if err != nil {
  116. return
  117. }
  118. if err := cmd.Start(); err != nil {
  119. log.Printf("interfaces: running /system/bin/ip: %v", err)
  120. return
  121. }
  122. // Search for line like "default via 10.0.2.2 dev radio0 table 1016 proto static mtu 1500 "
  123. lineread.Reader(out, func(line []byte) error {
  124. const pfx = "default via "
  125. if !mem.HasPrefix(mem.B(line), mem.S(pfx)) {
  126. return nil
  127. }
  128. line = line[len(pfx):]
  129. sp := bytes.IndexByte(line, ' ')
  130. if sp == -1 {
  131. return nil
  132. }
  133. ipb := line[:sp]
  134. if ip, err := netip.ParseAddr(string(ipb)); err == nil && ip.Is4() {
  135. ret = ip
  136. log.Printf("interfaces: found Android default route %v", ip)
  137. }
  138. return nil
  139. })
  140. cmd.Process.Kill()
  141. cmd.Wait()
  142. return ret, ret.IsValid()
  143. }
  144. func defaultRoute() (d DefaultRouteDetails, err error) {
  145. v, err := defaultRouteInterfaceProcNet()
  146. if err == nil {
  147. d.InterfaceName = v
  148. return d, nil
  149. }
  150. if runtime.GOOS == "android" {
  151. v, err = defaultRouteInterfaceAndroidIPRoute()
  152. d.InterfaceName = v
  153. return d, err
  154. }
  155. // Issue 4038: the default route (such as on Unifi UDM Pro)
  156. // might be in a non-default table, so it won't show up in
  157. // /proc/net/route. Use netlink to find the default route.
  158. //
  159. // TODO(bradfitz): this allocates a fair bit. We should track
  160. // this in net/interfaces/monitor instead and have
  161. // interfaces.GetState take a netmon.Monitor or similar so the
  162. // routing table can be cached and the monitor's existing
  163. // subscription to route changes can update the cached state,
  164. // rather than querying the whole thing every time like
  165. // defaultRouteFromNetlink does.
  166. //
  167. // Then we should just always try to use the cached route
  168. // table from netlink every time, and only use /proc/net/route
  169. // as a fallback for weird environments where netlink might be
  170. // banned but /proc/net/route is emulated (e.g. stuff like
  171. // Cloud Run?).
  172. return defaultRouteFromNetlink()
  173. }
  174. func defaultRouteFromNetlink() (d DefaultRouteDetails, err error) {
  175. c, err := rtnetlink.Dial(&netlink.Config{Strict: true})
  176. if err != nil {
  177. return d, fmt.Errorf("defaultRouteFromNetlink: Dial: %w", err)
  178. }
  179. defer c.Close()
  180. rms, err := c.Route.List()
  181. if err != nil {
  182. return d, fmt.Errorf("defaultRouteFromNetlink: List: %w", err)
  183. }
  184. for _, rm := range rms {
  185. if rm.Attributes.Gateway == nil {
  186. // A default route has a gateway. If it doesn't, skip it.
  187. continue
  188. }
  189. if rm.Attributes.Dst != nil {
  190. // A default route has a nil destination to mean anything
  191. // so ignore any route for a specific destination.
  192. // TODO(bradfitz): better heuristic?
  193. // empirically this seems like enough.
  194. continue
  195. }
  196. // TODO(bradfitz): care about address family, if
  197. // callers ever start caring about v4-vs-v6 default
  198. // route differences.
  199. idx := int(rm.Attributes.OutIface)
  200. if idx == 0 {
  201. continue
  202. }
  203. if iface, err := net.InterfaceByIndex(idx); err == nil {
  204. d.InterfaceName = iface.Name
  205. d.InterfaceIndex = idx
  206. return d, nil
  207. }
  208. }
  209. return d, errNoDefaultRoute
  210. }
  211. var zeroRouteBytes = []byte("00000000")
  212. var procNetRoutePath = "/proc/net/route"
  213. // maxProcNetRouteRead is the max number of lines to read from
  214. // /proc/net/route looking for a default route.
  215. const maxProcNetRouteRead = 1000
  216. var errNoDefaultRoute = errors.New("no default route found")
  217. func defaultRouteInterfaceProcNetInternal(bufsize int) (string, error) {
  218. f, err := os.Open(procNetRoutePath)
  219. if err != nil {
  220. return "", err
  221. }
  222. defer f.Close()
  223. br := bufio.NewReaderSize(f, bufsize)
  224. lineNum := 0
  225. for {
  226. lineNum++
  227. line, err := br.ReadSlice('\n')
  228. if err == io.EOF || lineNum > maxProcNetRouteRead {
  229. return "", errNoDefaultRoute
  230. }
  231. if err != nil {
  232. return "", err
  233. }
  234. if !bytes.Contains(line, zeroRouteBytes) {
  235. continue
  236. }
  237. fields := strings.Fields(string(line))
  238. ifc := fields[0]
  239. ip := fields[1]
  240. netmask := fields[7]
  241. if strings.HasPrefix(ifc, "tailscale") ||
  242. strings.HasPrefix(ifc, "wg") {
  243. continue
  244. }
  245. if ip == "00000000" && netmask == "00000000" {
  246. // default route
  247. return ifc, nil // interface name
  248. }
  249. }
  250. }
  251. // returns string interface name and an error.
  252. // io.EOF: full route table processed, no default route found.
  253. // other io error: something went wrong reading the route file.
  254. func defaultRouteInterfaceProcNet() (string, error) {
  255. rc, err := defaultRouteInterfaceProcNetInternal(128)
  256. if rc == "" && (errors.Is(err, io.EOF) || err == nil) {
  257. // https://github.com/google/gvisor/issues/5732
  258. // On a regular Linux kernel you can read the first 128 bytes of /proc/net/route,
  259. // then come back later to read the next 128 bytes and so on.
  260. //
  261. // In Google Cloud Run, where /proc/net/route comes from gVisor, you have to
  262. // read it all at once. If you read only the first few bytes then the second
  263. // read returns 0 bytes no matter how much originally appeared to be in the file.
  264. //
  265. // At the time of this writing (Mar 2021) Google Cloud Run has eth0 and eth1
  266. // with a 384 byte /proc/net/route. We allocate a large buffer to ensure we'll
  267. // read it all in one call.
  268. return defaultRouteInterfaceProcNetInternal(4096)
  269. }
  270. return rc, err
  271. }
  272. // defaultRouteInterfaceAndroidIPRoute tries to find the machine's default route interface name
  273. // by parsing the "ip route" command output. We use this on Android where /proc/net/route
  274. // can be missing entries or have locked-down permissions.
  275. // See also comments in https://github.com/tailscale/tailscale/pull/666.
  276. func defaultRouteInterfaceAndroidIPRoute() (ifname string, err error) {
  277. cmd := exec.Command("/system/bin/ip", "route", "show", "table", "0")
  278. out, err := cmd.StdoutPipe()
  279. if err != nil {
  280. return "", err
  281. }
  282. if err := cmd.Start(); err != nil {
  283. log.Printf("interfaces: running /system/bin/ip: %v", err)
  284. return "", err
  285. }
  286. // Search for line like "default via 10.0.2.2 dev radio0 table 1016 proto static mtu 1500 "
  287. lineread.Reader(out, func(line []byte) error {
  288. const pfx = "default via "
  289. if !mem.HasPrefix(mem.B(line), mem.S(pfx)) {
  290. return nil
  291. }
  292. ff := strings.Fields(string(line))
  293. for i, v := range ff {
  294. if i > 0 && ff[i-1] == "dev" && ifname == "" {
  295. ifname = v
  296. }
  297. }
  298. return nil
  299. })
  300. cmd.Process.Kill()
  301. cmd.Wait()
  302. if ifname == "" {
  303. return "", errors.New("no default routes found")
  304. }
  305. return ifname, nil
  306. }