74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
package peer
|
|
|
|
import (
|
|
"net/netip"
|
|
"time"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
"vppn/peer/control"
|
|
"vppn/peer/wginterface"
|
|
)
|
|
|
|
type PeerState string
|
|
|
|
const (
|
|
StateRelayed = PeerState("RELAY")
|
|
StateProbing = PeerState("PROBE")
|
|
StateDirect = PeerState("DIRECT")
|
|
)
|
|
|
|
type Peer struct {
|
|
wgPeer wgtypes.Peer
|
|
VPNIP netip.Addr // VPN IP address.
|
|
IsRelay bool // Peer is a relay.
|
|
IsPublic bool // Peer has a public IP.
|
|
Endpoint4 netip.AddrPort // Reported IPv4 endpoint.
|
|
Endpoint6 netip.AddrPort // Reported IPv6 endpoint.
|
|
RTT time.Duration // Round-trip time.
|
|
Role control.Role // Client initiates pings; server responds.
|
|
}
|
|
|
|
// PubKey is the wireguard public key.
|
|
func (p *Peer) PubKey() wgtypes.Key {
|
|
return p.wgPeer.PublicKey
|
|
}
|
|
|
|
func (p *Peer) State() PeerState {
|
|
if len(p.wgPeer.AllowedIPs) > 0 {
|
|
return StateDirect
|
|
}
|
|
if p.wgPeer.Endpoint == nil {
|
|
return StateRelayed
|
|
}
|
|
return StateProbing
|
|
}
|
|
|
|
func (p *Peer) WGEndpoint() netip.AddrPort {
|
|
ep := p.wgPeer.Endpoint
|
|
if ep == nil {
|
|
return netip.AddrPort{}
|
|
}
|
|
addr, ok := netip.AddrFromSlice(ep.IP)
|
|
if !ok {
|
|
return netip.AddrPort{}
|
|
}
|
|
return netip.AddrPortFrom(addr.Unmap(), uint16(ep.Port))
|
|
}
|
|
|
|
func (p *Peer) LastHandshakeTime() time.Time {
|
|
return p.wgPeer.LastHandshakeTime
|
|
}
|
|
|
|
func (p *Peer) Up() bool {
|
|
return time.Since(p.wgPeer.LastHandshakeTime) < wginterface.SessionTimeout
|
|
}
|
|
|
|
func (p *Peer) CanRelay() bool {
|
|
return p.IsRelay && p.Up()
|
|
}
|
|
|
|
func (p *Peer) PreferredEndpoint() netip.AddrPort {
|
|
return preferredEndpoint(p.Endpoint4, p.Endpoint6)
|
|
}
|