objref.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 Objref struct {
  22. Type int // TODO: enum
  23. Name string
  24. }
  25. func (e *Objref) marshal(fam byte) ([]byte, error) {
  26. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  27. {Type: unix.NFTA_OBJREF_IMM_TYPE, Data: binaryutil.BigEndian.PutUint32(uint32(e.Type))},
  28. {Type: unix.NFTA_OBJREF_IMM_NAME, Data: []byte(e.Name)}, // NOT \x00-terminated?!
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. return netlink.MarshalAttributes([]netlink.Attribute{
  34. {Type: unix.NFTA_EXPR_NAME, Data: []byte("objref\x00")},
  35. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  36. })
  37. }
  38. func (e *Objref) 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_OBJREF_IMM_TYPE:
  47. e.Type = int(ad.Uint32())
  48. case unix.NFTA_OBJREF_IMM_NAME:
  49. e.Name = ad.String()
  50. }
  51. }
  52. return ad.Err()
  53. }