ip.go 8.8 KB

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