link.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. package rtnetlink
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "github.com/jsimonetti/rtnetlink/internal/unix"
  7. "github.com/mdlayher/netlink"
  8. )
  9. var (
  10. // errInvalidLinkMessage is returned when a LinkMessage is malformed.
  11. errInvalidLinkMessage = errors.New("rtnetlink LinkMessage is invalid or too short")
  12. // errInvalidLinkMessageAttr is returned when link attributes are malformed.
  13. errInvalidLinkMessageAttr = errors.New("rtnetlink LinkMessage has a wrong attribute data length")
  14. )
  15. var _ Message = &LinkMessage{}
  16. // A LinkMessage is a route netlink link message.
  17. type LinkMessage struct {
  18. // Always set to AF_UNSPEC (0)
  19. Family uint16
  20. // Device Type
  21. Type uint16
  22. // Unique interface index, using a nonzero value with
  23. // NewLink will instruct the kernel to create a
  24. // device with the given index (kernel 3.7+ required)
  25. Index uint32
  26. // Contains device flags, see netdevice(7)
  27. Flags uint32
  28. // Change Flags, specifies which flags will be affected by the Flags field
  29. Change uint32
  30. // Attributes List
  31. Attributes *LinkAttributes
  32. }
  33. // MarshalBinary marshals a LinkMessage into a byte slice.
  34. func (m *LinkMessage) MarshalBinary() ([]byte, error) {
  35. b := make([]byte, unix.SizeofIfInfomsg)
  36. b[0] = 0 // Family
  37. b[1] = 0 // reserved
  38. nativeEndian.PutUint16(b[2:4], m.Type)
  39. nativeEndian.PutUint32(b[4:8], m.Index)
  40. nativeEndian.PutUint32(b[8:12], m.Flags)
  41. nativeEndian.PutUint32(b[12:16], m.Change)
  42. if m.Attributes != nil {
  43. ae := netlink.NewAttributeEncoder()
  44. ae.ByteOrder = nativeEndian
  45. err := m.Attributes.encode(ae)
  46. if err != nil {
  47. return nil, err
  48. }
  49. a, err := ae.Encode()
  50. if err != nil {
  51. return nil, err
  52. }
  53. return append(b, a...), nil
  54. }
  55. return b, nil
  56. }
  57. // UnmarshalBinary unmarshals the contents of a byte slice into a LinkMessage.
  58. func (m *LinkMessage) UnmarshalBinary(b []byte) error {
  59. l := len(b)
  60. if l < unix.SizeofIfInfomsg {
  61. return errInvalidLinkMessage
  62. }
  63. m.Family = nativeEndian.Uint16(b[0:2])
  64. m.Type = nativeEndian.Uint16(b[2:4])
  65. m.Index = nativeEndian.Uint32(b[4:8])
  66. m.Flags = nativeEndian.Uint32(b[8:12])
  67. m.Change = nativeEndian.Uint32(b[12:16])
  68. if l > unix.SizeofIfInfomsg {
  69. m.Attributes = &LinkAttributes{}
  70. ad, err := netlink.NewAttributeDecoder(b[16:])
  71. if err != nil {
  72. return err
  73. }
  74. ad.ByteOrder = nativeEndian
  75. err = m.Attributes.decode(ad)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. return nil
  81. }
  82. // rtMessage is an empty method to sattisfy the Message interface.
  83. func (*LinkMessage) rtMessage() {}
  84. // LinkService is used to retrieve rtnetlink family information.
  85. type LinkService struct {
  86. c *Conn
  87. }
  88. // execute executes the request and returns the messages as a LinkMessage slice
  89. func (l *LinkService) execute(m Message, family uint16, flags netlink.HeaderFlags) ([]LinkMessage, error) {
  90. msgs, err := l.c.Execute(m, family, flags)
  91. links := make([]LinkMessage, len(msgs))
  92. for i := range msgs {
  93. links[i] = *msgs[i].(*LinkMessage)
  94. }
  95. return links, err
  96. }
  97. // New creates a new interface using the LinkMessage information.
  98. func (l *LinkService) New(req *LinkMessage) error {
  99. flags := netlink.Request | netlink.Create | netlink.Acknowledge | netlink.Excl
  100. _, err := l.execute(req, unix.RTM_NEWLINK, flags)
  101. return err
  102. }
  103. // Delete removes an interface by index.
  104. func (l *LinkService) Delete(index uint32) error {
  105. req := &LinkMessage{
  106. Index: index,
  107. }
  108. flags := netlink.Request | netlink.Acknowledge
  109. _, err := l.c.Execute(req, unix.RTM_DELLINK, flags)
  110. return err
  111. }
  112. // Get retrieves interface information by index.
  113. func (l *LinkService) Get(index uint32) (LinkMessage, error) {
  114. req := &LinkMessage{
  115. Index: index,
  116. }
  117. flags := netlink.Request | netlink.DumpFiltered
  118. links, err := l.execute(req, unix.RTM_GETLINK, flags)
  119. if len(links) != 1 {
  120. return LinkMessage{}, fmt.Errorf("too many/little matches, expected 1, actual %d", len(links))
  121. }
  122. return links[0], err
  123. }
  124. // Set sets interface attributes according to the LinkMessage information.
  125. //
  126. // ref: https://lwn.net/Articles/236919/
  127. // We explicitly use RTM_NEWLINK to set link attributes instead of
  128. // RTM_SETLINK because:
  129. // - using RTM_SETLINK is actually an old rtnetlink API, not supporting most
  130. // attributes common today
  131. // - using RTM_NEWLINK is the prefered way to create AND update links
  132. // - RTM_NEWLINK is backward compatible to RTM_SETLINK
  133. func (l *LinkService) Set(req *LinkMessage) error {
  134. flags := netlink.Request | netlink.Acknowledge
  135. _, err := l.c.Execute(req, unix.RTM_NEWLINK, flags)
  136. return err
  137. }
  138. func (l *LinkService) list(kind string) ([]LinkMessage, error) {
  139. req := &LinkMessage{}
  140. if kind != "" {
  141. req.Attributes = &LinkAttributes{
  142. Info: &LinkInfo{Kind: kind},
  143. }
  144. }
  145. flags := netlink.Request | netlink.Dump
  146. return l.execute(req, unix.RTM_GETLINK, flags)
  147. }
  148. // ListByKind retrieves all interfaces of a specific kind.
  149. func (l *LinkService) ListByKind(kind string) ([]LinkMessage, error) {
  150. return l.list(kind)
  151. }
  152. // List retrieves all interfaces.
  153. func (l *LinkService) List() ([]LinkMessage, error) {
  154. return l.list("")
  155. }
  156. // LinkAttributes contains all attributes for an interface.
  157. type LinkAttributes struct {
  158. Address net.HardwareAddr // Interface L2 address
  159. Broadcast net.HardwareAddr // L2 broadcast address
  160. Name string // Device name
  161. MTU uint32 // MTU of the device
  162. Type uint32 // Link type
  163. QueueDisc string // Queueing discipline
  164. Master *uint32 // Master device index (0 value un-enslaves)
  165. OperationalState OperationalState // Interface operation state
  166. Stats *LinkStats // Interface Statistics
  167. Stats64 *LinkStats64 // Interface Statistics (64 bits version)
  168. Info *LinkInfo // Detailed Interface Information
  169. XDP *LinkXDP // Express Data Patch Information
  170. }
  171. // OperationalState represents an interface's operational state.
  172. type OperationalState uint8
  173. // Constants that represent operational state of an interface
  174. //
  175. // Adapted from https://elixir.bootlin.com/linux/v4.19.2/source/include/uapi/linux/if.h#L166
  176. const (
  177. OperStateUnknown OperationalState = iota // status could not be determined
  178. OperStateNotPresent // down, due to some missing component (typically hardware)
  179. OperStateDown // down, either administratively or due to a fault
  180. OperStateLowerLayerDown // down, due to lower-layer interfaces
  181. OperStateTesting // operationally down, in some test mode
  182. OperStateDormant // down, waiting for some external event
  183. OperStateUp // interface is in a state to send and receive packets
  184. )
  185. // unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage.
  186. func (a *LinkAttributes) decode(ad *netlink.AttributeDecoder) error {
  187. for ad.Next() {
  188. switch ad.Type() {
  189. case unix.IFLA_UNSPEC:
  190. // unused attribute
  191. case unix.IFLA_ADDRESS:
  192. l := len(ad.Bytes())
  193. if l < 4 || l > 32 {
  194. return errInvalidLinkMessageAttr
  195. }
  196. a.Address = ad.Bytes()
  197. case unix.IFLA_BROADCAST:
  198. l := len(ad.Bytes())
  199. if l < 4 || l > 32 {
  200. return errInvalidLinkMessageAttr
  201. }
  202. a.Broadcast = ad.Bytes()
  203. case unix.IFLA_IFNAME:
  204. a.Name = ad.String()
  205. case unix.IFLA_MTU:
  206. a.MTU = ad.Uint32()
  207. case unix.IFLA_LINK:
  208. a.Type = ad.Uint32()
  209. case unix.IFLA_QDISC:
  210. a.QueueDisc = ad.String()
  211. case unix.IFLA_OPERSTATE:
  212. a.OperationalState = OperationalState(ad.Uint8())
  213. case unix.IFLA_STATS:
  214. a.Stats = &LinkStats{}
  215. err := a.Stats.unmarshalBinary(ad.Bytes())
  216. if err != nil {
  217. return err
  218. }
  219. case unix.IFLA_STATS64:
  220. a.Stats64 = &LinkStats64{}
  221. err := a.Stats64.unmarshalBinary(ad.Bytes())
  222. if err != nil {
  223. return err
  224. }
  225. case unix.IFLA_LINKINFO:
  226. a.Info = &LinkInfo{}
  227. ad.Nested(a.Info.decode)
  228. case unix.IFLA_MASTER:
  229. v := ad.Uint32()
  230. a.Master = &v
  231. case unix.IFLA_XDP:
  232. a.XDP = &LinkXDP{}
  233. ad.Nested(a.XDP.decode)
  234. }
  235. }
  236. return nil
  237. }
  238. // MarshalBinary marshals a LinkAttributes into a byte slice.
  239. func (a *LinkAttributes) encode(ae *netlink.AttributeEncoder) error {
  240. ae.Uint16(unix.IFLA_UNSPEC, 0)
  241. ae.String(unix.IFLA_IFNAME, a.Name)
  242. ae.Uint32(unix.IFLA_LINK, a.Type)
  243. ae.String(unix.IFLA_QDISC, a.QueueDisc)
  244. if a.MTU != 0 {
  245. ae.Uint32(unix.IFLA_MTU, a.MTU)
  246. }
  247. if len(a.Address) != 0 {
  248. ae.Bytes(unix.IFLA_ADDRESS, a.Address)
  249. }
  250. if len(a.Broadcast) != 0 {
  251. ae.Bytes(unix.IFLA_BROADCAST, a.Broadcast)
  252. }
  253. if a.OperationalState != OperStateUnknown {
  254. ae.Uint8(unix.IFLA_OPERSTATE, uint8(a.OperationalState))
  255. }
  256. if a.Info != nil {
  257. nae := netlink.NewAttributeEncoder()
  258. nae.ByteOrder = ae.ByteOrder
  259. err := a.Info.encode(nae)
  260. if err != nil {
  261. return err
  262. }
  263. b, err := nae.Encode()
  264. if err != nil {
  265. return err
  266. }
  267. ae.Bytes(unix.IFLA_LINKINFO, b)
  268. }
  269. if a.XDP != nil {
  270. nae := netlink.NewAttributeEncoder()
  271. nae.ByteOrder = ae.ByteOrder
  272. err := a.XDP.encode(nae)
  273. if err != nil {
  274. return err
  275. }
  276. b, err := nae.Encode()
  277. if err != nil {
  278. return err
  279. }
  280. ae.Bytes(unix.IFLA_XDP, b)
  281. }
  282. if a.Master != nil {
  283. ae.Uint32(unix.IFLA_MASTER, *a.Master)
  284. }
  285. return nil
  286. }
  287. // LinkStats contains packet statistics
  288. type LinkStats struct {
  289. RXPackets uint32 // total packets received
  290. TXPackets uint32 // total packets transmitted
  291. RXBytes uint32 // total bytes received
  292. TXBytes uint32 // total bytes transmitted
  293. RXErrors uint32 // bad packets received
  294. TXErrors uint32 // packet transmit problems
  295. RXDropped uint32 // no space in linux buffers
  296. TXDropped uint32 // no space available in linux
  297. Multicast uint32 // multicast packets received
  298. Collisions uint32
  299. // detailed rx_errors:
  300. RXLengthErrors uint32
  301. RXOverErrors uint32 // receiver ring buff overflow
  302. RXCRCErrors uint32 // recved pkt with crc error
  303. RXFrameErrors uint32 // recv'd frame alignment error
  304. RXFIFOErrors uint32 // recv'r fifo overrun
  305. RXMissedErrors uint32 // receiver missed packet
  306. // detailed tx_errors
  307. TXAbortedErrors uint32
  308. TXCarrierErrors uint32
  309. TXFIFOErrors uint32
  310. TXHeartbeatErrors uint32
  311. TXWindowErrors uint32
  312. // for cslip etc
  313. RXCompressed uint32
  314. TXCompressed uint32
  315. RXNoHandler uint32 // dropped, no handler found
  316. }
  317. // unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage.
  318. func (a *LinkStats) unmarshalBinary(b []byte) error {
  319. l := len(b)
  320. if l != 92 && l != 96 {
  321. return fmt.Errorf("incorrect size, want: 92 or 96")
  322. }
  323. a.RXPackets = nativeEndian.Uint32(b[0:4])
  324. a.TXPackets = nativeEndian.Uint32(b[4:8])
  325. a.RXBytes = nativeEndian.Uint32(b[8:12])
  326. a.TXBytes = nativeEndian.Uint32(b[12:16])
  327. a.RXErrors = nativeEndian.Uint32(b[16:20])
  328. a.TXErrors = nativeEndian.Uint32(b[20:24])
  329. a.RXDropped = nativeEndian.Uint32(b[24:28])
  330. a.TXDropped = nativeEndian.Uint32(b[28:32])
  331. a.Multicast = nativeEndian.Uint32(b[32:36])
  332. a.Collisions = nativeEndian.Uint32(b[36:40])
  333. a.RXLengthErrors = nativeEndian.Uint32(b[40:44])
  334. a.RXOverErrors = nativeEndian.Uint32(b[44:48])
  335. a.RXCRCErrors = nativeEndian.Uint32(b[48:52])
  336. a.RXFrameErrors = nativeEndian.Uint32(b[52:56])
  337. a.RXFIFOErrors = nativeEndian.Uint32(b[56:60])
  338. a.RXMissedErrors = nativeEndian.Uint32(b[60:64])
  339. a.TXAbortedErrors = nativeEndian.Uint32(b[64:68])
  340. a.TXCarrierErrors = nativeEndian.Uint32(b[68:72])
  341. a.TXFIFOErrors = nativeEndian.Uint32(b[72:76])
  342. a.TXHeartbeatErrors = nativeEndian.Uint32(b[76:80])
  343. a.TXWindowErrors = nativeEndian.Uint32(b[80:84])
  344. a.RXCompressed = nativeEndian.Uint32(b[84:88])
  345. a.TXCompressed = nativeEndian.Uint32(b[88:92])
  346. if l == 96 {
  347. a.RXNoHandler = nativeEndian.Uint32(b[92:96])
  348. }
  349. return nil
  350. }
  351. // LinkStats64 contains packet statistics
  352. type LinkStats64 struct {
  353. RXPackets uint64 // total packets received
  354. TXPackets uint64 // total packets transmitted
  355. RXBytes uint64 // total bytes received
  356. TXBytes uint64 // total bytes transmitted
  357. RXErrors uint64 // bad packets received
  358. TXErrors uint64 // packet transmit problems
  359. RXDropped uint64 // no space in linux buffers
  360. TXDropped uint64 // no space available in linux
  361. Multicast uint64 // multicast packets received
  362. Collisions uint64
  363. // detailed rx_errors:
  364. RXLengthErrors uint64
  365. RXOverErrors uint64 // receiver ring buff overflow
  366. RXCRCErrors uint64 // recved pkt with crc error
  367. RXFrameErrors uint64 // recv'd frame alignment error
  368. RXFIFOErrors uint64 // recv'r fifo overrun
  369. RXMissedErrors uint64 // receiver missed packet
  370. // detailed tx_errors
  371. TXAbortedErrors uint64
  372. TXCarrierErrors uint64
  373. TXFIFOErrors uint64
  374. TXHeartbeatErrors uint64
  375. TXWindowErrors uint64
  376. // for cslip etc
  377. RXCompressed uint64
  378. TXCompressed uint64
  379. RXNoHandler uint64 // dropped, no handler found
  380. }
  381. // unmarshalBinary unmarshals the contents of a byte slice into a LinkMessage.
  382. func (a *LinkStats64) unmarshalBinary(b []byte) error {
  383. l := len(b)
  384. if l != 184 && l != 192 {
  385. return fmt.Errorf("incorrect size, want: 184 or 192")
  386. }
  387. a.RXPackets = nativeEndian.Uint64(b[0:8])
  388. a.TXPackets = nativeEndian.Uint64(b[8:16])
  389. a.RXBytes = nativeEndian.Uint64(b[16:24])
  390. a.TXBytes = nativeEndian.Uint64(b[24:32])
  391. a.RXErrors = nativeEndian.Uint64(b[32:40])
  392. a.TXErrors = nativeEndian.Uint64(b[40:48])
  393. a.RXDropped = nativeEndian.Uint64(b[48:56])
  394. a.TXDropped = nativeEndian.Uint64(b[56:64])
  395. a.Multicast = nativeEndian.Uint64(b[64:72])
  396. a.Collisions = nativeEndian.Uint64(b[72:80])
  397. a.RXLengthErrors = nativeEndian.Uint64(b[80:88])
  398. a.RXOverErrors = nativeEndian.Uint64(b[88:96])
  399. a.RXCRCErrors = nativeEndian.Uint64(b[96:104])
  400. a.RXFrameErrors = nativeEndian.Uint64(b[104:112])
  401. a.RXFIFOErrors = nativeEndian.Uint64(b[112:120])
  402. a.RXMissedErrors = nativeEndian.Uint64(b[120:128])
  403. a.TXAbortedErrors = nativeEndian.Uint64(b[128:136])
  404. a.TXCarrierErrors = nativeEndian.Uint64(b[136:144])
  405. a.TXFIFOErrors = nativeEndian.Uint64(b[144:152])
  406. a.TXHeartbeatErrors = nativeEndian.Uint64(b[152:160])
  407. a.TXWindowErrors = nativeEndian.Uint64(b[160:168])
  408. a.RXCompressed = nativeEndian.Uint64(b[168:176])
  409. a.TXCompressed = nativeEndian.Uint64(b[176:184])
  410. if l == 192 {
  411. a.RXNoHandler = nativeEndian.Uint64(b[184:192])
  412. }
  413. return nil
  414. }
  415. // LinkInfo contains data for specific network types
  416. type LinkInfo struct {
  417. Kind string // Driver name
  418. Data []byte // Driver specific configuration stored as nested Netlink messages
  419. SlaveKind string // Slave driver name
  420. SlaveData []byte // Slave driver specific configuration
  421. }
  422. func (i *LinkInfo) decode(ad *netlink.AttributeDecoder) error {
  423. for ad.Next() {
  424. switch ad.Type() {
  425. case unix.IFLA_INFO_KIND:
  426. i.Kind = ad.String()
  427. case unix.IFLA_INFO_SLAVE_KIND:
  428. i.SlaveKind = ad.String()
  429. case unix.IFLA_INFO_DATA:
  430. i.Data = ad.Bytes()
  431. case unix.IFLA_INFO_SLAVE_DATA:
  432. i.SlaveData = ad.Bytes()
  433. }
  434. }
  435. return nil
  436. }
  437. func (i *LinkInfo) encode(ae *netlink.AttributeEncoder) error {
  438. ae.String(unix.IFLA_INFO_KIND, i.Kind)
  439. ae.Bytes(unix.IFLA_INFO_DATA, i.Data)
  440. if len(i.SlaveData) > 0 {
  441. ae.String(unix.IFLA_INFO_SLAVE_KIND, i.SlaveKind)
  442. ae.Bytes(unix.IFLA_INFO_SLAVE_DATA, i.SlaveData)
  443. }
  444. return nil
  445. }
  446. // LinkXDP holds Express Data Path specific information
  447. type LinkXDP struct {
  448. FD int32
  449. ExpectedFD int32
  450. Attached uint8
  451. Flags uint32
  452. ProgID uint32
  453. }
  454. func (xdp *LinkXDP) decode(ad *netlink.AttributeDecoder) error {
  455. for ad.Next() {
  456. switch ad.Type() {
  457. case unix.IFLA_XDP_FD:
  458. xdp.FD = ad.Int32()
  459. case unix.IFLA_XDP_EXPECTED_FD:
  460. xdp.ExpectedFD = ad.Int32()
  461. case unix.IFLA_XDP_ATTACHED:
  462. xdp.Attached = ad.Uint8()
  463. case unix.IFLA_XDP_FLAGS:
  464. xdp.Flags = ad.Uint32()
  465. case unix.IFLA_XDP_PROG_ID:
  466. xdp.ProgID = ad.Uint32()
  467. }
  468. }
  469. return nil
  470. }
  471. func (xdp *LinkXDP) encode(ae *netlink.AttributeEncoder) error {
  472. ae.Int32(unix.IFLA_XDP_FD, xdp.FD)
  473. ae.Int32(unix.IFLA_XDP_EXPECTED_FD, xdp.ExpectedFD)
  474. ae.Uint32(unix.IFLA_XDP_FLAGS, xdp.Flags)
  475. // XDP_ATtACHED and XDP_PROG_ID are things that only can return from the kernel,
  476. // not be send, so we don't encode them.
  477. // source: https://elixir.bootlin.com/linux/v5.10.15/source/net/core/rtnetlink.c#L2894
  478. return nil
  479. }