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