info.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package xt
  2. import (
  3. "golang.org/x/sys/unix"
  4. )
  5. // TableFamily specifies the address family of the table Match or Target Info
  6. // data is contained in. On purpose, we don't import the expr package here in
  7. // order to keep the option open to import this package instead into expr.
  8. type TableFamily byte
  9. // InfoAny is a (un)marshaling implemented by any info type.
  10. type InfoAny interface {
  11. marshal(fam TableFamily, rev uint32) ([]byte, error)
  12. unmarshal(fam TableFamily, rev uint32, data []byte) error
  13. }
  14. // Marshal a Match or Target Info type into its binary representation.
  15. func Marshal(fam TableFamily, rev uint32, info InfoAny) ([]byte, error) {
  16. return info.marshal(fam, rev)
  17. }
  18. // Unmarshal Info binary payload into its corresponding dedicated type as
  19. // indicated by the name argument. In several cases, unmarshalling depends on
  20. // the specific table family the Target or Match expression with the info
  21. // payload belongs to, as well as the specific info structure revision.
  22. func Unmarshal(name string, fam TableFamily, rev uint32, data []byte) (InfoAny, error) {
  23. var i InfoAny
  24. switch name {
  25. case "addrtype":
  26. switch rev {
  27. case 0:
  28. i = &AddrType{}
  29. case 1:
  30. i = &AddrTypeV1{}
  31. }
  32. case "conntrack":
  33. switch rev {
  34. case 1:
  35. i = &ConntrackMtinfo1{}
  36. case 2:
  37. i = &ConntrackMtinfo2{}
  38. case 3:
  39. i = &ConntrackMtinfo3{}
  40. }
  41. case "tcp":
  42. i = &Tcp{}
  43. case "udp":
  44. i = &Udp{}
  45. case "SNAT":
  46. if fam == unix.NFPROTO_IPV4 {
  47. i = &NatIPv4MultiRangeCompat{}
  48. }
  49. case "DNAT":
  50. switch fam {
  51. case unix.NFPROTO_IPV4:
  52. if rev == 0 {
  53. i = &NatIPv4MultiRangeCompat{}
  54. break
  55. }
  56. fallthrough
  57. case unix.NFPROTO_IPV6:
  58. switch rev {
  59. case 1:
  60. i = &NatRange{}
  61. case 2:
  62. i = &NatRange2{}
  63. }
  64. }
  65. case "MASQUERADE":
  66. switch fam {
  67. case unix.NFPROTO_IPV4:
  68. i = &NatIPv4MultiRangeCompat{}
  69. }
  70. case "REDIRECT":
  71. switch fam {
  72. case unix.NFPROTO_IPV4:
  73. if rev == 0 {
  74. i = &NatIPv4MultiRangeCompat{}
  75. break
  76. }
  77. fallthrough
  78. case unix.NFPROTO_IPV6:
  79. i = &NatRange{}
  80. }
  81. }
  82. if i == nil {
  83. i = &Unknown{}
  84. }
  85. if err := i.unmarshal(fam, rev, data); err != nil {
  86. return nil, err
  87. }
  88. return i, nil
  89. }