netshovel/packet.go

82 lines
1.6 KiB
Go
Raw Normal View History

package netshovel
2018-07-23 09:58:31 -06:00
import (
2018-07-23 17:48:14 -06:00
"encoding/hex"
2018-07-23 09:58:31 -06:00
"fmt"
"strings"
"time"
"github.com/dirtbags/netshovel/gapstring"
)
2018-07-23 15:34:22 -06:00
type PacketFactory func()Packet
2018-07-23 17:48:14 -06:00
type Field struct {
key, value string
}
2018-07-23 09:58:31 -06:00
type Packet struct {
2018-07-23 15:34:22 -06:00
Name string
2018-07-23 09:58:31 -06:00
Opcode int
Description string
When time.Time
Payload gapstring.GapString
2018-07-23 17:48:14 -06:00
Fields []Field
2018-07-23 09:58:31 -06:00
}
var never = time.Unix(0, 0)
func NewPacket() Packet {
return Packet{
Opcode: -1,
Description: "Undefined",
When: never,
Payload: gapstring.GapString{},
2018-07-23 17:48:14 -06:00
Fields: []Field{},
2018-07-23 09:58:31 -06:00
}
}
func (pkt *Packet) Describe() string {
out := new(strings.Builder)
2018-07-23 17:48:14 -06:00
fmt.Fprintf(out, " %s Opcode %d: %s\n",
pkt.When.UTC().Format(time.RFC3339Nano),
2018-07-23 09:58:31 -06:00
pkt.Opcode,
pkt.Description,
)
2018-07-23 17:48:14 -06:00
for _, f := range(pkt.Fields) {
fmt.Fprintf(out, " %s: %s\n", f.key, f.value)
2018-07-23 15:34:22 -06:00
}
fmt.Fprint(out, pkt.Payload.Hexdump())
return out.String()
}
2018-07-23 17:48:14 -06:00
2018-07-23 15:34:22 -06:00
func (pkt *Packet) Set(key, value string) {
2018-07-23 17:48:14 -06:00
pkt.Fields = append(pkt.Fields, Field{key, value})
}
func (pkt *Packet) SetString(key, value string) {
pkt.Set(key, fmt.Sprintf("%#v", value))
}
func (pkt *Packet) SetInt(key string, value int) {
pkt.Set(key, fmt.Sprintf("%d == 0x%x", value, value))
}
func (pkt *Packet) SetUint(key string, value uint) {
pkt.Set(key, fmt.Sprintf("%d == 0x%x", value, value))
}
func (pkt *Packet) SetUint32(key string, value uint32) {
pkt.Set(key, fmt.Sprintf("%d == 0x%04x", value, value))
}
func (pkt *Packet) SetBytes(key string, value []byte) {
pkt.Set(key, hex.EncodeToString(value))
}
func (pkt *Packet) SetGapString(key string, value gapstring.GapString) {
pkt.Set(key, fmt.Sprintf("%s %s", value.HexString(), value.Runes()))
2018-07-23 09:58:31 -06:00
}