-
Notifications
You must be signed in to change notification settings - Fork 6
/
packet.go
96 lines (77 loc) · 2.56 KB
/
packet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright 2016 Platina Systems, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package arp
import (
"github.com/platinasystems/elib"
"github.com/platinasystems/vnet"
"github.com/platinasystems/vnet/ethernet"
"github.com/platinasystems/vnet/ip4"
"fmt"
"unsafe"
)
type Opcode uint16
const (
Request Opcode = 1 + iota
Reply
ReverseRequest
ReverseReply
)
var opcodeStrings = [...]string{
Request: "request",
Reply: "reply",
ReverseRequest: "reverse-request",
ReverseReply: "reverse-reply",
}
type L2Type uint16
const (
L2TypeEthernet L2Type = 1
)
var l2TypeStrings = [...]string{
L2TypeEthernet: "ethernet",
}
func (x Opcode) String() string { return elib.StringerWithFormat(opcodeStrings[:], int(x), "0x%x") }
func (x L2Type) String() string { return elib.StringerWithFormat(l2TypeStrings[:], int(x), "0x%x") }
type Header struct {
L2Type vnet.Uint16
L3Type vnet.Uint16
NL2AddressBytes uint8
NL3AddressBytes uint8
Opcode vnet.Uint16
}
func (h *Header) GetOpcode() Opcode { return Opcode(h.Opcode.ToHost()) }
func (h *Header) GetL2Type() L2Type { return L2Type(h.L2Type.ToHost()) }
func (h *Header) GetL3Type() ethernet.Type { return ethernet.Type(h.L3Type.ToHost()) }
func (x Opcode) FromHost() vnet.Uint16 { return vnet.Uint16(x).FromHost() }
func (x L2Type) FromHost() vnet.Uint16 { return vnet.Uint16(x).FromHost() }
// Typical case for arp: ip4 over ethernet.
type EthernetIp4Addr struct {
Ethernet ethernet.Address
Ip4 ip4.Address
}
type HeaderEthernetIp4 struct {
Header
Addrs [2]EthernetIp4Addr
}
const HeaderEthernetIp4Bytes = 8 + 6 + 4
func (h *HeaderEthernetIp4) String() (s string) {
s = fmt.Sprintf("%s, l2/l3 type/size %s/%d %s/%d, %s/%s -> %s/%s",
h.GetOpcode().String(),
h.GetL2Type().String(), h.Header.NL2AddressBytes,
h.GetL3Type().String(), h.Header.NL3AddressBytes,
&h.Addrs[0].Ethernet, &h.Addrs[0].Ip4,
&h.Addrs[1].Ethernet, &h.Addrs[1].Ip4)
return
}
// Implement vnet.Header interface.
func (h *HeaderEthernetIp4) Len() uint { return HeaderEthernetIp4Bytes }
func (h *HeaderEthernetIp4) Write(b []byte) {
type t struct{ data [HeaderEthernetIp4Bytes]byte }
i := (*t)(unsafe.Pointer(h))
copy(b[:], i.data[:])
}
func (h *HeaderEthernetIp4) Read(b []byte) vnet.PacketHeader {
return (*HeaderEthernetIp4)(vnet.Pointer(b))
}
func GetHeader(r *vnet.Ref) *HeaderEthernetIp4 { return (*HeaderEthernetIp4)(r.Data()) }
func GetPacketHeader(r *vnet.Ref) vnet.PacketHeader { return GetHeader(r) }