counter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. "github.com/google/nftables/binaryutil"
  18. "github.com/mdlayher/netlink"
  19. "golang.org/x/sys/unix"
  20. )
  21. type Counter struct {
  22. Bytes uint64
  23. Packets uint64
  24. }
  25. func (e *Counter) marshal(fam byte) ([]byte, error) {
  26. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  27. {Type: unix.NFTA_COUNTER_BYTES, Data: binaryutil.BigEndian.PutUint64(e.Bytes)},
  28. {Type: unix.NFTA_COUNTER_PACKETS, Data: binaryutil.BigEndian.PutUint64(e.Packets)},
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. return netlink.MarshalAttributes([]netlink.Attribute{
  34. {Type: unix.NFTA_EXPR_NAME, Data: []byte("counter\x00")},
  35. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  36. })
  37. }
  38. func (e *Counter) unmarshal(fam byte, data []byte) error {
  39. ad, err := netlink.NewAttributeDecoder(data)
  40. if err != nil {
  41. return err
  42. }
  43. ad.ByteOrder = binary.BigEndian
  44. for ad.Next() {
  45. switch ad.Type() {
  46. case unix.NFTA_COUNTER_BYTES:
  47. e.Bytes = ad.Uint64()
  48. case unix.NFTA_COUNTER_PACKETS:
  49. e.Packets = ad.Uint64()
  50. }
  51. }
  52. return ad.Err()
  53. }