Decoder.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2019 by Farsight Security, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package dnstap
  17. import (
  18. framestream "github.com/farsightsec/golang-framestream"
  19. "google.golang.org/protobuf/proto"
  20. )
  21. // A Decoder reads and parses Dnstap messages from an io.Reader
  22. type Decoder struct {
  23. buf []byte
  24. r Reader
  25. }
  26. // NewDecoder creates a Decoder using the given dnstap Reader, accepting
  27. // dnstap data frames up to maxSize in size.
  28. func NewDecoder(r Reader, maxSize int) *Decoder {
  29. return &Decoder{
  30. buf: make([]byte, maxSize),
  31. r: r,
  32. }
  33. }
  34. // Decode reads and parses a Dnstap message from the Decoder's Reader.
  35. // Decode silently discards data frames larger than the Decoder's configured
  36. // maxSize.
  37. func (d *Decoder) Decode(m *Dnstap) error {
  38. for {
  39. n, err := d.r.ReadFrame(d.buf)
  40. switch err {
  41. case framestream.ErrDataFrameTooLarge:
  42. continue
  43. case nil:
  44. break
  45. default:
  46. return err
  47. }
  48. return proto.Unmarshal(d.buf[:n], m)
  49. }
  50. }