68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
package proxy
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"time"
|
|
)
|
|
|
|
type Packet interface {
|
|
Marshal() []byte
|
|
Contents() []byte
|
|
}
|
|
|
|
type SimplePacket struct {
|
|
Data []byte
|
|
timestamp time.Time
|
|
}
|
|
|
|
// create a packet from the raw data of an IP packet
|
|
func NewSimplePacket(data []byte) Packet {
|
|
return SimplePacket{
|
|
Data: data,
|
|
timestamp: time.Now(),
|
|
}
|
|
}
|
|
|
|
// rebuild a packet from the wrapped format
|
|
func UnmarshalSimplePacket(data []byte) (SimplePacket, error) {
|
|
p := SimplePacket{
|
|
Data: data[:len(data)-8],
|
|
}
|
|
|
|
unixTime := int64(binary.LittleEndian.Uint64(data[len(data)-8:]))
|
|
p.timestamp = time.Unix(unixTime, 0)
|
|
|
|
return p, nil
|
|
}
|
|
|
|
// get the raw data of the IP packet
|
|
func (p SimplePacket) Marshal() []byte {
|
|
footer := make([]byte, 8)
|
|
|
|
unixTime := uint64(p.timestamp.Unix())
|
|
binary.LittleEndian.PutUint64(footer, unixTime)
|
|
|
|
return append(p.Data, footer...)
|
|
}
|
|
|
|
func (p SimplePacket) Contents() []byte {
|
|
return p.Data
|
|
}
|
|
|
|
func AppendMac(b []byte, g MacGenerator) []byte {
|
|
mac := g.Generate(b)
|
|
b = append(b, mac...)
|
|
return b
|
|
}
|
|
|
|
func StripMac(b []byte, v MacVerifier) ([]byte, error) {
|
|
data := b[:len(b)-v.CodeLength()]
|
|
sum := b[len(b)-v.CodeLength():]
|
|
|
|
if err := v.Verify(data, sum); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return data, nil
|
|
}
|