numgen.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2018 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package expr
  15. import (
  16. "encoding/binary"
  17. "fmt"
  18. "github.com/google/nftables/binaryutil"
  19. "github.com/mdlayher/netlink"
  20. "golang.org/x/sys/unix"
  21. )
  22. // Numgen defines Numgen expression structure
  23. type Numgen struct {
  24. Register uint32
  25. Modulus uint32
  26. Type uint32
  27. Offset uint32
  28. }
  29. func (e *Numgen) marshal(fam byte) ([]byte, error) {
  30. // Currently only two types are supported, failing if Type is not of two known types
  31. switch e.Type {
  32. case unix.NFT_NG_INCREMENTAL:
  33. case unix.NFT_NG_RANDOM:
  34. default:
  35. return nil, fmt.Errorf("unsupported numgen type %d", e.Type)
  36. }
  37. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  38. {Type: unix.NFTA_NG_DREG, Data: binaryutil.BigEndian.PutUint32(e.Register)},
  39. {Type: unix.NFTA_NG_MODULUS, Data: binaryutil.BigEndian.PutUint32(e.Modulus)},
  40. {Type: unix.NFTA_NG_TYPE, Data: binaryutil.BigEndian.PutUint32(e.Type)},
  41. {Type: unix.NFTA_NG_OFFSET, Data: binaryutil.BigEndian.PutUint32(e.Offset)},
  42. })
  43. if err != nil {
  44. return nil, err
  45. }
  46. return netlink.MarshalAttributes([]netlink.Attribute{
  47. {Type: unix.NFTA_EXPR_NAME, Data: []byte("numgen\x00")},
  48. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  49. })
  50. }
  51. func (e *Numgen) unmarshal(fam byte, data []byte) error {
  52. ad, err := netlink.NewAttributeDecoder(data)
  53. if err != nil {
  54. return err
  55. }
  56. ad.ByteOrder = binary.BigEndian
  57. for ad.Next() {
  58. switch ad.Type() {
  59. case unix.NFTA_NG_DREG:
  60. e.Register = ad.Uint32()
  61. case unix.NFTA_NG_MODULUS:
  62. e.Modulus = ad.Uint32()
  63. case unix.NFTA_NG_TYPE:
  64. e.Type = ad.Uint32()
  65. case unix.NFTA_NG_OFFSET:
  66. e.Offset = ad.Uint32()
  67. }
  68. }
  69. return ad.Err()
  70. }