discoverips.go 7.7 KB

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