discoverips.go 7.6 KB

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