route_linux.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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{
  42. RtNexthop: *((*unix.RtNexthop)(unsafe.Pointer(&b[0:unix.SizeofRtNexthop][0]))),
  43. }
  44. }
  45. func (msg *RtNexthop) Len() int {
  46. if len(msg.Children) == 0 {
  47. return unix.SizeofRtNexthop
  48. }
  49. l := 0
  50. for _, child := range msg.Children {
  51. l += rtaAlignOf(child.Len())
  52. }
  53. l += unix.SizeofRtNexthop
  54. return rtaAlignOf(l)
  55. }
  56. func (msg *RtNexthop) Serialize() []byte {
  57. length := msg.Len()
  58. msg.RtNexthop.Len = uint16(length)
  59. buf := make([]byte, length)
  60. copy(buf, (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:])
  61. next := rtaAlignOf(unix.SizeofRtNexthop)
  62. if len(msg.Children) > 0 {
  63. for _, child := range msg.Children {
  64. childBuf := child.Serialize()
  65. copy(buf[next:], childBuf)
  66. next += rtaAlignOf(len(childBuf))
  67. }
  68. }
  69. return buf
  70. }
  71. type RtGenMsg struct {
  72. unix.RtGenmsg
  73. }
  74. func NewRtGenMsg() *RtGenMsg {
  75. return &RtGenMsg{
  76. RtGenmsg: unix.RtGenmsg{
  77. Family: unix.AF_UNSPEC,
  78. },
  79. }
  80. }
  81. func (msg *RtGenMsg) Len() int {
  82. return rtaAlignOf(unix.SizeofRtGenmsg)
  83. }
  84. func DeserializeRtGenMsg(b []byte) *RtGenMsg {
  85. return &RtGenMsg{RtGenmsg: unix.RtGenmsg{Family: b[0]}}
  86. }
  87. func (msg *RtGenMsg) Serialize() []byte {
  88. out := make([]byte, msg.Len())
  89. out[0] = msg.Family
  90. return out
  91. }