Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1 | // Copyright 2012 Google, Inc. All rights reserved. |
| 2 | // Copyright 2009-2011 Andreas Krennmair. All rights reserved. |
| 3 | // |
| 4 | // Use of this source code is governed by a BSD-style license |
| 5 | // that can be found in the LICENSE file in the root of the source |
| 6 | // tree. |
| 7 | |
| 8 | package layers |
| 9 | |
| 10 | import ( |
| 11 | "encoding/binary" |
| 12 | "fmt" |
| 13 | "github.com/google/gopacket" |
| 14 | ) |
| 15 | |
| 16 | // Dot1Q is the packet layer for 802.1Q VLAN headers. |
| 17 | type Dot1Q struct { |
| 18 | BaseLayer |
| 19 | Priority uint8 |
| 20 | DropEligible bool |
| 21 | VLANIdentifier uint16 |
| 22 | Type EthernetType |
| 23 | } |
| 24 | |
| 25 | // LayerType returns gopacket.LayerTypeDot1Q |
| 26 | func (d *Dot1Q) LayerType() gopacket.LayerType { return LayerTypeDot1Q } |
| 27 | |
| 28 | // DecodeFromBytes decodes the given bytes into this layer. |
| 29 | func (d *Dot1Q) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { |
| 30 | d.Priority = (data[0] & 0xE0) >> 5 |
| 31 | d.DropEligible = data[0]&0x10 != 0 |
| 32 | d.VLANIdentifier = binary.BigEndian.Uint16(data[:2]) & 0x0FFF |
| 33 | d.Type = EthernetType(binary.BigEndian.Uint16(data[2:4])) |
| 34 | d.BaseLayer = BaseLayer{Contents: data[:4], Payload: data[4:]} |
| 35 | return nil |
| 36 | } |
| 37 | |
| 38 | // CanDecode returns the set of layer types that this DecodingLayer can decode. |
| 39 | func (d *Dot1Q) CanDecode() gopacket.LayerClass { |
| 40 | return LayerTypeDot1Q |
| 41 | } |
| 42 | |
| 43 | // NextLayerType returns the layer type contained by this DecodingLayer. |
| 44 | func (d *Dot1Q) NextLayerType() gopacket.LayerType { |
| 45 | return d.Type.LayerType() |
| 46 | } |
| 47 | |
| 48 | func decodeDot1Q(data []byte, p gopacket.PacketBuilder) error { |
| 49 | d := &Dot1Q{} |
| 50 | return decodingLayerDecoder(d, data, p) |
| 51 | } |
| 52 | |
| 53 | // SerializeTo writes the serialized form of this layer into the |
| 54 | // SerializationBuffer, implementing gopacket.SerializableLayer. |
| 55 | // See the docs for gopacket.SerializableLayer for more info. |
| 56 | func (d *Dot1Q) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { |
| 57 | bytes, err := b.PrependBytes(4) |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | if d.VLANIdentifier > 0xFFF { |
| 62 | return fmt.Errorf("vlan identifier %v is too high", d.VLANIdentifier) |
| 63 | } |
| 64 | firstBytes := uint16(d.Priority)<<13 | d.VLANIdentifier |
| 65 | if d.DropEligible { |
| 66 | firstBytes |= 0x1000 |
| 67 | } |
| 68 | binary.BigEndian.PutUint16(bytes, firstBytes) |
| 69 | binary.BigEndian.PutUint16(bytes[2:], uint16(d.Type)) |
| 70 | return nil |
| 71 | } |