route_linux.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package nl
  2. import (
  3. "unsafe"
  4. "golang.org/x/sys/unix"
  5. )
  6. type RtMsg struct {
  7. unix.RtMsg
  8. }
  9. func NewRtMsg() *RtMsg {
  10. return &RtMsg{
  11. RtMsg: unix.RtMsg{
  12. Table: unix.RT_TABLE_MAIN,
  13. Scope: unix.RT_SCOPE_UNIVERSE,
  14. Protocol: unix.RTPROT_BOOT,
  15. Type: unix.RTN_UNICAST,
  16. },
  17. }
  18. }
  19. func NewRtDelMsg() *RtMsg {
  20. return &RtMsg{
  21. RtMsg: unix.RtMsg{
  22. Table: unix.RT_TABLE_MAIN,
  23. Scope: unix.RT_SCOPE_NOWHERE,
  24. },
  25. }
  26. }
  27. func (msg *RtMsg) Len() int {
  28. return unix.SizeofRtMsg
  29. }
  30. func DeserializeRtMsg(b []byte) *RtMsg {
  31. return (*RtMsg)(unsafe.Pointer(&b[0:unix.SizeofRtMsg][0]))
  32. }
  33. func (msg *RtMsg) Serialize() []byte {
  34. return (*(*[unix.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]
  35. }
  36. type RtNexthop struct {
  37. unix.RtNexthop
  38. Children []NetlinkRequestData
  39. }
  40. func DeserializeRtNexthop(b []byte) *RtNexthop {
  41. return (*RtNexthop)(unsafe.Pointer(&b[0:unix.SizeofRtNexthop][0]))
  42. }
  43. func (msg *RtNexthop) Len() int {
  44. if len(msg.Children) == 0 {
  45. return unix.SizeofRtNexthop
  46. }
  47. l := 0
  48. for _, child := range msg.Children {
  49. l += rtaAlignOf(child.Len())
  50. }
  51. l += unix.SizeofRtNexthop
  52. return rtaAlignOf(l)
  53. }
  54. func (msg *RtNexthop) Serialize() []byte {
  55. length := msg.Len()
  56. msg.RtNexthop.Len = uint16(length)
  57. buf := make([]byte, length)
  58. copy(buf, (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:])
  59. next := rtaAlignOf(unix.SizeofRtNexthop)
  60. if len(msg.Children) > 0 {
  61. for _, child := range msg.Children {
  62. childBuf := child.Serialize()
  63. copy(buf[next:], childBuf)
  64. next += rtaAlignOf(len(childBuf))
  65. }
  66. }
  67. return buf
  68. }