rule.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package netlink
  2. import (
  3. "fmt"
  4. "net"
  5. "golang.org/x/sys/unix"
  6. )
  7. // Rule represents a netlink rule.
  8. type Rule struct {
  9. Priority int
  10. Family int
  11. Table int
  12. Mark int
  13. Mask int
  14. Tos uint
  15. TunID uint
  16. Goto int
  17. Src *net.IPNet
  18. Dst *net.IPNet
  19. Flow int
  20. IifName string
  21. OifName string
  22. SuppressIfgroup int
  23. SuppressPrefixlen int
  24. Invert bool
  25. Dport *RulePortRange
  26. Sport *RulePortRange
  27. // Type is the unix.RTN_* rule type, such as RTN_UNICAST
  28. // or RTN_UNREACHABLE.
  29. // When adding a new rule, zero means automatic.
  30. Type uint8
  31. }
  32. func (r Rule) String() string {
  33. from := "all"
  34. if r.Src != nil && r.Src.String() != "<nil>" {
  35. from = r.Src.String()
  36. }
  37. to := "all"
  38. if r.Dst != nil && r.Dst.String() != "<nil>" {
  39. to = r.Dst.String()
  40. }
  41. var typ string
  42. switch r.Type {
  43. case unix.RTN_UNSPEC: // zero
  44. typ = ""
  45. case unix.RTN_UNICAST:
  46. typ = ""
  47. case unix.RTN_LOCAL:
  48. typ = " local"
  49. case unix.RTN_BROADCAST:
  50. typ = " broadcast"
  51. case unix.RTN_ANYCAST:
  52. typ = " anycast"
  53. case unix.RTN_MULTICAST:
  54. typ = " multicast"
  55. case unix.RTN_BLACKHOLE:
  56. typ = " blackhole"
  57. case unix.RTN_UNREACHABLE:
  58. typ = " unreachable"
  59. case unix.RTN_PROHIBIT:
  60. typ = " prohibit"
  61. case unix.RTN_THROW:
  62. typ = " throw"
  63. case unix.RTN_NAT:
  64. typ = " nat"
  65. case unix.RTN_XRESOLVE:
  66. typ = " xresolve"
  67. default:
  68. typ = fmt.Sprintf(" type(0x%x)", r.Type)
  69. }
  70. return fmt.Sprintf("ip rule %d: from %s to %s table %d%s",
  71. r.Priority, from, to, r.Table, typ)
  72. }
  73. // NewRule return empty rules.
  74. func NewRule() *Rule {
  75. return &Rule{
  76. SuppressIfgroup: -1,
  77. SuppressPrefixlen: -1,
  78. Priority: -1,
  79. Mark: -1,
  80. Mask: -1,
  81. Goto: -1,
  82. Flow: -1,
  83. }
  84. }
  85. // NewRulePortRange creates rule sport/dport range.
  86. func NewRulePortRange(start, end uint16) *RulePortRange {
  87. return &RulePortRange{Start: start, End: end}
  88. }
  89. // RulePortRange represents rule sport/dport range.
  90. type RulePortRange struct {
  91. Start uint16
  92. End uint16
  93. }