immediate.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. type Immediate struct {
  23. Register uint32
  24. Data []byte
  25. }
  26. func (e *Immediate) marshal(fam byte) ([]byte, error) {
  27. immData, err := netlink.MarshalAttributes([]netlink.Attribute{
  28. {Type: unix.NFTA_DATA_VALUE, Data: e.Data},
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  34. {Type: unix.NFTA_IMMEDIATE_DREG, Data: binaryutil.BigEndian.PutUint32(e.Register)},
  35. {Type: unix.NLA_F_NESTED | unix.NFTA_IMMEDIATE_DATA, Data: immData},
  36. })
  37. if err != nil {
  38. return nil, err
  39. }
  40. return netlink.MarshalAttributes([]netlink.Attribute{
  41. {Type: unix.NFTA_EXPR_NAME, Data: []byte("immediate\x00")},
  42. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  43. })
  44. }
  45. func (e *Immediate) unmarshal(fam byte, data []byte) error {
  46. ad, err := netlink.NewAttributeDecoder(data)
  47. if err != nil {
  48. return err
  49. }
  50. ad.ByteOrder = binary.BigEndian
  51. for ad.Next() {
  52. switch ad.Type() {
  53. case unix.NFTA_IMMEDIATE_DREG:
  54. e.Register = ad.Uint32()
  55. case unix.NFTA_IMMEDIATE_DATA:
  56. nestedAD, err := netlink.NewAttributeDecoder(ad.Bytes())
  57. if err != nil {
  58. return fmt.Errorf("nested NewAttributeDecoder() failed: %v", err)
  59. }
  60. for nestedAD.Next() {
  61. switch nestedAD.Type() {
  62. case unix.NFTA_DATA_VALUE:
  63. e.Data = nestedAD.Bytes()
  64. }
  65. }
  66. if nestedAD.Err() != nil {
  67. return fmt.Errorf("decoding immediate: %v", nestedAD.Err())
  68. }
  69. }
  70. }
  71. return ad.Err()
  72. }