102 lines
2.2 KiB
Go
102 lines
2.2 KiB
Go
package peer
|
|
|
|
import (
|
|
"net/netip"
|
|
)
|
|
|
|
const (
|
|
packetTypeSyn = 1
|
|
packetTypeAck = 3
|
|
packetTypeProbe = 4
|
|
packetTypeAddrDiscovery = 5
|
|
packetTypeInit = 6
|
|
)
|
|
|
|
// ----------------------------------------------------------------------------
|
|
|
|
type packetInit struct {
|
|
TraceID uint64
|
|
Version uint64
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
|
|
type packetSyn struct {
|
|
TraceID uint64 // TraceID to match response w/ request.
|
|
SharedKey [32]byte // Our shared key.
|
|
Direct bool
|
|
PossibleAddrs [8]netip.AddrPort // Possible public addresses of the sender.
|
|
}
|
|
|
|
func (p packetSyn) Marshal(buf []byte) []byte {
|
|
return newBinWriter(buf).
|
|
Byte(packetTypeSyn).
|
|
Uint64(p.TraceID).
|
|
SharedKey(p.SharedKey).
|
|
Bool(p.Direct).
|
|
AddrPort8(p.PossibleAddrs).
|
|
Build()
|
|
}
|
|
|
|
func parsePacketSyn(buf []byte) (p packetSyn, err error) {
|
|
err = newBinReader(buf[1:]).
|
|
Uint64(&p.TraceID).
|
|
SharedKey(&p.SharedKey).
|
|
Bool(&p.Direct).
|
|
AddrPort8(&p.PossibleAddrs).
|
|
Error()
|
|
return
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
|
|
type packetAck struct {
|
|
TraceID uint64
|
|
ToAddr netip.AddrPort
|
|
PossibleAddrs [8]netip.AddrPort // Possible public addresses of the sender.
|
|
}
|
|
|
|
func (p packetAck) Marshal(buf []byte) []byte {
|
|
return newBinWriter(buf).
|
|
Byte(packetTypeAck).
|
|
Uint64(p.TraceID).
|
|
AddrPort(p.ToAddr).
|
|
AddrPort8(p.PossibleAddrs).
|
|
Build()
|
|
}
|
|
|
|
func parsePacketAck(buf []byte) (p packetAck, err error) {
|
|
err = newBinReader(buf[1:]).
|
|
Uint64(&p.TraceID).
|
|
AddrPort(&p.ToAddr).
|
|
AddrPort8(&p.PossibleAddrs).
|
|
Error()
|
|
return
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
|
|
// A probeReqPacket is sent from a client to a server to determine if direct
|
|
// UDP communication can be used.
|
|
type packetProbe struct {
|
|
TraceID uint64
|
|
}
|
|
|
|
func (p packetProbe) Marshal(buf []byte) []byte {
|
|
return newBinWriter(buf).
|
|
Byte(packetTypeProbe).
|
|
Uint64(p.TraceID).
|
|
Build()
|
|
}
|
|
|
|
func parsePacketProbe(buf []byte) (p packetProbe, err error) {
|
|
err = newBinReader(buf[1:]).
|
|
Uint64(&p.TraceID).
|
|
Error()
|
|
return
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
|
|
type packetLocalDiscovery struct{}
|