ip.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. package mesh
  15. import (
  16. "errors"
  17. "fmt"
  18. "net"
  19. "sort"
  20. "github.com/vishvananda/netlink"
  21. )
  22. // getIP returns a private and public IP address for the local node.
  23. // It selects the private IP address in the following order:
  24. // - private IP to which hostname resolves
  25. // - private IP assigned to interface of default route
  26. // - private IP assigned to local interface
  27. // - public IP to which hostname resolves
  28. // - public IP assigned to interface of default route
  29. // - public IP assigned to local interface
  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. ip.Mask = mask
  71. if isPublic(ip.IP) {
  72. hostPub = append(hostPub, ip)
  73. continue
  74. }
  75. hostPriv = append(hostPriv, ip)
  76. }
  77. sortIPs(hostPriv)
  78. sortIPs(hostPub)
  79. }
  80. var defaultPriv, defaultPub []*net.IPNet
  81. {
  82. // Check IPs on interface for default route next.
  83. iface, err := defaultInterface()
  84. if err != nil {
  85. return nil, nil, err
  86. }
  87. ips, err := ipsForInterface(iface)
  88. if err != nil {
  89. return nil, nil, err
  90. }
  91. for _, ip := range ips {
  92. if isLocal(ip.IP) {
  93. continue
  94. }
  95. if isPublic(ip.IP) {
  96. defaultPub = append(defaultPub, ip)
  97. continue
  98. }
  99. defaultPriv = append(defaultPriv, ip)
  100. }
  101. sortIPs(defaultPriv)
  102. sortIPs(defaultPub)
  103. }
  104. var interfacePriv, interfacePub []*net.IPNet
  105. {
  106. // Finally look for IPs on all interfaces.
  107. ips, err := ipsForAllInterfaces()
  108. if err != nil {
  109. return nil, nil, err
  110. }
  111. for _, ip := range ips {
  112. if isLocal(ip.IP) {
  113. continue
  114. }
  115. if isPublic(ip.IP) {
  116. interfacePub = append(interfacePub, ip)
  117. continue
  118. }
  119. interfacePriv = append(interfacePriv, ip)
  120. }
  121. sortIPs(interfacePriv)
  122. sortIPs(interfacePub)
  123. }
  124. var priv, pub, tmpPriv, tmpPub []*net.IPNet
  125. tmpPriv = append(tmpPriv, hostPriv...)
  126. tmpPriv = append(tmpPriv, defaultPriv...)
  127. tmpPriv = append(tmpPriv, interfacePriv...)
  128. tmpPub = append(tmpPub, hostPub...)
  129. tmpPub = append(tmpPub, defaultPub...)
  130. tmpPub = append(tmpPub, interfacePub...)
  131. for i := range tmpPriv {
  132. if _, ok := ignore[tmpPriv[i].String()]; ok {
  133. continue
  134. }
  135. priv = append(priv, tmpPriv[i])
  136. }
  137. for i := range tmpPub {
  138. if _, ok := ignore[tmpPub[i].String()]; ok {
  139. continue
  140. }
  141. pub = append(pub, tmpPub[i])
  142. }
  143. if len(priv) == 0 && len(pub) == 0 {
  144. return nil, nil, errors.New("no valid IP was found")
  145. }
  146. if len(priv) == 0 {
  147. priv = pub
  148. }
  149. if len(pub) == 0 {
  150. pub = priv
  151. }
  152. return priv[0], pub[0], nil
  153. }
  154. // sortIPs sorts IPs so the result is stable.
  155. // It will first sort IPs by type, to prefer selecting
  156. // IPs of the same type, and then by value.
  157. func sortIPs(ips []*net.IPNet) {
  158. sort.Slice(ips, func(i, j int) bool {
  159. i4, j4 := ips[i].IP.To4(), ips[j].IP.To4()
  160. if i4 != nil && j4 == nil {
  161. return true
  162. }
  163. if j4 != nil && i4 == nil {
  164. return false
  165. }
  166. return ips[i].String() < ips[j].String()
  167. })
  168. }
  169. func assignedToInterface(ip *net.IPNet) (bool, net.IPMask, error) {
  170. links, err := netlink.LinkList()
  171. if err != nil {
  172. return false, nil, fmt.Errorf("failed to list interfaces: %v", err)
  173. }
  174. // Sort the links for stability.
  175. sort.Slice(links, func(i, j int) bool {
  176. return links[i].Attrs().Name < links[j].Attrs().Name
  177. })
  178. for _, link := range links {
  179. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  180. if err != nil {
  181. return false, nil, fmt.Errorf("failed to list addresses for %s: %v", link.Attrs().Name, err)
  182. }
  183. // Sort the IPs for stability.
  184. sort.Slice(addrs, func(i, j int) bool {
  185. return addrs[i].String() < addrs[j].String()
  186. })
  187. for i := range addrs {
  188. if ip.IP.Equal(addrs[i].IP) {
  189. return true, addrs[i].Mask, nil
  190. }
  191. }
  192. }
  193. return false, nil, nil
  194. }
  195. func isLocal(ip net.IP) bool {
  196. return ip.IsLoopback() || ip.IsLinkLocalMulticast() || ip.IsLinkLocalUnicast()
  197. }
  198. func isPublic(ip net.IP) bool {
  199. // Check RFC 1918 addresses.
  200. if ip4 := ip.To4(); ip4 != nil {
  201. switch true {
  202. // Check for 10.0.0.0/8.
  203. case ip4[0] == 10:
  204. return false
  205. // Check for 172.16.0.0/12.
  206. case ip4[0] == 172 && ip4[1]&0xf0 == 0x01:
  207. return false
  208. // Check for 192.168.0.0/16.
  209. case ip4[0] == 192 && ip4[1] == 168:
  210. return false
  211. default:
  212. return true
  213. }
  214. }
  215. // Check RFC 4193 addresses.
  216. if len(ip) == net.IPv6len {
  217. switch true {
  218. // Check for fd00::/8.
  219. case ip[0] == 0xfd && ip[1] == 0x00:
  220. return false
  221. default:
  222. return true
  223. }
  224. }
  225. return false
  226. }
  227. // ipsForHostname returns a slice of IPs to which the
  228. // given hostname resolves.
  229. func ipsForHostname(hostname string) []*net.IPNet {
  230. if ip := net.ParseIP(hostname); ip != nil {
  231. return []*net.IPNet{oneAddressCIDR(ip)}
  232. }
  233. ips, err := net.LookupIP(hostname)
  234. if err != nil {
  235. // Most likely the hostname is not resolvable.
  236. return nil
  237. }
  238. nets := make([]*net.IPNet, len(ips))
  239. for i := range ips {
  240. nets[i] = oneAddressCIDR(ips[i])
  241. }
  242. return nets
  243. }
  244. // ipsForAllInterfaces returns a slice of IPs assigned to all the
  245. // interfaces on the host.
  246. func ipsForAllInterfaces() ([]*net.IPNet, error) {
  247. ifaces, err := net.Interfaces()
  248. if err != nil {
  249. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  250. }
  251. var nets []*net.IPNet
  252. for _, iface := range ifaces {
  253. ips, err := ipsForInterface(&iface)
  254. if err != nil {
  255. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  256. }
  257. nets = append(nets, ips...)
  258. }
  259. return nets, nil
  260. }
  261. // ipsForInterface returns a slice of IPs assigned to the given interface.
  262. func ipsForInterface(iface *net.Interface) ([]*net.IPNet, error) {
  263. link, err := netlink.LinkByIndex(iface.Index)
  264. if err != nil {
  265. return nil, fmt.Errorf("failed to get link: %s", err)
  266. }
  267. addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  268. if err != nil {
  269. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  270. }
  271. var ips []*net.IPNet
  272. for _, a := range addrs {
  273. if a.IPNet != nil {
  274. ips = append(ips, a.IPNet)
  275. }
  276. }
  277. return ips, nil
  278. }
  279. // interfacesForIP returns a slice of interfaces withthe given IP.
  280. func interfacesForIP(ip *net.IPNet) ([]net.Interface, error) {
  281. ifaces, err := net.Interfaces()
  282. if err != nil {
  283. return nil, fmt.Errorf("failed to list interfaces: %v", err)
  284. }
  285. var interfaces []net.Interface
  286. for _, iface := range ifaces {
  287. ips, err := ipsForInterface(&iface)
  288. if err != nil {
  289. return nil, fmt.Errorf("failed to list addresses for %s: %v", iface.Name, err)
  290. }
  291. for i := range ips {
  292. if ip.IP.Equal(ips[i].IP) {
  293. interfaces = append(interfaces, iface)
  294. break
  295. }
  296. }
  297. }
  298. if len(interfaces) == 0 {
  299. return nil, fmt.Errorf("no interface has %s assigned", ip.String())
  300. }
  301. return interfaces, nil
  302. }
  303. // defaultInterface returns the interface for the default route of the host.
  304. func defaultInterface() (*net.Interface, error) {
  305. routes, err := netlink.RouteList(nil, netlink.FAMILY_ALL)
  306. if err != nil {
  307. return nil, err
  308. }
  309. for _, route := range routes {
  310. if route.Dst == nil || route.Dst.String() == "0.0.0.0/0" || route.Dst.String() == "::/0" {
  311. if route.LinkIndex <= 0 {
  312. return nil, errors.New("failed to determine interface of route")
  313. }
  314. return net.InterfaceByIndex(route.LinkIndex)
  315. }
  316. }
  317. return nil, errors.New("failed to find default route")
  318. }
  319. type allocator struct {
  320. bits int
  321. ones int
  322. cidr *net.IPNet
  323. current net.IP
  324. }
  325. func newAllocator(cidr net.IPNet) *allocator {
  326. ones, bits := cidr.Mask.Size()
  327. current := make(net.IP, len(cidr.IP))
  328. copy(current, cidr.IP)
  329. if ip4 := current.To4(); ip4 != nil {
  330. current = ip4
  331. }
  332. return &allocator{
  333. bits: bits,
  334. ones: ones,
  335. cidr: &cidr,
  336. current: current,
  337. }
  338. }
  339. func (a *allocator) next() *net.IPNet {
  340. if a.current == nil {
  341. return nil
  342. }
  343. for i := len(a.current) - 1; i >= 0; i-- {
  344. a.current[i]++
  345. // if we haven't overflowed, then we can exit.
  346. if a.current[i] != 0 {
  347. break
  348. }
  349. }
  350. if !a.cidr.Contains(a.current) {
  351. a.current = nil
  352. }
  353. ip := make(net.IP, len(a.current))
  354. copy(ip, a.current)
  355. return &net.IPNet{IP: ip, Mask: net.CIDRMask(a.ones, a.bits)}
  356. }