pax_global_header00006660000000000000000000000064136600213220014505gustar00rootroot0000000000000052 comment=504a57d28670379f59e61bf636cccd05b7fa7911 golang-github-mdlayher-ethernet-0.0~git20190606.0394541/000077500000000000000000000000001366002132200220745ustar00rootroot00000000000000golang-github-mdlayher-ethernet-0.0~git20190606.0394541/.travis.yml000066400000000000000000000004511366002132200242050ustar00rootroot00000000000000language: go go: - 1.x os: - linux before_install: - go get golang.org/x/lint/golint - go get honnef.co/go/tools/cmd/staticcheck - go get -d ./... script: - go build -tags=gofuzz ./... - go vet ./... - staticcheck ./... - golint -set_exit_status ./... - go test -v -race ./... golang-github-mdlayher-ethernet-0.0~git20190606.0394541/LICENSE.md000066400000000000000000000020701366002132200234770ustar00rootroot00000000000000MIT License =========== Copyright (C) 2015 Matt Layher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-mdlayher-ethernet-0.0~git20190606.0394541/README.md000066400000000000000000000013501366002132200233520ustar00rootroot00000000000000ethernet [![Build Status](https://travis-ci.org/mdlayher/ethernet.svg?branch=master)](https://travis-ci.org/mdlayher/ethernet) [![GoDoc](https://godoc.org/github.com/mdlayher/ethernet?status.svg)](https://godoc.org/github.com/mdlayher/ethernet) [![Go Report Card](https://goreportcard.com/badge/github.com/mdlayher/ethernet)](https://goreportcard.com/report/github.com/mdlayher/ethernet) ======== Package `ethernet` implements marshaling and unmarshaling of IEEE 802.3 Ethernet II frames and IEEE 802.1Q VLAN tags. MIT Licensed. For more information about using Ethernet frames in Go, check out my blog post: [Network Protocol Breakdown: Ethernet and Go](https://medium.com/@mdlayher/network-protocol-breakdown-ethernet-and-go-de985d726cc1).golang-github-mdlayher-ethernet-0.0~git20190606.0394541/cmd/000077500000000000000000000000001366002132200226375ustar00rootroot00000000000000golang-github-mdlayher-ethernet-0.0~git20190606.0394541/cmd/etherecho/000077500000000000000000000000001366002132200246055ustar00rootroot00000000000000golang-github-mdlayher-ethernet-0.0~git20190606.0394541/cmd/etherecho/README.md000066400000000000000000000021471366002132200260700ustar00rootroot00000000000000etherecho ========= Command `etherecho` broadcasts a message to all machines in the same network segment, and listens for other messages from other `etherecho` servers. `etherecho` only works on Linux and BSD, and requires root permission or `CAP_NET_ADMIN` on Linux. Usage ----- ``` $ etherecho -h Usage of etherecho: -i string network interface to use to send and receive messages -m string message to be sent (default: system's hostname) ``` Example ------- Start an instance of `etherecho` on two machines on the same network segment: ``` foo $ etherecho -i eth0 ``` ``` bar $ etherecho -i eth0 ``` Both machines should begin seeing messages from each other at regular intervals: ``` foo $ etherecho -i eth0 2017/06/14 00:03:13 [aa:aa:aa:aa:aa:aa] bar 2017/06/14 00:03:14 [aa:aa:aa:aa:aa:aa] bar 2017/06/14 00:03:15 [aa:aa:aa:aa:aa:aa] bar ``` ``` bar $ etherecho -i eth0 2017/06/14 00:03:13 [bb:bb:bb:bb:bb:bb] foo 2017/06/14 00:03:14 [bb:bb:bb:bb:bb:bb] foo 2017/06/14 00:03:15 [bb:bb:bb:bb:bb:bb] foo ``` Additional machines can be added, so long as they reside on the same network segment.golang-github-mdlayher-ethernet-0.0~git20190606.0394541/cmd/etherecho/main.go000066400000000000000000000056641366002132200260730ustar00rootroot00000000000000// Command etherecho broadcasts a message to all machines in the same network // segment, and listens for other messages from other etherecho servers. // // etherecho only works on Linux and BSD, and requires root permission or // CAP_NET_ADMIN on Linux. package main import ( "flag" "log" "net" "os" "time" "github.com/mdlayher/ethernet" "github.com/mdlayher/raw" ) // Make use of an unassigned EtherType for etherecho. // https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml const etherType = 0xcccc func main() { var ( ifaceFlag = flag.String("i", "", "network interface to use to send and receive messages") msgFlag = flag.String("m", "", "message to be sent (default: system's hostname)") ) flag.Parse() // Open a raw socket on the specified interface, and configure it to accept // traffic with etherecho's EtherType. ifi, err := net.InterfaceByName(*ifaceFlag) if err != nil { log.Fatalf("failed to find interface %q: %v", *ifaceFlag, err) } c, err := raw.ListenPacket(ifi, etherType, nil) if err != nil { log.Fatalf("failed to listen: %v", err) } // Default message to system's hostname if empty. msg := *msgFlag if msg == "" { msg, err = os.Hostname() if err != nil { log.Fatalf("failed to retrieve hostname: %v", err) } } // Send messages in one goroutine, receive messages in another. go sendMessages(c, ifi.HardwareAddr, msg) go receiveMessages(c, ifi.MTU) // Block forever. select {} } // sendMessages continuously sends a message over a connection at regular intervals, // sourced from specified hardware address. func sendMessages(c net.PacketConn, source net.HardwareAddr, msg string) { // Message is broadcast to all machines in same network segment. f := ðernet.Frame{ Destination: ethernet.Broadcast, Source: source, EtherType: etherType, Payload: []byte(msg), } b, err := f.MarshalBinary() if err != nil { log.Fatalf("failed to marshal ethernet frame: %v", err) } // Required by Linux, even though the Ethernet frame has a destination. // Unused by BSD. addr := &raw.Addr{ HardwareAddr: ethernet.Broadcast, } // Send message forever. t := time.NewTicker(1 * time.Second) for range t.C { if _, err := c.WriteTo(b, addr); err != nil { log.Fatalf("failed to send message: %v", err) } } } // receiveMessages continuously receives messages over a connection. The messages // may be up to the interface's MTU in size. func receiveMessages(c net.PacketConn, mtu int) { var f ethernet.Frame b := make([]byte, mtu) // Keep receiving messages forever. for { n, addr, err := c.ReadFrom(b) if err != nil { log.Fatalf("failed to receive message: %v", err) } // Unpack Ethernet II frame into Go representation. if err := (&f).UnmarshalBinary(b[:n]); err != nil { log.Fatalf("failed to unmarshal ethernet frame: %v", err) } // Display source of message and message itself. log.Printf("[%s] %s", addr.String(), string(f.Payload)) } } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/ethernet.go000066400000000000000000000212321366002132200242410ustar00rootroot00000000000000// Package ethernet implements marshaling and unmarshaling of IEEE 802.3 // Ethernet II frames and IEEE 802.1Q VLAN tags. package ethernet import ( "encoding/binary" "errors" "fmt" "hash/crc32" "io" "net" ) //go:generate stringer -output=string.go -type=EtherType const ( // minPayload is the minimum payload size for an Ethernet frame, assuming // that no 802.1Q VLAN tags are present. minPayload = 46 ) var ( // Broadcast is a special hardware address which indicates a Frame should // be sent to every device on a given LAN segment. Broadcast = net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff} ) var ( // ErrInvalidFCS is returned when Frame.UnmarshalFCS detects an incorrect // Ethernet frame check sequence in a byte slice for a Frame. ErrInvalidFCS = errors.New("invalid frame check sequence") ) // An EtherType is a value used to identify an upper layer protocol // encapsulated in a Frame. // // A list of IANA-assigned EtherType values may be found here: // http://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml. type EtherType uint16 // Common EtherType values frequently used in a Frame. const ( EtherTypeIPv4 EtherType = 0x0800 EtherTypeARP EtherType = 0x0806 EtherTypeIPv6 EtherType = 0x86DD // EtherTypeVLAN and EtherTypeServiceVLAN are used as 802.1Q Tag Protocol // Identifiers (TPIDs). EtherTypeVLAN EtherType = 0x8100 EtherTypeServiceVLAN EtherType = 0x88a8 ) // A Frame is an IEEE 802.3 Ethernet II frame. A Frame contains information // such as source and destination hardware addresses, zero or more optional // 802.1Q VLAN tags, an EtherType, and payload data. type Frame struct { // Destination specifies the destination hardware address for this Frame. // // If this address is set to Broadcast, the Frame will be sent to every // device on a given LAN segment. Destination net.HardwareAddr // Source specifies the source hardware address for this Frame. // // Typically, this is the hardware address of the network interface used to // send this Frame. Source net.HardwareAddr // ServiceVLAN specifies an optional 802.1Q service VLAN tag, for use with // 802.1ad double tagging, or "Q-in-Q". If ServiceVLAN is not nil, VLAN must // not be nil as well. // // Most users should leave this field set to nil and use VLAN instead. ServiceVLAN *VLAN // VLAN specifies an optional 802.1Q customer VLAN tag, which may or may // not be present in a Frame. It is important to note that the operating // system may automatically strip VLAN tags before they can be parsed. VLAN *VLAN // EtherType is a value used to identify an upper layer protocol // encapsulated in this Frame. EtherType EtherType // Payload is a variable length data payload encapsulated by this Frame. Payload []byte } // MarshalBinary allocates a byte slice and marshals a Frame into binary form. func (f *Frame) MarshalBinary() ([]byte, error) { b := make([]byte, f.length()) _, err := f.read(b) return b, err } // MarshalFCS allocates a byte slice, marshals a Frame into binary form, and // finally calculates and places a 4-byte IEEE CRC32 frame check sequence at // the end of the slice. // // Most users should use MarshalBinary instead. MarshalFCS is provided as a // convenience for rare occasions when the operating system cannot // automatically generate a frame check sequence for an Ethernet frame. func (f *Frame) MarshalFCS() ([]byte, error) { // Frame length with 4 extra bytes for frame check sequence b := make([]byte, f.length()+4) if _, err := f.read(b); err != nil { return nil, err } // Compute IEEE CRC32 checksum of frame bytes and place it directly // in the last four bytes of the slice binary.BigEndian.PutUint32(b[len(b)-4:], crc32.ChecksumIEEE(b[0:len(b)-4])) return b, nil } // read reads data from a Frame into b. read is used to marshal a Frame // into binary form, but does not allocate on its own. func (f *Frame) read(b []byte) (int, error) { // S-VLAN must also have accompanying C-VLAN. if f.ServiceVLAN != nil && f.VLAN == nil { return 0, ErrInvalidVLAN } copy(b[0:6], f.Destination) copy(b[6:12], f.Source) // Marshal each non-nil VLAN tag into bytes, inserting the appropriate // EtherType/TPID before each, so devices know that one or more VLANs // are present. vlans := []struct { vlan *VLAN tpid EtherType }{ {vlan: f.ServiceVLAN, tpid: EtherTypeServiceVLAN}, {vlan: f.VLAN, tpid: EtherTypeVLAN}, } n := 12 for _, vt := range vlans { if vt.vlan == nil { continue } // Add VLAN EtherType and VLAN bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(vt.tpid)) if _, err := vt.vlan.read(b[n+2 : n+4]); err != nil { return 0, err } n += 4 } // Marshal actual EtherType after any VLANs, copy payload into // output bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(f.EtherType)) copy(b[n+2:], f.Payload) return len(b), nil } // UnmarshalBinary unmarshals a byte slice into a Frame. func (f *Frame) UnmarshalBinary(b []byte) error { // Verify that both hardware addresses and a single EtherType are present if len(b) < 14 { return io.ErrUnexpectedEOF } // Track offset in packet for reading data n := 14 // Continue looping and parsing VLAN tags until no more VLAN EtherType // values are detected et := EtherType(binary.BigEndian.Uint16(b[n-2 : n])) switch et { case EtherTypeServiceVLAN, EtherTypeVLAN: // VLAN type is hinted for further parsing. An index is returned which // indicates how many bytes were consumed by VLAN tags. nn, err := f.unmarshalVLANs(et, b[n:]) if err != nil { return err } n += nn default: // No VLANs detected. f.EtherType = et } // Allocate single byte slice to store destination and source hardware // addresses, and payload bb := make([]byte, 6+6+len(b[n:])) copy(bb[0:6], b[0:6]) f.Destination = bb[0:6] copy(bb[6:12], b[6:12]) f.Source = bb[6:12] // There used to be a minimum payload length restriction here, but as // long as two hardware addresses and an EtherType are present, it // doesn't really matter what is contained in the payload. We will // follow the "robustness principle". copy(bb[12:], b[n:]) f.Payload = bb[12:] return nil } // UnmarshalFCS computes the IEEE CRC32 frame check sequence of a Frame, // verifies it against the checksum present in the byte slice, and finally, // unmarshals a byte slice into a Frame. // // Most users should use UnmarshalBinary instead. UnmarshalFCS is provided as // a convenience for rare occasions when the operating system cannot // automatically verify a frame check sequence for an Ethernet frame. func (f *Frame) UnmarshalFCS(b []byte) error { // Must contain enough data for FCS, to avoid panics if len(b) < 4 { return io.ErrUnexpectedEOF } // Verify checksum in slice versus newly computed checksum want := binary.BigEndian.Uint32(b[len(b)-4:]) got := crc32.ChecksumIEEE(b[0 : len(b)-4]) if want != got { return ErrInvalidFCS } return f.UnmarshalBinary(b[0 : len(b)-4]) } // length calculates the number of bytes required to store a Frame. func (f *Frame) length() int { // If payload is less than the required minimum length, we zero-pad up to // the required minimum length pl := len(f.Payload) if pl < minPayload { pl = minPayload } // Add additional length if VLAN tags are needed. var vlanLen int switch { case f.ServiceVLAN != nil && f.VLAN != nil: vlanLen = 8 case f.VLAN != nil: vlanLen = 4 } // 6 bytes: destination hardware address // 6 bytes: source hardware address // N bytes: VLAN tags (if present) // 2 bytes: EtherType // N bytes: payload length (may be padded) return 6 + 6 + vlanLen + 2 + pl } // unmarshalVLANs unmarshals S/C-VLAN tags. It is assumed that tpid // is a valid S/C-VLAN TPID. func (f *Frame) unmarshalVLANs(tpid EtherType, b []byte) (int, error) { // 4 or more bytes must remain for valid S/C-VLAN tag and EtherType. if len(b) < 4 { return 0, io.ErrUnexpectedEOF } // Track how many bytes are consumed by VLAN tags. var n int switch tpid { case EtherTypeServiceVLAN: vlan := new(VLAN) if err := vlan.UnmarshalBinary(b[n : n+2]); err != nil { return 0, err } f.ServiceVLAN = vlan // Assume that a C-VLAN immediately trails an S-VLAN. if EtherType(binary.BigEndian.Uint16(b[n+2:n+4])) != EtherTypeVLAN { return 0, ErrInvalidVLAN } // 4 or more bytes must remain for valid C-VLAN tag and EtherType. n += 4 if len(b[n:]) < 4 { return 0, io.ErrUnexpectedEOF } // Continue to parse the C-VLAN. fallthrough case EtherTypeVLAN: vlan := new(VLAN) if err := vlan.UnmarshalBinary(b[n : n+2]); err != nil { return 0, err } f.VLAN = vlan f.EtherType = EtherType(binary.BigEndian.Uint16(b[n+2 : n+4])) n += 4 default: panic(fmt.Sprintf("unknown VLAN TPID: %04x", tpid)) } return n, nil } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/ethernet_test.go000066400000000000000000000260131366002132200253020ustar00rootroot00000000000000package ethernet import ( "bytes" "io" "net" "reflect" "testing" ) func TestFrameMarshalBinary(t *testing.T) { var tests = []struct { desc string f *Frame b []byte err error }{ { desc: "S-VLAN, no C-VLAN", f: &Frame{ // Contents don't matter. ServiceVLAN: &VLAN{}, }, err: ErrInvalidVLAN, }, { desc: "IPv4, no VLANs", f: &Frame{ Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1}, Source: net.HardwareAddr{1, 0, 1, 0, 1, 0}, EtherType: EtherTypeIPv4, Payload: bytes.Repeat([]byte{0}, 50), }, b: append([]byte{ 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0x08, 0x00, }, bytes.Repeat([]byte{0}, 50)...), }, { desc: "IPv6, C-VLAN: (PRI 1, ID 101)", f: &Frame{ Destination: net.HardwareAddr{1, 0, 1, 0, 1, 0}, Source: net.HardwareAddr{0, 1, 0, 1, 0, 1}, VLAN: &VLAN{ Priority: 1, ID: 101, }, EtherType: EtherTypeIPv6, Payload: bytes.Repeat([]byte{0}, 50), }, b: append([]byte{ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0x81, 0x00, 0x20, 0x65, 0x86, 0xDD, }, bytes.Repeat([]byte{0}, 50)...), }, { desc: "ARP, S-VLAN: (PRI 0, DROP, ID 100), C-VLAN: (PRI 1, ID 101)", f: &Frame{ Destination: Broadcast, Source: net.HardwareAddr{0, 1, 0, 1, 0, 1}, ServiceVLAN: &VLAN{ DropEligible: true, ID: 100, }, VLAN: &VLAN{ Priority: 1, ID: 101, }, EtherType: EtherTypeARP, Payload: bytes.Repeat([]byte{0}, 50), }, b: append([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 0, 1, 0, 1, 0x88, 0xa8, 0x10, 0x64, 0x81, 0x00, 0x20, 0x65, 0x08, 0x06, }, bytes.Repeat([]byte{0}, 50)...), }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { b, err := tt.f.MarshalBinary() if err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.b, b; !bytes.Equal(want, got) { t.Fatalf("unexpected Frame bytes:\n- want: %v\n- got: %v", want, got) } }) } } func TestFrameMarshalFCS(t *testing.T) { var tests = []struct { desc string f *Frame b []byte err error }{ { desc: "IPv4, no VLANs", f: &Frame{ Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1}, Source: net.HardwareAddr{1, 0, 1, 0, 1, 0}, EtherType: EtherTypeIPv4, Payload: bytes.Repeat([]byte{0}, 50), }, b: append( append( []byte{ 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0x08, 0x00, }, bytes.Repeat([]byte{0}, 50)..., ), []byte{159, 205, 24, 60}..., ), }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { b, err := tt.f.MarshalFCS() if err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.b, b; !bytes.Equal(want, got) { t.Fatalf("unexpected Frame bytes:\n- want: %v\n- got: %v", want, got) } }) } } func TestFrameUnmarshalBinary(t *testing.T) { var tests = []struct { desc string b []byte f *Frame err error }{ { desc: "nil buffer", err: io.ErrUnexpectedEOF, }, { desc: "short buffer", b: bytes.Repeat([]byte{0}, 13), err: io.ErrUnexpectedEOF, }, { desc: "1 short S-VLAN", b: []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0xa8, 0x00, }, err: io.ErrUnexpectedEOF, }, { desc: "1 short C-VLAN", b: []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0x00, 0x00, }, err: io.ErrUnexpectedEOF, }, { desc: "VLAN ID too large", b: []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0x00, 0xff, 0xff, 0x00, 0x00, }, err: ErrInvalidVLAN, }, { desc: "no C-VLAN after S-VLAN", b: []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0xa8, 0x20, 0x65, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, }, err: ErrInvalidVLAN, }, { desc: "short C-VLAN after S-VLAN", b: []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0xa8, 0x20, 0x65, 0x81, 0x00, 0x00, 0x00, }, err: io.ErrUnexpectedEOF, }, { desc: "go-fuzz crasher: VLAN tag without enough bytes for trailing EtherType", b: []byte("190734863281\x81\x0032"), err: io.ErrUnexpectedEOF, }, { desc: "0 VLANs detected, but 1 may have been present", b: bytes.Repeat([]byte{0}, 56), f: &Frame{ Destination: net.HardwareAddr{0, 0, 0, 0, 0, 0}, Source: net.HardwareAddr{0, 0, 0, 0, 0, 0}, Payload: bytes.Repeat([]byte{0}, 42), }, }, { desc: "IPv4, no VLANs", b: append([]byte{ 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0x08, 0x00, }, bytes.Repeat([]byte{0}, 50)...), f: &Frame{ Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1}, Source: net.HardwareAddr{1, 0, 1, 0, 1, 0}, EtherType: EtherTypeIPv4, Payload: bytes.Repeat([]byte{0}, 50), }, }, { desc: "IPv6, C-VLAN: (PRI 1, ID 101)", b: append([]byte{ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0x81, 0x00, 0x20, 0x65, 0x86, 0xDD, }, bytes.Repeat([]byte{0}, 50)...), f: &Frame{ Destination: net.HardwareAddr{1, 0, 1, 0, 1, 0}, Source: net.HardwareAddr{0, 1, 0, 1, 0, 1}, VLAN: &VLAN{ Priority: 1, ID: 101, }, EtherType: EtherTypeIPv6, Payload: bytes.Repeat([]byte{0}, 50), }, }, { desc: "ARP, S-VLAN: (PRI 0, DROP, ID 100), C-VLAN: (PRI 1, ID 101)", b: append([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 0, 1, 0, 1, 0x88, 0xa8, 0x10, 0x64, 0x81, 0x00, 0x20, 0x65, 0x08, 0x06, }, bytes.Repeat([]byte{0}, 50)...), f: &Frame{ Destination: Broadcast, Source: net.HardwareAddr{0, 1, 0, 1, 0, 1}, ServiceVLAN: &VLAN{ DropEligible: true, ID: 100, }, VLAN: &VLAN{ Priority: 1, ID: 101, }, EtherType: EtherTypeARP, Payload: bytes.Repeat([]byte{0}, 50), }, }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { f := new(Frame) if err := f.UnmarshalBinary(tt.b); err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.f, f; !reflect.DeepEqual(want, got) { t.Fatalf("unexpected Frame:\n- want: %v\n- got: %v", want, got) } }) } } func TestFrameUnmarshalFCS(t *testing.T) { var tests = []struct { desc string b []byte f *Frame err error }{ { desc: "too short for FCS", b: []byte{1, 2, 3}, err: io.ErrUnexpectedEOF, }, { desc: "invalid FCS", b: []byte{1, 2, 3, 4}, err: ErrInvalidFCS, }, { desc: "IPv4, no VLANs", b: append( append( []byte{ 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0x08, 0x00, }, bytes.Repeat([]byte{0}, 50)..., ), []byte{159, 205, 24, 60}..., ), f: &Frame{ Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1}, Source: net.HardwareAddr{1, 0, 1, 0, 1, 0}, EtherType: EtherTypeIPv4, Payload: bytes.Repeat([]byte{0}, 50), }, }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { f := new(Frame) if err := f.UnmarshalFCS(tt.b); err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.f, f; !reflect.DeepEqual(want, got) { t.Fatalf("unexpected Frame:\n- want: %v\n- got: %v", want, got) } }) } } // Benchmarks for Frame.MarshalBinary with varying VLAN tags and payloads func BenchmarkFrameMarshalBinary(b *testing.B) { f := &Frame{ Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameMarshalBinary(b, f) } func BenchmarkFrameMarshalBinaryCVLAN(b *testing.B) { f := &Frame{ VLAN: &VLAN{ Priority: PriorityBackground, ID: 10, }, Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameMarshalBinary(b, f) } func BenchmarkFrameMarshalBinarySVLANCVLAN(b *testing.B) { f := &Frame{ ServiceVLAN: &VLAN{ Priority: PriorityBackground, ID: 10, }, VLAN: &VLAN{ Priority: PriorityBestEffort, ID: 20, }, Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameMarshalBinary(b, f) } func BenchmarkFrameMarshalBinaryJumboPayload(b *testing.B) { f := &Frame{ Payload: make([]byte, 8192), } benchmarkFrameMarshalBinary(b, f) } func benchmarkFrameMarshalBinary(b *testing.B, f *Frame) { f.Destination = net.HardwareAddr{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad} f.Source = net.HardwareAddr{0xad, 0xbe, 0xef, 0xde, 0xad, 0xde} b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if _, err := f.MarshalBinary(); err != nil { b.Fatal(err) } } } // Benchmarks for Frame.MarshalFCS func BenchmarkFrameMarshalFCS(b *testing.B) { f := &Frame{ Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameMarshalFCS(b, f) } func benchmarkFrameMarshalFCS(b *testing.B, f *Frame) { f.Destination = net.HardwareAddr{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad} f.Source = net.HardwareAddr{0xad, 0xbe, 0xef, 0xde, 0xad, 0xde} b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if _, err := f.MarshalFCS(); err != nil { b.Fatal(err) } } } // Benchmarks for Frame.UnmarshalBinary with varying VLAN tags and payloads func BenchmarkFrameUnmarshalBinary(b *testing.B) { f := &Frame{ Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameUnmarshalBinary(b, f) } func BenchmarkFrameUnmarshalBinaryCVLAN(b *testing.B) { f := &Frame{ VLAN: &VLAN{ Priority: PriorityBackground, ID: 10, }, Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameUnmarshalBinary(b, f) } func BenchmarkFrameUnmarshalBinarySVLANCVLAN(b *testing.B) { f := &Frame{ ServiceVLAN: &VLAN{ Priority: PriorityBackground, ID: 10, }, VLAN: &VLAN{ Priority: PriorityBestEffort, ID: 20, }, Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameUnmarshalBinary(b, f) } func BenchmarkFrameUnmarshalBinaryJumboPayload(b *testing.B) { f := &Frame{ Payload: make([]byte, 8192), } benchmarkFrameUnmarshalBinary(b, f) } func benchmarkFrameUnmarshalBinary(b *testing.B, f *Frame) { f.Destination = net.HardwareAddr{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad} f.Source = net.HardwareAddr{0xad, 0xbe, 0xef, 0xde, 0xad, 0xde} fb, err := f.MarshalBinary() if err != nil { b.Fatal(err) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if err := f.UnmarshalBinary(fb); err != nil { b.Fatal(err) } } } // Benchmarks for Frame.UnmarshalFCS func BenchmarkFrameUnmarshalFCS(b *testing.B) { f := &Frame{ Payload: []byte{0, 1, 2, 3, 4}, } benchmarkFrameUnmarshalFCS(b, f) } func benchmarkFrameUnmarshalFCS(b *testing.B, f *Frame) { f.Destination = net.HardwareAddr{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad} f.Source = net.HardwareAddr{0xad, 0xbe, 0xef, 0xde, 0xad, 0xde} fb, err := f.MarshalFCS() if err != nil { b.Fatal(err) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if err := f.UnmarshalFCS(fb); err != nil { b.Fatal(err) } } } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/fuzz.go000066400000000000000000000005261366002132200234240ustar00rootroot00000000000000// +build gofuzz package ethernet func Fuzz(data []byte) int { f := new(Frame) if err := f.UnmarshalBinary(data); err != nil { return 0 } if _, err := f.MarshalBinary(); err != nil { panic(err) } if err := f.UnmarshalFCS(data); err != nil { return 0 } if _, err := f.MarshalFCS(); err != nil { panic(err) } return 1 } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/go.mod000066400000000000000000000004451366002132200232050ustar00rootroot00000000000000module github.com/mdlayher/ethernet go 1.12 require ( github.com/google/go-cmp v0.3.0 // indirect github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18 golang.org/x/net v0.0.0-20190603091049-60506f45cf65 // indirect golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4 // indirect ) golang-github-mdlayher-ethernet-0.0~git20190606.0394541/go.sum000066400000000000000000000027101366002132200232270ustar00rootroot00000000000000github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18 h1:zwOa3e/13D6veNIz6zzuqrd3eZEMF0dzD0AQWKcYSs4= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/net v0.0.0-20190419010253-1f3472d942ba/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190418153312-f0ce4c0180be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4 h1:3i7qG/aA9NUAzdnJHfhgxSKSmxbAebomYR5IZgFbC5Y= golang.org/x/sys v0.0.0-20190606122018-79a91cf218c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang-github-mdlayher-ethernet-0.0~git20190606.0394541/string.go000066400000000000000000000015221366002132200237310ustar00rootroot00000000000000// Code generated by "stringer -output=string.go -type=EtherType"; DO NOT EDIT. package ethernet import "fmt" const ( _EtherType_name_0 = "EtherTypeIPv4" _EtherType_name_1 = "EtherTypeARP" _EtherType_name_2 = "EtherTypeVLAN" _EtherType_name_3 = "EtherTypeIPv6" _EtherType_name_4 = "EtherTypeServiceVLAN" ) var ( _EtherType_index_0 = [...]uint8{0, 13} _EtherType_index_1 = [...]uint8{0, 12} _EtherType_index_2 = [...]uint8{0, 13} _EtherType_index_3 = [...]uint8{0, 13} _EtherType_index_4 = [...]uint8{0, 20} ) func (i EtherType) String() string { switch { case i == 2048: return _EtherType_name_0 case i == 2054: return _EtherType_name_1 case i == 33024: return _EtherType_name_2 case i == 34525: return _EtherType_name_3 case i == 34984: return _EtherType_name_4 default: return fmt.Sprintf("EtherType(%d)", i) } } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/vlan.go000066400000000000000000000067461366002132200234000ustar00rootroot00000000000000package ethernet import ( "encoding/binary" "errors" "io" ) const ( // VLANNone is a special VLAN ID which indicates that no VLAN is being // used in a Frame. In this case, the VLAN's other fields may be used // to indicate a Frame's priority. VLANNone = 0x000 // VLANMax is a reserved VLAN ID which may indicate a wildcard in some // management systems, but may not be configured or transmitted in a // VLAN tag. VLANMax = 0xfff ) var ( // ErrInvalidVLAN is returned when a VLAN tag is invalid due to one of the // following reasons: // - Priority of greater than 7 is detected // - ID of greater than 4094 (0xffe) is detected // - A customer VLAN does not follow a service VLAN (when using Q-in-Q) ErrInvalidVLAN = errors.New("invalid VLAN") ) // Priority is an IEEE P802.1p priority level. Priority can be any value from // 0 to 7. // // It is important to note that priority 1 (PriorityBackground) actually has // a lower priority than 0 (PriorityBestEffort). All other Priority constants // indicate higher priority as the integer values increase. type Priority uint8 // IEEE P802.1p recommended priority levels. Note that PriorityBackground has // a lower priority than PriorityBestEffort. const ( PriorityBackground Priority = 1 PriorityBestEffort Priority = 0 PriorityExcellentEffort Priority = 2 PriorityCriticalApplications Priority = 3 PriorityVideo Priority = 4 PriorityVoice Priority = 5 PriorityInternetworkControl Priority = 6 PriorityNetworkControl Priority = 7 ) // A VLAN is an IEEE 802.1Q Virtual LAN (VLAN) tag. A VLAN contains // information regarding traffic priority and a VLAN identifier for // a given Frame. type VLAN struct { // Priority specifies a IEEE P802.1p priority level. Priority can be any // value from 0 to 7. Priority Priority // DropEligible indicates if a Frame is eligible to be dropped in the // presence of network congestion. DropEligible bool // ID specifies the VLAN ID for a Frame. ID can be any value from 0 to // 4094 (0x000 to 0xffe), allowing up to 4094 VLANs. // // If ID is 0 (0x000, VLANNone), no VLAN is specified, and the other fields // simply indicate a Frame's priority. ID uint16 } // MarshalBinary allocates a byte slice and marshals a VLAN into binary form. func (v *VLAN) MarshalBinary() ([]byte, error) { b := make([]byte, 2) _, err := v.read(b) return b, err } // read reads data from a VLAN into b. read is used to marshal a VLAN into // binary form, but does not allocate on its own. func (v *VLAN) read(b []byte) (int, error) { // Check for VLAN priority in valid range if v.Priority > PriorityNetworkControl { return 0, ErrInvalidVLAN } // Check for VLAN ID in valid range if v.ID >= VLANMax { return 0, ErrInvalidVLAN } // 3 bits: priority ub := uint16(v.Priority) << 13 // 1 bit: drop eligible var drop uint16 if v.DropEligible { drop = 1 } ub |= drop << 12 // 12 bits: VLAN ID ub |= v.ID binary.BigEndian.PutUint16(b, ub) return 2, nil } // UnmarshalBinary unmarshals a byte slice into a VLAN. func (v *VLAN) UnmarshalBinary(b []byte) error { // VLAN tag is always 2 bytes if len(b) != 2 { return io.ErrUnexpectedEOF } // 3 bits: priority // 1 bit : drop eligible // 12 bits: VLAN ID ub := binary.BigEndian.Uint16(b[0:2]) v.Priority = Priority(uint8(ub >> 13)) v.DropEligible = ub&0x1000 != 0 v.ID = ub & 0x0fff // Check for VLAN ID in valid range if v.ID >= VLANMax { return ErrInvalidVLAN } return nil } golang-github-mdlayher-ethernet-0.0~git20190606.0394541/vlan_test.go000066400000000000000000000053731366002132200244320ustar00rootroot00000000000000package ethernet import ( "bytes" "io" "reflect" "testing" ) func TestVLANMarshalBinary(t *testing.T) { var tests = []struct { desc string v *VLAN b []byte err error }{ { desc: "VLAN priority too large", v: &VLAN{ Priority: 8, }, err: ErrInvalidVLAN, }, { desc: "VLAN ID too large", v: &VLAN{ ID: 4095, }, err: ErrInvalidVLAN, }, { desc: "empty VLAN", v: &VLAN{}, b: []byte{0x00, 0x00}, }, { desc: "VLAN: PRI 1, ID 101", v: &VLAN{ Priority: 1, ID: 101, }, b: []byte{0x20, 0x65}, }, { desc: "VLANs: PRI 0, DROP, ID 100", v: &VLAN{ DropEligible: true, ID: 100, }, b: []byte{0x10, 0x64}, }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { b, err := tt.v.MarshalBinary() if err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.b, b; !bytes.Equal(want, got) { t.Fatalf("unexpected VLAN bytes:\n- want: %v\n- got: %v", want, got) } }) } } func TestVLANUnmarshalBinary(t *testing.T) { var tests = []struct { desc string b []byte v *VLAN err error }{ { desc: "nil buffer", err: io.ErrUnexpectedEOF, }, { desc: "short buffer", b: []byte{0}, err: io.ErrUnexpectedEOF, }, { desc: "VLAN ID too large", b: []byte{0xff, 0xff}, err: ErrInvalidVLAN, }, { desc: "VLAN: PRI 1, ID 101", b: []byte{0x20, 0x65}, v: &VLAN{ Priority: 1, ID: 101, }, }, { desc: "VLAN: PRI 0, DROP, ID 100", b: []byte{0x10, 0x64}, v: &VLAN{ DropEligible: true, ID: 100, }, }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { v := new(VLAN) if err := v.UnmarshalBinary(tt.b); err != nil { if want, got := tt.err, err; want != got { t.Fatalf("unexpected error: %v != %v", want, got) } return } if want, got := tt.v, v; !reflect.DeepEqual(want, got) { t.Fatalf("unexpected VLAN:\n- want: %v\n- got: %v", want, got) } }) } } // Benchmarks for VLAN.MarshalBinary func BenchmarkVLANMarshalBinary(b *testing.B) { v := &VLAN{ Priority: PriorityBackground, ID: 10, } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if _, err := v.MarshalBinary(); err != nil { b.Fatal(err) } } } // Benchmarks for VLAN.UnmarshalBinary func BenchmarkVLANUnmarshalBinary(b *testing.B) { v := &VLAN{ Priority: PriorityBestEffort, ID: 20, } vb, err := v.MarshalBinary() if err != nil { b.Fatal(err) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { if err := v.UnmarshalBinary(vb); err != nil { b.Fatal(err) } } }