routes_linux.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright 2016 The etcd 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 netutil
  16. import (
  17. "bytes"
  18. "encoding/binary"
  19. "fmt"
  20. "net"
  21. "sort"
  22. "syscall"
  23. "go.etcd.io/etcd/pkg/cpuutil"
  24. )
  25. var errNoDefaultRoute = fmt.Errorf("could not find default route")
  26. var errNoDefaultHost = fmt.Errorf("could not find default host")
  27. var errNoDefaultInterface = fmt.Errorf("could not find default interface")
  28. // GetDefaultHost obtains the first IP address of machine from the routing table and returns the IP address as string.
  29. // An IPv4 address is preferred to an IPv6 address for backward compatibility.
  30. func GetDefaultHost() (string, error) {
  31. rmsgs, rerr := getDefaultRoutes()
  32. if rerr != nil {
  33. return "", rerr
  34. }
  35. // prioritize IPv4
  36. if rmsg, ok := rmsgs[syscall.AF_INET]; ok {
  37. if host, err := chooseHost(syscall.AF_INET, rmsg); host != "" || err != nil {
  38. return host, err
  39. }
  40. delete(rmsgs, syscall.AF_INET)
  41. }
  42. // sort so choice is deterministic
  43. var families []int
  44. for family := range rmsgs {
  45. families = append(families, int(family))
  46. }
  47. sort.Ints(families)
  48. for _, f := range families {
  49. family := uint8(f)
  50. if host, err := chooseHost(family, rmsgs[family]); host != "" || err != nil {
  51. return host, err
  52. }
  53. }
  54. return "", errNoDefaultHost
  55. }
  56. func chooseHost(family uint8, rmsg *syscall.NetlinkMessage) (string, error) {
  57. host, oif, err := parsePREFSRC(rmsg)
  58. if host != "" || err != nil {
  59. return host, err
  60. }
  61. // prefsrc not detected, fall back to getting address from iface
  62. ifmsg, ierr := getIfaceAddr(oif, family)
  63. if ierr != nil {
  64. return "", ierr
  65. }
  66. attrs, aerr := syscall.ParseNetlinkRouteAttr(ifmsg)
  67. if aerr != nil {
  68. return "", aerr
  69. }
  70. for _, attr := range attrs {
  71. // search for RTA_DST because ipv6 doesn't have RTA_SRC
  72. if attr.Attr.Type == syscall.RTA_DST {
  73. return net.IP(attr.Value).String(), nil
  74. }
  75. }
  76. return "", nil
  77. }
  78. func getDefaultRoutes() (map[uint8]*syscall.NetlinkMessage, error) {
  79. dat, err := syscall.NetlinkRIB(syscall.RTM_GETROUTE, syscall.AF_UNSPEC)
  80. if err != nil {
  81. return nil, err
  82. }
  83. msgs, msgErr := syscall.ParseNetlinkMessage(dat)
  84. if msgErr != nil {
  85. return nil, msgErr
  86. }
  87. routes := make(map[uint8]*syscall.NetlinkMessage)
  88. rtmsg := syscall.RtMsg{}
  89. for _, m := range msgs {
  90. if m.Header.Type != syscall.RTM_NEWROUTE {
  91. continue
  92. }
  93. buf := bytes.NewBuffer(m.Data[:syscall.SizeofRtMsg])
  94. if rerr := binary.Read(buf, cpuutil.ByteOrder(), &rtmsg); rerr != nil {
  95. continue
  96. }
  97. if rtmsg.Dst_len == 0 && rtmsg.Table == syscall.RT_TABLE_MAIN {
  98. // zero-length Dst_len implies default route
  99. msg := m
  100. routes[rtmsg.Family] = &msg
  101. }
  102. }
  103. if len(routes) > 0 {
  104. return routes, nil
  105. }
  106. return nil, errNoDefaultRoute
  107. }
  108. // Used to get an address of interface.
  109. func getIfaceAddr(idx uint32, family uint8) (*syscall.NetlinkMessage, error) {
  110. dat, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, int(family))
  111. if err != nil {
  112. return nil, err
  113. }
  114. msgs, msgErr := syscall.ParseNetlinkMessage(dat)
  115. if msgErr != nil {
  116. return nil, msgErr
  117. }
  118. ifaddrmsg := syscall.IfAddrmsg{}
  119. for _, m := range msgs {
  120. if m.Header.Type != syscall.RTM_NEWADDR {
  121. continue
  122. }
  123. buf := bytes.NewBuffer(m.Data[:syscall.SizeofIfAddrmsg])
  124. if rerr := binary.Read(buf, cpuutil.ByteOrder(), &ifaddrmsg); rerr != nil {
  125. continue
  126. }
  127. if ifaddrmsg.Index == idx {
  128. return &m, nil
  129. }
  130. }
  131. return nil, fmt.Errorf("could not find address for interface index %v", idx)
  132. }
  133. // Used to get a name of interface.
  134. func getIfaceLink(idx uint32) (*syscall.NetlinkMessage, error) {
  135. dat, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC)
  136. if err != nil {
  137. return nil, err
  138. }
  139. msgs, msgErr := syscall.ParseNetlinkMessage(dat)
  140. if msgErr != nil {
  141. return nil, msgErr
  142. }
  143. ifinfomsg := syscall.IfInfomsg{}
  144. for _, m := range msgs {
  145. if m.Header.Type != syscall.RTM_NEWLINK {
  146. continue
  147. }
  148. buf := bytes.NewBuffer(m.Data[:syscall.SizeofIfInfomsg])
  149. if rerr := binary.Read(buf, cpuutil.ByteOrder(), &ifinfomsg); rerr != nil {
  150. continue
  151. }
  152. if ifinfomsg.Index == int32(idx) {
  153. return &m, nil
  154. }
  155. }
  156. return nil, fmt.Errorf("could not find link for interface index %v", idx)
  157. }
  158. // GetDefaultInterfaces gets names of interfaces and returns a map[interface]families.
  159. func GetDefaultInterfaces() (map[string]uint8, error) {
  160. interfaces := make(map[string]uint8)
  161. rmsgs, rerr := getDefaultRoutes()
  162. if rerr != nil {
  163. return interfaces, rerr
  164. }
  165. for family, rmsg := range rmsgs {
  166. _, oif, err := parsePREFSRC(rmsg)
  167. if err != nil {
  168. return interfaces, err
  169. }
  170. ifmsg, ierr := getIfaceLink(oif)
  171. if ierr != nil {
  172. return interfaces, ierr
  173. }
  174. attrs, aerr := syscall.ParseNetlinkRouteAttr(ifmsg)
  175. if aerr != nil {
  176. return interfaces, aerr
  177. }
  178. for _, attr := range attrs {
  179. if attr.Attr.Type == syscall.IFLA_IFNAME {
  180. // key is an interface name
  181. // possible values: 2 - AF_INET, 10 - AF_INET6, 12 - dualstack
  182. interfaces[string(attr.Value[:len(attr.Value)-1])] += family
  183. }
  184. }
  185. }
  186. if len(interfaces) > 0 {
  187. return interfaces, nil
  188. }
  189. return interfaces, errNoDefaultInterface
  190. }
  191. // parsePREFSRC returns preferred source address and output interface index (RTA_OIF).
  192. func parsePREFSRC(m *syscall.NetlinkMessage) (host string, oif uint32, err error) {
  193. var attrs []syscall.NetlinkRouteAttr
  194. attrs, err = syscall.ParseNetlinkRouteAttr(m)
  195. if err != nil {
  196. return "", 0, err
  197. }
  198. for _, attr := range attrs {
  199. if attr.Attr.Type == syscall.RTA_PREFSRC {
  200. host = net.IP(attr.Value).String()
  201. }
  202. if attr.Attr.Type == syscall.RTA_OIF {
  203. oif = cpuutil.ByteOrder().Uint32(attr.Value)
  204. }
  205. if host != "" && oif != uint32(0) {
  206. break
  207. }
  208. }
  209. if oif == 0 {
  210. err = errNoDefaultRoute
  211. }
  212. return host, oif, err
  213. }