blob: 5cdd2f8d68325d1b58ac26c6b726c0348cbbff15 [file] [log] [blame]
Naveen Sampath04696f72022-06-13 15:19:14 +05301// 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 if len(data) < 4 {
31 df.SetTruncated()
32 return fmt.Errorf("802.1Q tag length %d too short", len(data))
33 }
34 d.Priority = (data[0] & 0xE0) >> 5
35 d.DropEligible = data[0]&0x10 != 0
36 d.VLANIdentifier = binary.BigEndian.Uint16(data[:2]) & 0x0FFF
37 d.Type = EthernetType(binary.BigEndian.Uint16(data[2:4]))
38 d.BaseLayer = BaseLayer{Contents: data[:4], Payload: data[4:]}
39 return nil
40}
41
42// CanDecode returns the set of layer types that this DecodingLayer can decode.
43func (d *Dot1Q) CanDecode() gopacket.LayerClass {
44 return LayerTypeDot1Q
45}
46
47// NextLayerType returns the layer type contained by this DecodingLayer.
48func (d *Dot1Q) NextLayerType() gopacket.LayerType {
49 return d.Type.LayerType()
50}
51
52func decodeDot1Q(data []byte, p gopacket.PacketBuilder) error {
53 d := &Dot1Q{}
54 return decodingLayerDecoder(d, data, p)
55}
56
57// SerializeTo writes the serialized form of this layer into the
58// SerializationBuffer, implementing gopacket.SerializableLayer.
59// See the docs for gopacket.SerializableLayer for more info.
60func (d *Dot1Q) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
61 bytes, err := b.PrependBytes(4)
62 if err != nil {
63 return err
64 }
65 if d.VLANIdentifier > 0xFFF {
66 return fmt.Errorf("vlan identifier %v is too high", d.VLANIdentifier)
67 }
68 firstBytes := uint16(d.Priority)<<13 | d.VLANIdentifier
69 if d.DropEligible {
70 firstBytes |= 0x1000
71 }
72 binary.BigEndian.PutUint16(bytes, firstBytes)
73 binary.BigEndian.PutUint16(bytes[2:], uint16(d.Type))
74 return nil
75}