counter.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 nftables
  15. import (
  16. "github.com/google/nftables/binaryutil"
  17. "github.com/mdlayher/netlink"
  18. "golang.org/x/sys/unix"
  19. )
  20. // CounterObj implements Obj.
  21. type CounterObj struct {
  22. Table *Table
  23. Name string // e.g. “fwded”
  24. Bytes uint64
  25. Packets uint64
  26. }
  27. func (c *CounterObj) unmarshal(ad *netlink.AttributeDecoder) error {
  28. for ad.Next() {
  29. switch ad.Type() {
  30. case unix.NFTA_COUNTER_BYTES:
  31. c.Bytes = ad.Uint64()
  32. case unix.NFTA_COUNTER_PACKETS:
  33. c.Packets = ad.Uint64()
  34. }
  35. }
  36. return ad.Err()
  37. }
  38. func (c *CounterObj) table() *Table {
  39. return c.Table
  40. }
  41. func (c *CounterObj) family() TableFamily {
  42. return c.Table.Family
  43. }
  44. func (c *CounterObj) marshal(data bool) ([]byte, error) {
  45. obj, err := netlink.MarshalAttributes([]netlink.Attribute{
  46. {Type: unix.NFTA_COUNTER_BYTES, Data: binaryutil.BigEndian.PutUint64(c.Bytes)},
  47. {Type: unix.NFTA_COUNTER_PACKETS, Data: binaryutil.BigEndian.PutUint64(c.Packets)},
  48. })
  49. if err != nil {
  50. return nil, err
  51. }
  52. const NFT_OBJECT_COUNTER = 1 // TODO: get into x/sys/unix
  53. attrs := []netlink.Attribute{
  54. {Type: unix.NFTA_OBJ_TABLE, Data: []byte(c.Table.Name + "\x00")},
  55. {Type: unix.NFTA_OBJ_NAME, Data: []byte(c.Name + "\x00")},
  56. {Type: unix.NFTA_OBJ_TYPE, Data: binaryutil.BigEndian.PutUint32(NFT_OBJECT_COUNTER)},
  57. }
  58. if data {
  59. attrs = append(attrs, netlink.Attribute{Type: unix.NLA_F_NESTED | unix.NFTA_OBJ_DATA, Data: obj})
  60. }
  61. return netlink.MarshalAttributes(attrs)
  62. }