dissertation-2-code/proxy/packet.go

68 lines
1.2 KiB
Go
Raw Normal View History

2020-10-22 21:19:26 +01:00
package proxy
import (
"encoding/binary"
"time"
)
2020-11-25 19:35:31 +00:00
type Packet interface {
2020-11-26 18:55:29 +00:00
Marshal() []byte
2020-11-26 22:39:07 +00:00
Contents() []byte
2020-11-25 19:35:31 +00:00
}
type SimplePacket struct {
2020-10-22 21:19:26 +01:00
Data []byte
timestamp time.Time
}
// create a packet from the raw data of an IP packet
2020-11-25 19:35:31 +00:00
func NewSimplePacket(data []byte) Packet {
return SimplePacket{
2020-10-25 15:36:34 +00:00
Data: data,
2020-10-22 21:19:26 +01:00
timestamp: time.Now(),
}
}
// rebuild a packet from the wrapped format
2020-11-26 18:55:29 +00:00
func UnmarshalSimplePacket(data []byte) (SimplePacket, error) {
2020-11-25 19:35:31 +00:00
p := SimplePacket{
2020-10-25 15:36:34 +00:00
Data: data[:len(data)-8],
2020-10-22 21:19:26 +01:00
}
unixTime := int64(binary.LittleEndian.Uint64(data[len(data)-8:]))
p.timestamp = time.Unix(unixTime, 0)
return p, nil
2020-10-22 21:19:26 +01:00
}
// get the raw data of the IP packet
2020-11-26 18:55:29 +00:00
func (p SimplePacket) Marshal() []byte {
footer := make([]byte, 8)
unixTime := uint64(p.timestamp.Unix())
binary.LittleEndian.PutUint64(footer, unixTime)
2020-11-26 18:55:29 +00:00
return append(p.Data, footer...)
}
2020-10-22 21:19:26 +01:00
2020-11-26 22:39:07 +00:00
func (p SimplePacket) Contents() []byte {
return p.Data
}
2020-11-26 18:55:29 +00:00
func AppendMac(b []byte, g MacGenerator) []byte {
mac := g.Generate(b)
b = append(b, mac...)
return b
}
2020-10-22 21:19:26 +01:00
2020-11-26 18:55:29 +00:00
func StripMac(b []byte, v MacVerifier) ([]byte, error) {
data := b[:len(b)-v.CodeLength()]
sum := b[len(b)-v.CodeLength():]
2020-10-22 21:19:26 +01:00
2020-11-26 18:55:29 +00:00
if err := v.Verify(data, sum); err != nil {
return nil, err
}
2020-10-22 21:19:26 +01:00
2020-11-26 18:55:29 +00:00
return data, nil
2020-10-22 21:19:26 +01:00
}