blob: 47f93d73eb25a9e58fed602afc3ede6cb827cd8a [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001// 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
8package layers
9
10import (
11 "encoding/binary"
12 "fmt"
13 "github.com/google/gopacket"
14)
15
16// Dot1Q is the packet layer for 802.1Q VLAN headers.
17type Dot1Q struct {
18 BaseLayer
19 Priority uint8
20 DropEligible bool
21 VLANIdentifier uint16
22 Type EthernetType
23}
24
25// LayerType returns gopacket.LayerTypeDot1Q
26func (d *Dot1Q) LayerType() gopacket.LayerType { return LayerTypeDot1Q }
27
28// DecodeFromBytes decodes the given bytes into this layer.
29func (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.
39func (d *Dot1Q) CanDecode() gopacket.LayerClass {
40 return LayerTypeDot1Q
41}
42
43// NextLayerType returns the layer type contained by this DecodingLayer.
44func (d *Dot1Q) NextLayerType() gopacket.LayerType {
45 return d.Type.LayerType()
46}
47
48func 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.
56func (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}