loopback.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2012 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package layers
  7. import (
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "github.com/google/gopacket"
  12. )
  13. // Loopback contains the header for loopback encapsulation. This header is
  14. // used by both BSD and OpenBSD style loopback decoding (pcap's DLT_NULL
  15. // and DLT_LOOP, respectively).
  16. type Loopback struct {
  17. BaseLayer
  18. Family ProtocolFamily
  19. }
  20. // LayerType returns LayerTypeLoopback.
  21. func (l *Loopback) LayerType() gopacket.LayerType { return LayerTypeLoopback }
  22. // DecodeFromBytes decodes the given bytes into this layer.
  23. func (l *Loopback) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  24. if len(data) < 4 {
  25. return errors.New("Loopback packet too small")
  26. }
  27. // The protocol could be either big-endian or little-endian, we're
  28. // not sure. But we're PRETTY sure that the value is less than
  29. // 256, so we can check the first two bytes.
  30. var prot uint32
  31. if data[0] == 0 && data[1] == 0 {
  32. prot = binary.BigEndian.Uint32(data[:4])
  33. } else {
  34. prot = binary.LittleEndian.Uint32(data[:4])
  35. }
  36. if prot > 0xFF {
  37. return fmt.Errorf("Invalid loopback protocol %q", data[:4])
  38. }
  39. l.Family = ProtocolFamily(prot)
  40. l.BaseLayer = BaseLayer{data[:4], data[4:]}
  41. return nil
  42. }
  43. // CanDecode returns the set of layer types that this DecodingLayer can decode.
  44. func (l *Loopback) CanDecode() gopacket.LayerClass {
  45. return LayerTypeLoopback
  46. }
  47. // NextLayerType returns the layer type contained by this DecodingLayer.
  48. func (l *Loopback) NextLayerType() gopacket.LayerType {
  49. return l.Family.LayerType()
  50. }
  51. // SerializeTo writes the serialized form of this layer into the
  52. // SerializationBuffer, implementing gopacket.SerializableLayer.
  53. func (l *Loopback) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
  54. bytes, err := b.PrependBytes(4)
  55. if err != nil {
  56. return err
  57. }
  58. binary.LittleEndian.PutUint32(bytes, uint32(l.Family))
  59. return nil
  60. }
  61. func decodeLoopback(data []byte, p gopacket.PacketBuilder) error {
  62. l := Loopback{}
  63. if err := l.DecodeFromBytes(data, gopacket.NilDecodeFeedback); err != nil {
  64. return err
  65. }
  66. p.AddLayer(&l)
  67. return p.NextDecoder(l.Family)
  68. }