discoverips.go 7.7 KB

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