reject.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 Reject struct {
  22. Type uint32
  23. Code uint8
  24. }
  25. func (e *Reject) marshal(fam byte) ([]byte, error) {
  26. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  27. {Type: unix.NFTA_REJECT_TYPE, Data: binaryutil.BigEndian.PutUint32(e.Type)},
  28. {Type: unix.NFTA_REJECT_ICMP_CODE, Data: []byte{e.Code}},
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. return netlink.MarshalAttributes([]netlink.Attribute{
  34. {Type: unix.NFTA_EXPR_NAME, Data: []byte("reject\x00")},
  35. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  36. })
  37. }
  38. func (e *Reject) 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_REJECT_TYPE:
  47. e.Type = ad.Uint32()
  48. case unix.NFTA_REJECT_ICMP_CODE:
  49. e.Code = ad.Uint8()
  50. }
  51. }
  52. return ad.Err()
  53. }