discoverips.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build linux
  15. // +build linux
  16. package mesh
  17. import (
  18. "errors"
  19. "fmt"
  20. "net"
  21. "sort"
  22. "github.com/vishvananda/netlink"
  23. )
  24. // getIP returns a private and public IP address for the local node.
  25. // It selects the private IP address in the following order:
  26. // - private IP to which hostname resolves
  27. // - private IP assigned to interface of default route
  28. // - private IP assigned to local interface
  29. // - nil if no private IP was found
  30. // It selects the public IP address in the following order:
  31. // - public IP to which hostname resolves
  32. // - public IP assigned to interface of default route
  33. // - public IP assigned to local interface
  34. // - private IP to which hostname resolves
  35. // - private IP assigned to interface of default route
  36. // - private IP assigned to local interface
  37. // - if no IP was found, return nil and an error.
  38. func getIP(hostname string, ignoreIfaces ...int) (*net.IPNet, *net.IPNet, error) {
  39. ignore := make(map[string]struct{})
  40. for i := range ignoreIfaces {
  41. if ignoreIfaces[i] == 0 {
  42. // Only ignore valid interfaces.
  43. continue
  44. }
  45. iface, err := net.InterfaceByIndex(ignoreIfaces[i])
  46. if err != nil {
  47. return nil, nil, fmt.Errorf("failed to find interface %d: %v", ignoreIfaces[i], err)
  48. }
  49. ips, err := ipsForInterface(iface)
  50. if err != nil {
  51. return nil, nil, err
  52. }
  53. for _, ip := range ips {
  54. ignore[ip.String()] = struct{}{}
  55. ignore[oneAddressCIDR(ip.IP).String()] = struct{}{}
  56. }
  57. }
  58. var hostPriv, hostPub []*net.IPNet
  59. {
  60. // Check IPs to which hostname resolves first.
  61. ips := ipsForHostname(hostname)
  62. for _, ip := range ips {
  63. ok, mask, err := assignedToInterface(ip)
  64. if err != nil {
  65. return nil, nil, fmt.Errorf("failed to search locally assigned addresses: %v", err)
  66. }
  67. if !ok {
  68. continue
  69. }
  70. if isLocal(ip.IP) {
  71. continue
  72. }
  73. ip.Mask = mask
  74. if isPublic(ip.IP) {
  75. hostPub = append(hostPub, ip)
  76. continue
  77. }
  78. hostPriv = append(hostPriv, ip)
  79. }
  80. sortIPs(hostPriv)
  81. sortIPs(hostPub)
  82. }
  83. var defaultPriv, defaultPub []*net.IPNet
  84. {
  85. // Check IPs on interface for default route next.
  86. iface, err := defaultInterface()
  87. if err != nil {
  88. return nil, nil, err
  89. }
  90. ips, err := ipsForInterface(iface)
  91. if err != nil {
  92. return nil, nil, err
  93. }
  94. for _, ip := range ips {
  95. if isLocal(ip.IP) {
  96. continue
  97. }
  98. if isPublic(ip.IP) {
  99. defaultPub = append(defaultPub, ip)
  100. continue
  101. }
  102. defaultPriv = append(defaultPriv, ip)
  103. }
  104. sortIPs(defaultPriv)
  105. sortIPs(defaultPub)
  106. }
  107. var interfacePriv, interfacePub []*net.IPNet
  108. {
  109. // Finally look for IPs on all interfaces.
  110. ips, err := ipsForAllInterfaces()
  111. if err != nil {
  112. return nil, nil, err
  113. }
  114. for _, ip := range ips {
  115. if isLocal(ip.IP) {
  116. continue
  117. }
  118. if isPublic(ip.IP) {
  119. interfacePub = append(interfacePub, ip)
  120. continue
  121. }
  122. interfacePriv = append(interfacePriv, ip)
  123. }
  124. sortIPs(interfacePriv)
  125. sortIPs(interfacePub)
  126. }
  127. var priv, pub, tmpPriv, tmpPub []*net.IPNet
  128. tmpPriv = append(tmpPriv, hostPriv...)
  129. tmpPriv = append(tmpPriv, defaultPriv...)
  130. tmpPriv = append(tmpPriv, interfacePriv...)
  131. tmpPub = append(tmpPub, hostPub...)
  132. tmpPub = append(tmpPub, defaultPub...)
  133. tmpPub = append(tmpPub, interfacePub...)
  134. for i := range tmpPriv {
  135. if _, ok := ignore[tmpPriv[i].String()]; ok {
  136. continue
  137. }
  138. priv = append(priv, tmpPriv[i])
  139. }
  140. for i := range tmpPub {
  141. if _, ok := ignore[tmpPub[i].String()]; ok {
  142. continue
  143. }
  144. pub = append(pub, tmpPub[i])
  145. }
  146. if len(priv) == 0 && len(pub) == 0 {
  147. return nil, nil, errors.New("no valid IP was found")
  148. }
  149. if len(priv) == 0 {
  150. // If no private IPs were found, use nil.
  151. priv = append(priv, nil)
  152. }
  153. if len(pub) == 0 {
  154. pub = priv
  155. }
  156. return priv[0], pub[0], nil
  157. }
  158. func assignedToInterface(ip *net.IPNet) (bool, net.IPMask, error) {
  159. links, err := netlink.LinkList()
  160. if err != nil {
  161. return false, nil, fmt.Errorf("failed to list interfaces: %v", err)
  162. }
  163. // Sort the links for stability.
  164. sort.Slice(links, func(i, j int) bool {
  165. return links[i].Attrs().Name < links[j].Attrs().Name
  166. })
  167. for _, link := range links {
  168. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  169. if err != nil {
  170. return false, nil, fmt.Errorf("failed to list addresses for %s: %v", link.Attrs().Name, err)
  171. }
  172. // Sort the IPs for stability.
  173. sort.Slice(addrs, func(i, j int) bool {
  174. return addrs[i].String() < addrs[j].String()
  175. })
  176. for i := range addrs {
  177. if ip.IP.Equal(addrs[i].IP) {
  178. return true, addrs[i].Mask, nil
  179. }
  180. }
  181. }
  182. return false, nil, nil
  183. }
  184. // ipsForHostname returns a slice of IPs to which the
  185. // given hostname resolves.
  186. func ipsForHostname(hostname string) []*net.IPNet {
  187. if ip := net.ParseIP(hostname); ip != nil {
  188. return []*net.IPNet{oneAddressCIDR(ip)}
  189. }
  190. ips, err := net.LookupIP(hostname)
  191. if err != nil {
  192. // Most likely the hostname is not resolvable.
  193. return nil
  194. }
  195. nets := make([]*net.IPNet, len(ips))
  196. for i := range ips {
  197. nets[i] = oneAddressCIDR(ips[i])
  198. }
  199. return nets
  200. }
  201. // ipsForAllInterfaces returns a slice of IPs assigned to all the
  202. // interfaces on the host.
  203. func ipsForAllInterfaces() ([]*net.IPNet, error) {
  204. ifaces, err := net.Interfaces()
  205. if err != nil {
  206. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  207. }
  208. var nets []*net.IPNet
  209. for _, iface := range ifaces {
  210. ips, err := ipsForInterface(&iface)
  211. if err != nil {
  212. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  213. }
  214. nets = append(nets, ips...)
  215. }
  216. return nets, nil
  217. }
  218. // ipsForInterface returns a slice of IPs assigned to the given interface.
  219. func ipsForInterface(iface *net.Interface) ([]*net.IPNet, error) {
  220. link, err := netlink.LinkByIndex(iface.Index)
  221. if err != nil {
  222. return nil, fmt.Errorf("failed to get link: %s", err)
  223. }
  224. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  225. if err != nil {
  226. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  227. }
  228. var ips []*net.IPNet
  229. for _, a := range addrs {
  230. if a.IPNet != nil {
  231. ips = append(ips, a.IPNet)
  232. }
  233. }
  234. return ips, nil
  235. }
  236. // interfacesForIP returns a slice of interfaces withthe given IP.
  237. func interfacesForIP(ip *net.IPNet) ([]net.Interface, error) {
  238. ifaces, err := net.Interfaces()
  239. if err != nil {
  240. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  241. }
  242. var interfaces []net.Interface
  243. for _, iface := range ifaces {
  244. ips, err := ipsForInterface(&iface)
  245. if err != nil {
  246. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  247. }
  248. for i := range ips {
  249. if ip.IP.Equal(ips[i].IP) {
  250. interfaces = append(interfaces, iface)
  251. break
  252. }
  253. }
  254. }
  255. if len(interfaces) == 0 {
  256. return nil, fmt.Errorf("no interface has %s assigned", ip.String())
  257. }
  258. return interfaces, nil
  259. }
  260. // defaultInterface returns the interface for the default route of the host.
  261. func defaultInterface() (*net.Interface, error) {
  262. routes, err := netlink.RouteList(nil, netlink.FAMILY_ALL)
  263. if err != nil {
  264. return nil, err
  265. }
  266. for _, route := range routes {
  267. if route.Dst == nil || route.Dst.String() == "0.0.0.0/0" || route.Dst.String() == "::/0" {
  268. if route.LinkIndex <= 0 {
  269. return nil, errors.New("failed to determine interface of route")
  270. }
  271. return net.InterfaceByIndex(route.LinkIndex)
  272. }
  273. }
  274. return nil, errors.New("failed to find default route")
  275. }