discoverips.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. // If allowedCIDRs is not empty, only IPs within these CIDRs will be considered for private IP selection.
  39. func getIP(hostname string, allowedCIDRs []*net.IPNet, ignoreIfaces ...int) (*net.IPNet, *net.IPNet, error) {
  40. ignore := make(map[string]struct{})
  41. for i := range ignoreIfaces {
  42. if ignoreIfaces[i] == 0 {
  43. // Only ignore valid interfaces.
  44. continue
  45. }
  46. iface, err := net.InterfaceByIndex(ignoreIfaces[i])
  47. if err != nil {
  48. return nil, nil, fmt.Errorf("failed to find interface %d: %v", ignoreIfaces[i], err)
  49. }
  50. ips, err := ipsForInterface(iface)
  51. if err != nil {
  52. return nil, nil, err
  53. }
  54. for _, ip := range ips {
  55. ignore[ip.String()] = struct{}{}
  56. ignore[oneAddressCIDR(ip.IP).String()] = struct{}{}
  57. }
  58. }
  59. var hostPriv, hostPub []*net.IPNet
  60. {
  61. // Check IPs to which hostname resolves first.
  62. ips := ipsForHostname(hostname)
  63. for _, ip := range ips {
  64. ok, mask, err := assignedToInterface(ip)
  65. if err != nil {
  66. return nil, nil, fmt.Errorf("failed to search locally assigned addresses: %v", err)
  67. }
  68. if !ok {
  69. continue
  70. }
  71. if isLocal(ip.IP) {
  72. continue
  73. }
  74. ip.Mask = mask
  75. if isPublic(ip.IP) {
  76. hostPub = append(hostPub, ip)
  77. continue
  78. }
  79. hostPriv = append(hostPriv, ip)
  80. }
  81. sortIPs(hostPriv)
  82. sortIPs(hostPub)
  83. }
  84. var defaultPriv, defaultPub []*net.IPNet
  85. {
  86. // Check IPs on interface for default route next.
  87. iface, err := defaultInterface()
  88. if err != nil {
  89. return nil, nil, err
  90. }
  91. ips, err := ipsForInterface(iface)
  92. if err != nil {
  93. return nil, nil, err
  94. }
  95. for _, ip := range ips {
  96. if isLocal(ip.IP) {
  97. continue
  98. }
  99. if isPublic(ip.IP) {
  100. defaultPub = append(defaultPub, ip)
  101. continue
  102. }
  103. defaultPriv = append(defaultPriv, ip)
  104. }
  105. sortIPs(defaultPriv)
  106. sortIPs(defaultPub)
  107. }
  108. var interfacePriv, interfacePub []*net.IPNet
  109. {
  110. // Finally look for IPs on all interfaces.
  111. ips, err := ipsForAllInterfaces()
  112. if err != nil {
  113. return nil, nil, err
  114. }
  115. for _, ip := range ips {
  116. if isLocal(ip.IP) {
  117. continue
  118. }
  119. if isPublic(ip.IP) {
  120. interfacePub = append(interfacePub, ip)
  121. continue
  122. }
  123. interfacePriv = append(interfacePriv, ip)
  124. }
  125. sortIPs(interfacePriv)
  126. sortIPs(interfacePub)
  127. }
  128. var priv, pub, tmpPriv, tmpPub []*net.IPNet
  129. tmpPriv = append(tmpPriv, hostPriv...)
  130. tmpPriv = append(tmpPriv, defaultPriv...)
  131. tmpPriv = append(tmpPriv, interfacePriv...)
  132. tmpPub = append(tmpPub, hostPub...)
  133. tmpPub = append(tmpPub, defaultPub...)
  134. tmpPub = append(tmpPub, interfacePub...)
  135. for i := range tmpPriv {
  136. if _, ok := ignore[tmpPriv[i].String()]; ok {
  137. continue
  138. }
  139. // If allowedCIDRs is specified, filter private IPs by these CIDRs.
  140. if len(allowedCIDRs) > 0 && !isInCIDRs(tmpPriv[i].IP, allowedCIDRs) {
  141. continue
  142. }
  143. priv = append(priv, tmpPriv[i])
  144. }
  145. for i := range tmpPub {
  146. if _, ok := ignore[tmpPub[i].String()]; ok {
  147. continue
  148. }
  149. pub = append(pub, tmpPub[i])
  150. }
  151. if len(priv) == 0 && len(pub) == 0 {
  152. return nil, nil, errors.New("no valid IP was found")
  153. }
  154. if len(priv) == 0 {
  155. // If no private IPs were found, use nil.
  156. priv = append(priv, nil)
  157. }
  158. if len(pub) == 0 {
  159. pub = priv
  160. }
  161. return priv[0], pub[0], nil
  162. }
  163. func assignedToInterface(ip *net.IPNet) (bool, net.IPMask, error) {
  164. links, err := netlink.LinkList()
  165. if err != nil {
  166. return false, nil, fmt.Errorf("failed to list interfaces: %v", err)
  167. }
  168. // Sort the links for stability.
  169. sort.Slice(links, func(i, j int) bool {
  170. return links[i].Attrs().Name < links[j].Attrs().Name
  171. })
  172. for _, link := range links {
  173. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  174. if err != nil {
  175. return false, nil, fmt.Errorf("failed to list addresses for %s: %v", link.Attrs().Name, err)
  176. }
  177. // Sort the IPs for stability.
  178. sort.Slice(addrs, func(i, j int) bool {
  179. return addrs[i].String() < addrs[j].String()
  180. })
  181. for i := range addrs {
  182. if ip.IP.Equal(addrs[i].IP) {
  183. return true, addrs[i].Mask, nil
  184. }
  185. }
  186. }
  187. return false, nil, nil
  188. }
  189. // ipsForHostname returns a slice of IPs to which the
  190. // given hostname resolves.
  191. func ipsForHostname(hostname string) []*net.IPNet {
  192. if ip := net.ParseIP(hostname); ip != nil {
  193. return []*net.IPNet{oneAddressCIDR(ip)}
  194. }
  195. ips, err := net.LookupIP(hostname)
  196. if err != nil {
  197. // Most likely the hostname is not resolvable.
  198. return nil
  199. }
  200. nets := make([]*net.IPNet, len(ips))
  201. for i := range ips {
  202. nets[i] = oneAddressCIDR(ips[i])
  203. }
  204. return nets
  205. }
  206. // ipsForAllInterfaces returns a slice of IPs assigned to all the
  207. // interfaces on the host.
  208. func ipsForAllInterfaces() ([]*net.IPNet, error) {
  209. ifaces, err := net.Interfaces()
  210. if err != nil {
  211. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  212. }
  213. var nets []*net.IPNet
  214. for _, iface := range ifaces {
  215. ips, err := ipsForInterface(&iface)
  216. if err != nil {
  217. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  218. }
  219. nets = append(nets, ips...)
  220. }
  221. return nets, nil
  222. }
  223. // ipsForInterface returns a slice of IPs assigned to the given interface.
  224. func ipsForInterface(iface *net.Interface) ([]*net.IPNet, error) {
  225. link, err := netlink.LinkByIndex(iface.Index)
  226. if err != nil {
  227. return nil, fmt.Errorf("failed to get link: %s", err)
  228. }
  229. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  230. if err != nil {
  231. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  232. }
  233. var ips []*net.IPNet
  234. for _, a := range addrs {
  235. if a.IPNet != nil {
  236. ips = append(ips, a.IPNet)
  237. }
  238. }
  239. return ips, nil
  240. }
  241. // interfacesForIP returns a slice of interfaces withthe given IP.
  242. func interfacesForIP(ip *net.IPNet) ([]net.Interface, error) {
  243. ifaces, err := net.Interfaces()
  244. if err != nil {
  245. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  246. }
  247. var interfaces []net.Interface
  248. for _, iface := range ifaces {
  249. ips, err := ipsForInterface(&iface)
  250. if err != nil {
  251. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  252. }
  253. for i := range ips {
  254. if ip.IP.Equal(ips[i].IP) {
  255. interfaces = append(interfaces, iface)
  256. break
  257. }
  258. }
  259. }
  260. if len(interfaces) == 0 {
  261. return nil, fmt.Errorf("no interface has %s assigned", ip.String())
  262. }
  263. return interfaces, nil
  264. }
  265. // defaultInterface returns the interface for the default route of the host.
  266. func defaultInterface() (*net.Interface, error) {
  267. routes, err := netlink.RouteList(nil, netlink.FAMILY_ALL)
  268. if err != nil {
  269. return nil, err
  270. }
  271. for _, route := range routes {
  272. if route.Dst == nil || route.Dst.String() == "0.0.0.0/0" || route.Dst.String() == "::/0" {
  273. if route.LinkIndex <= 0 {
  274. return nil, errors.New("failed to determine interface of route")
  275. }
  276. return net.InterfaceByIndex(route.LinkIndex)
  277. }
  278. }
  279. return nil, errors.New("failed to find default route")
  280. }
  281. // isInCIDRs checks if the given IP is within any of the provided CIDRs.
  282. func isInCIDRs(ip net.IP, cidrs []*net.IPNet) bool {
  283. for _, cidr := range cidrs {
  284. if cidr.Contains(ip) {
  285. return true
  286. }
  287. }
  288. return false
  289. }