connlimit.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2019 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. "github.com/google/nftables/binaryutil"
  18. "github.com/mdlayher/netlink"
  19. "golang.org/x/sys/unix"
  20. )
  21. const (
  22. // Per https://git.netfilter.org/libnftnl/tree/include/linux/netfilter/nf_tables.h?id=84d12cfacf8ddd857a09435f3d982ab6250d250c#n1167
  23. NFTA_CONNLIMIT_UNSPEC = iota
  24. NFTA_CONNLIMIT_COUNT
  25. NFTA_CONNLIMIT_FLAGS
  26. NFT_CONNLIMIT_F_INV = 1
  27. )
  28. // Per https://git.netfilter.org/libnftnl/tree/src/expr/connlimit.c?id=84d12cfacf8ddd857a09435f3d982ab6250d250c
  29. type Connlimit struct {
  30. Count uint32
  31. Flags uint32
  32. }
  33. func (e *Connlimit) marshal(fam byte) ([]byte, error) {
  34. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  35. {Type: NFTA_CONNLIMIT_COUNT, Data: binaryutil.BigEndian.PutUint32(e.Count)},
  36. {Type: NFTA_CONNLIMIT_FLAGS, Data: binaryutil.BigEndian.PutUint32(e.Flags)},
  37. })
  38. if err != nil {
  39. return nil, err
  40. }
  41. return netlink.MarshalAttributes([]netlink.Attribute{
  42. {Type: unix.NFTA_EXPR_NAME, Data: []byte("connlimit\x00")},
  43. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  44. })
  45. }
  46. func (e *Connlimit) unmarshal(fam byte, data []byte) error {
  47. ad, err := netlink.NewAttributeDecoder(data)
  48. if err != nil {
  49. return err
  50. }
  51. ad.ByteOrder = binary.BigEndian
  52. for ad.Next() {
  53. switch ad.Type() {
  54. case NFTA_CONNLIMIT_COUNT:
  55. e.Count = binaryutil.BigEndian.Uint32(ad.Bytes())
  56. case NFTA_CONNLIMIT_FLAGS:
  57. e.Flags = binaryutil.BigEndian.Uint32(ad.Bytes())
  58. }
  59. }
  60. return ad.Err()
  61. }