daemon

package
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultKeepaliveInterval     = 30 * time.Second
	DefaultIdleTimeout           = 120 * time.Second
	DefaultIdleSweepInterval     = 15 * time.Second
	DefaultSYNRateLimit          = 100
	DefaultMaxConnectionsPerPort = 1024
	DefaultMaxTotalConnections   = 4096
	DefaultTimeWaitDuration      = 10 * time.Second
)

Default tuning constants (used when Config fields are zero).

View Source
const (
	DialDirectRetries    = 3                      // direct connection attempts before relay
	DialMaxRetries       = 6                      // total attempts (direct + relay)
	DialInitialRTO       = 1 * time.Second        // initial SYN retransmission timeout
	DialMaxRTO           = 8 * time.Second        // max backoff for SYN retransmission
	DialCheckInterval    = 10 * time.Millisecond  // poll interval for state changes during dial
	RetxCheckInterval    = 100 * time.Millisecond // retransmission check ticker
	MaxRetxAttempts      = 8                      // abandon connection after this many retransmissions
	HeartbeatReregThresh = 3                      // heartbeat failures before re-registration
	SYNBucketAge         = 10 * time.Second       // stale per-source SYN bucket reap threshold
)

Dial and retransmission constants.

View Source
const (
	ZeroWinProbeInitial = 500 * time.Millisecond // initial zero-window probe interval
	ZeroWinProbeMax     = 30 * time.Second       // max zero-window probe backoff
)

Zero-window probe constants.

View Source
const (
	HandshakeRequest = "handshake_request"
	HandshakeAccept  = "handshake_accept"
	HandshakeReject  = "handshake_reject"
	HandshakeRevoke  = "handshake_revoke"
)

Handshake message types

View Source
const (
	CmdBind              byte = 0x01
	CmdBindOK            byte = 0x02
	CmdDial              byte = 0x03
	CmdDialOK            byte = 0x04
	CmdAccept            byte = 0x05
	CmdSend              byte = 0x06
	CmdRecv              byte = 0x07
	CmdClose             byte = 0x08
	CmdCloseOK           byte = 0x09
	CmdError             byte = 0x0A
	CmdSendTo            byte = 0x0B
	CmdRecvFrom          byte = 0x0C
	CmdInfo              byte = 0x0D
	CmdInfoOK            byte = 0x0E
	CmdHandshake         byte = 0x0F // driver → daemon: handshake request/approve/reject
	CmdHandshakeOK       byte = 0x10
	CmdResolveHostname   byte = 0x11
	CmdResolveHostnameOK byte = 0x12
	CmdSetHostname       byte = 0x13
	CmdSetHostnameOK     byte = 0x14
	CmdSetVisibility     byte = 0x15
	CmdSetVisibilityOK   byte = 0x16
	CmdDeregister        byte = 0x17
	CmdDeregisterOK      byte = 0x18
	CmdSetTags           byte = 0x19
	CmdSetTagsOK         byte = 0x1A
	CmdSetWebhook        byte = 0x1B
	CmdSetWebhookOK      byte = 0x1C
	CmdSetTaskExec       byte = 0x1D
	CmdSetTaskExecOK     byte = 0x1E
)

IPC commands (daemon ↔ driver)

View Source
const (
	SubHandshakeSend    byte = 0x01
	SubHandshakeApprove byte = 0x02
	SubHandshakeReject  byte = 0x03
	SubHandshakePending byte = 0x04
	SubHandshakeTrusted byte = 0x05
	SubHandshakeRevoke  byte = 0x06
)

Handshake IPC sub-commands

View Source
const (
	InitialCongWin = 10 * MaxSegmentSize          // 40 KB initial congestion window (IW10, RFC 6928)
	MaxCongWin     = 1024 * 1024                  // 1 MB max congestion window
	MaxSegmentSize = 4096                         // MTU for virtual segments
	RecvBufSize    = 512                          // receive buffer channel capacity (segments)
	MaxRecvWin     = RecvBufSize * MaxSegmentSize // 2 MB max receive window
	MaxOOOBuf      = 128                          // max out-of-order segments buffered per connection
	AcceptQueueLen = 64                           // listener accept channel capacity
	SendBufLen     = 256                          // send buffer channel capacity (segments)
)

Default window parameters

View Source
const (
	ClockGranularity = 10 * time.Millisecond  // minimum RTTVAR for RTO calculation
	RTOMin           = 200 * time.Millisecond // minimum retransmission timeout
	RTOMax           = 10 * time.Second       // maximum retransmission timeout
	InitialRTO       = 1 * time.Second        // initial retransmission timeout
)

RTO parameters (RFC 6298)

View Source
const DelayedACKThreshold = 2

DelayedACKThreshold is the number of segments to receive before sending an ACK immediately.

View Source
const DelayedACKTimeout = 40 * time.Millisecond

DelayedACKTimeout is the max time to delay an ACK (RFC 1122 suggests 500ms max, we use 40ms).

View Source
const NagleTimeout = 40 * time.Millisecond

NagleTimeout is the maximum time to buffer small writes before flushing.

View Source
const RecvChSize = 1024

RecvChSize is the capacity of the incoming packet channel.

Variables

This section is empty.

Functions

func DiscoverEndpoint

func DiscoverEndpoint(beaconAddr string, nodeID uint32, conn *net.UDPConn) (*net.UDPAddr, error)

DiscoverEndpoint sends a STUN discover to the beacon and returns the observed public endpoint.

func EncodeSACK

func EncodeSACK(blocks []SACKBlock) []byte

EncodeSACK encodes SACK blocks into a byte slice. Format: "SACK" (4 bytes) + count (1 byte) + N * 8 bytes (Left:4, Right:4).

Types

type Config

type Config struct {
	RegistryAddr        string
	BeaconAddr          string
	ListenAddr          string // UDP listen address for tunnel traffic
	SocketPath          string // Unix socket path for IPC
	Encrypt             bool   // enable tunnel-layer encryption (X25519 + AES-256-GCM)
	RegistryTLS         bool   // use TLS for registry connection
	RegistryFingerprint string // hex SHA-256 fingerprint for TLS cert pinning
	IdentityPath        string // path to persist Ed25519 identity (empty = no persistence)
	Owner               string // owner identifier (email) for key rotation recovery

	Endpoint string // fixed public endpoint (host:port) — skips STUN discovery (for cloud VMs)
	Public   bool   // make this node's endpoint publicly discoverable
	Hostname string // hostname for discovery (empty = none)

	// Built-in services
	DisableEcho         bool // disable built-in echo service (port 7)
	DisableDataExchange bool // disable built-in data exchange service (port 1001)
	DisableEventStream  bool // disable built-in event stream service (port 1002)

	// Webhook
	WebhookURL string // HTTP(S) endpoint for event notifications (empty = disabled)

	// Tuning (zero = use defaults)
	KeepaliveInterval     time.Duration // default 30s
	IdleTimeout           time.Duration // default 120s
	SYNRateLimit          int           // default 100
	MaxConnectionsPerPort int           // default 1024
	MaxTotalConnections   int           // default 4096
	TimeWaitDuration      time.Duration // default 10s
}

type ConnState

type ConnState uint8
const (
	StateClosed ConnState = iota
	StateListen
	StateSynSent
	StateSynReceived
	StateEstablished
	StateFinWait
	StateCloseWait
	StateTimeWait
)

func (ConnState) String

func (s ConnState) String() string

type ConnStats

type ConnStats struct {
	BytesSent   uint64 // total user bytes sent
	BytesRecv   uint64 // total user bytes received
	SegsSent    uint64 // data segments sent
	SegsRecv    uint64 // data segments received
	Retransmits uint64 // timeout-based retransmissions
	FastRetx    uint64 // fast retransmissions (3 dup ACKs)
	SACKRecv    uint64 // SACK blocks received from peer
	SACKSent    uint64 // SACK blocks sent to peer
	DupACKs     uint64 // duplicate ACKs received
}

ConnStats tracks per-connection traffic and reliability metrics.

type Connection

type Connection struct {
	Mu           sync.Mutex // protects State, SendSeq, RecvAck, LastActivity, Stats
	ID           uint32
	LocalAddr    protocol.Addr // our virtual address
	LocalPort    uint16
	RemoteAddr   protocol.Addr
	RemotePort   uint16
	State        ConnState
	LastActivity time.Time // updated on send/recv
	// Reliable delivery
	SendSeq uint32
	RecvAck uint32
	SendBuf chan []byte
	RecvBuf chan []byte
	// Sliding window + retransmission (send side)
	RetxMu        sync.Mutex
	Unacked       []*retxEntry           // ordered by seq
	LastAck       uint32                 // highest cumulative ACK received
	DupAckCount   int                    // consecutive duplicate ACKs
	RTO           time.Duration          // retransmission timeout
	SRTT          time.Duration          // smoothed RTT
	RTTVAR        time.Duration          // RTT variance (RFC 6298)
	CongWin       int                    // congestion window in bytes
	SSThresh      int                    // slow-start threshold
	InRecovery    bool                   // true during timeout loss recovery
	RecoveryPoint uint32                 // highest seq sent when entering recovery
	RetxStop      chan struct{}          // closed to stop retx goroutine
	RetxSend      func(*protocol.Packet) // callback to send retransmitted packets
	WindowCh      chan struct{}          // signaled when window opens up
	PeerRecvWin   int                    // peer's advertised receive window (0 = unknown/unlimited)
	// Nagle algorithm (write coalescing)
	NagleBuf []byte        // pending small write data
	NagleMu  sync.Mutex    // protects NagleBuf
	NagleCh  chan struct{} // signaled when Nagle should flush
	NoDelay  bool          // if true, disable Nagle (send immediately)
	// Receive window (reassembly)
	RecvMu      sync.Mutex
	ExpectedSeq uint32         // next in-order seq expected
	OOOBuf      []*recvSegment // out-of-order buffer
	// Delayed ACK
	AckMu       sync.Mutex  // protects PendingACKs and ACKTimer
	PendingACKs int         // count of unacked received segments
	ACKTimer    *time.Timer // delayed ACK timer
	// Close
	CloseOnce  sync.Once // ensures RecvBuf is closed exactly once
	RecvClosed bool      // true after RecvBuf is closed (guarded by RecvMu)
	// Retransmit state
	LastRetxTime time.Time // when last RTO retransmission fired (prevents cascading)
	// Per-connection statistics
	Stats ConnStats
}

func (*Connection) BytesInFlight

func (c *Connection) BytesInFlight() int

BytesInFlight returns total unacknowledged bytes.

func (*Connection) CloseRecvBuf

func (c *Connection) CloseRecvBuf()

CloseRecvBuf safely closes RecvBuf exactly once. Both the flag set and channel close happen under RecvMu so DeliverInOrder can never send to a closed channel.

func (*Connection) DeliverInOrder

func (c *Connection) DeliverInOrder(seq uint32, data []byte) uint32

DeliverInOrder handles an incoming data segment, buffering out-of-order segments and delivering in-order data to RecvBuf. Returns the cumulative ACK number (next expected seq).

To avoid deadlocking routeLoop (C1 fix), segments are collected under RecvMu and delivered to RecvBuf after releasing the lock.

func (*Connection) EffectiveWindow

func (c *Connection) EffectiveWindow() int

EffectiveWindow returns the effective send window (minimum of congestion window and peer's advertised receive window). Must be called with RetxMu held.

func (*Connection) ProcessAck

func (c *Connection) ProcessAck(ack uint32, pureACK bool)

ProcessAck removes segments acknowledged by the given ack number, updates RTT estimate, detects duplicate ACKs for fast retransmit, and grows the congestion window. If pureACK is true, duplicate ACK detection is enabled. Data packets with piggybacked ACKs should pass pureACK=false to avoid false fast retransmits (RFC 5681 Section 3.2).

func (*Connection) ProcessSACK

func (c *Connection) ProcessSACK(blocks []SACKBlock)

ProcessSACK marks unacked segments that are covered by SACK blocks. This prevents unnecessary retransmission of segments the peer already has.

func (*Connection) RecvWindow

func (c *Connection) RecvWindow() uint16

RecvWindow returns the number of free segments in the receive buffer, used as the advertised receive window.

func (*Connection) SACKBlocks

func (c *Connection) SACKBlocks() []SACKBlock

SACKBlocks returns SACK blocks describing out-of-order received segments. Must be called with RecvMu held.

func (*Connection) TrackSend

func (c *Connection) TrackSend(seq uint32, data []byte)

TrackSend adds a sent data segment to the retransmission buffer.

func (*Connection) WindowAvailable

func (c *Connection) WindowAvailable() bool

WindowAvailable returns true if the effective window allows more data. Must be called with RetxMu held.

type ConnectionInfo

type ConnectionInfo struct {
	ID          uint32
	LocalPort   uint16
	RemoteAddr  string
	RemotePort  uint16
	State       string
	SendSeq     uint32
	RecvAck     uint32
	CongWin     int
	SSThresh    int
	InFlight    int
	SRTT        time.Duration
	RTTVAR      time.Duration
	Unacked     int
	OOOBuf      int
	PeerRecvWin int
	RecvWin     int
	InRecovery  bool
	Stats       ConnStats
}

ConnectionInfo describes an active connection for diagnostics.

type Daemon

type Daemon struct {
	// contains filtered or unexported fields
}

func New

func New(cfg Config) *Daemon

func (*Daemon) Addr

func (d *Daemon) Addr() protocol.Addr

func (*Daemon) CloseConnection

func (d *Daemon) CloseConnection(conn *Connection)

CloseConnection sends FIN and enters TIME_WAIT.

func (*Daemon) DialConnection

func (d *Daemon) DialConnection(dstAddr protocol.Addr, dstPort uint16) (*Connection, error)

DialConnection initiates a connection to a remote address:port.

func (*Daemon) Identity

func (d *Daemon) Identity() *crypto.Identity

Identity returns the daemon's Ed25519 identity (may be nil if unset).

func (*Daemon) Info

func (d *Daemon) Info() *DaemonInfo

Info returns current daemon status.

func (*Daemon) NodeID

func (d *Daemon) NodeID() uint32

func (*Daemon) SendData

func (d *Daemon) SendData(conn *Connection, data []byte) error

SendData sends data over an established connection. Implements Nagle's algorithm: small writes are coalesced into MSS-sized segments unless NoDelay is set. Large writes (>= MSS) are sent immediately.

func (*Daemon) SendDatagram

func (d *Daemon) SendDatagram(dstAddr protocol.Addr, dstPort uint16, data []byte) error

SendDatagram sends an unreliable packet. If the destination is a broadcast address, sends to all members of that network.

func (*Daemon) SetWebhookURL

func (d *Daemon) SetWebhookURL(url string)

SetWebhookURL hot-swaps the webhook client at runtime. An empty URL disables the webhook (all Emit calls become no-ops).

func (*Daemon) Start

func (d *Daemon) Start() error

func (*Daemon) Stop

func (d *Daemon) Stop() error

type DaemonInfo

type DaemonInfo struct {
	NodeID             uint32
	Address            string
	Hostname           string
	Uptime             time.Duration
	Connections        int
	Ports              int
	Peers              int
	EncryptedPeers     int
	AuthenticatedPeers int
	Encrypt            bool
	Identity           bool   // true if identity is persisted
	PublicKey          string // base64 Ed25519 public key (empty if no identity)
	Owner              string // owner identifier for key rotation recovery
	BytesSent          uint64
	BytesRecv          uint64
	PktsSent           uint64
	PktsRecv           uint64
	PeerList           []PeerInfo
	ConnList           []ConnectionInfo
}

DaemonInfo holds status information about the running daemon.

type HandshakeManager

type HandshakeManager struct {
	// contains filtered or unexported fields
}

HandshakeManager handles the trust handshake protocol on port 444.

func NewHandshakeManager

func NewHandshakeManager(d *Daemon) *HandshakeManager

func (*HandshakeManager) ApproveHandshake

func (hm *HandshakeManager) ApproveHandshake(peerNodeID uint32) error

ApproveHandshake approves a pending handshake request.

func (*HandshakeManager) IsTrusted

func (hm *HandshakeManager) IsTrusted(nodeID uint32) bool

IsTrusted returns whether a peer has been approved.

func (*HandshakeManager) PendingRequests

func (hm *HandshakeManager) PendingRequests() []PendingHandshake

PendingRequests returns all pending handshake requests.

func (*HandshakeManager) RejectHandshake

func (hm *HandshakeManager) RejectHandshake(peerNodeID uint32, reason string) error

RejectHandshake rejects a pending handshake request.

func (*HandshakeManager) RevokeTrust

func (hm *HandshakeManager) RevokeTrust(peerNodeID uint32) error

RevokeTrust removes a peer from the trusted set and notifies both the registry and the peer itself. Either party can revoke unilaterally.

func (*HandshakeManager) SendRequest

func (hm *HandshakeManager) SendRequest(peerNodeID uint32, justification string) error

SendRequest sends a handshake request to a remote node. First tries direct connection (port 444). If that fails (e.g. private node), falls back to relaying through the registry.

func (*HandshakeManager) SetWebhook

func (hm *HandshakeManager) SetWebhook(wc *WebhookClient)

SetWebhook configures the webhook client for event notifications.

func (*HandshakeManager) Start

func (hm *HandshakeManager) Start() error

Start binds port 444 and begins handling handshake connections.

func (*HandshakeManager) Stop

func (hm *HandshakeManager) Stop()

Stop waits for all background RPCs to finish and stops the replay reaper.

func (*HandshakeManager) TrustedPeers

func (hm *HandshakeManager) TrustedPeers() []TrustRecord

TrustedPeers returns all trusted peers.

type HandshakeMsg

type HandshakeMsg struct {
	Type          string `json:"type"`
	NodeID        uint32 `json:"node_id"`
	PublicKey     string `json:"public_key"`    // base64 Ed25519 public key
	Justification string `json:"justification"` // why the sender wants to connect
	Signature     string `json:"signature"`     // Ed25519 sig over "handshake:<node_id>:<peer_id>"
	Reason        string `json:"reason"`        // rejection reason
	Timestamp     int64  `json:"timestamp"`
}

HandshakeMsg is the wire format for handshake protocol messages on port 444.

type IPCServer

type IPCServer struct {
	// contains filtered or unexported fields
}

IPCServer handles connections from local drivers over Unix socket.

func NewIPCServer

func NewIPCServer(socketPath string, d *Daemon) *IPCServer

func (*IPCServer) Close

func (s *IPCServer) Close() error

func (*IPCServer) DeliverDatagram

func (s *IPCServer) DeliverDatagram(srcAddr protocol.Addr, srcPort uint16, dstPort uint16, data []byte)

Deliver a datagram to any listening IPC client

func (*IPCServer) Start

func (s *IPCServer) Start() error

type IncomingPacket

type IncomingPacket struct {
	Packet *protocol.Packet
	From   *net.UDPAddr
}

type Listener

type Listener struct {
	Port     uint16
	AcceptCh chan *Connection
}

type PeerInfo

type PeerInfo struct {
	NodeID        uint32
	Endpoint      string
	Encrypted     bool
	Authenticated bool // true if peer proved Ed25519 identity
	Relay         bool // true if using beacon relay (symmetric NAT)
}

PeerInfo describes a known peer.

type PendingHandshake

type PendingHandshake struct {
	NodeID        uint32
	PublicKey     string
	Justification string
	ReceivedAt    time.Time
}

PendingHandshake is an unapproved incoming request.

type PortManager

type PortManager struct {
	// contains filtered or unexported fields
}

PortManager handles virtual port binding and connection tracking.

func NewPortManager

func NewPortManager() *PortManager

func (*PortManager) AllConnections

func (pm *PortManager) AllConnections() []*Connection

AllConnections returns all active connections.

func (*PortManager) AllocEphemeralPort

func (pm *PortManager) AllocEphemeralPort() uint16

func (*PortManager) Bind

func (pm *PortManager) Bind(port uint16) (*Listener, error)

func (*PortManager) ConnectionCountForPort

func (pm *PortManager) ConnectionCountForPort(port uint16) int

ConnectionCountForPort returns the number of active connections on a port.

func (*PortManager) ConnectionList

func (pm *PortManager) ConnectionList() []ConnectionInfo

ConnectionList returns info about all active connections.

func (*PortManager) FindConnection

func (pm *PortManager) FindConnection(localPort uint16, remoteAddr protocol.Addr, remotePort uint16) *Connection

func (*PortManager) GetConnection

func (pm *PortManager) GetConnection(id uint32) *Connection

func (*PortManager) GetListener

func (pm *PortManager) GetListener(port uint16) *Listener

func (*PortManager) IdleConnections

func (pm *PortManager) IdleConnections(maxIdle time.Duration) []*Connection

IdleConnections returns connections that have been idle longer than the given duration.

func (*PortManager) NewConnection

func (pm *PortManager) NewConnection(localPort uint16, remoteAddr protocol.Addr, remotePort uint16) *Connection

func (*PortManager) RemoveConnection

func (pm *PortManager) RemoveConnection(id uint32)

func (*PortManager) StaleConnections

func (pm *PortManager) StaleConnections(timeWaitDur time.Duration) []*Connection

StaleConnections returns connections in a terminal state that should be cleaned up. CLOSED, FIN_WAIT, CLOSE_WAIT are cleaned up immediately. TIME_WAIT connections are cleaned up after timeWaitDur.

func (*PortManager) TotalActiveConnections

func (pm *PortManager) TotalActiveConnections() int

TotalActiveConnections returns the total number of non-closed connections.

func (*PortManager) Unbind

func (pm *PortManager) Unbind(port uint16)

type SACKBlock

type SACKBlock struct {
	Left  uint32
	Right uint32
}

SACKBlock represents a contiguous range of received bytes. Left is the seq of the first byte; Right is the seq of the first byte AFTER the range.

func DecodeSACK

func DecodeSACK(data []byte) ([]SACKBlock, bool)

DecodeSACK parses SACK blocks from an ACK payload. Returns nil, false if the payload is not SACK data.

type TrustRecord

type TrustRecord struct {
	NodeID     uint32
	PublicKey  string // base64 Ed25519 pubkey
	ApprovedAt time.Time
	Mutual     bool   // true if both sides initiated
	Network    uint16 // non-zero if trust is via network membership
}

TrustRecord holds information about a trusted peer.

type TunnelManager

type TunnelManager struct {

	// Metrics
	BytesSent uint64
	BytesRecv uint64
	PktsSent  uint64
	PktsRecv  uint64
	// contains filtered or unexported fields
}

TunnelManager manages real UDP tunnels to peer daemons.

func NewTunnelManager

func NewTunnelManager() *TunnelManager

func (*TunnelManager) AddPeer

func (tm *TunnelManager) AddPeer(nodeID uint32, addr *net.UDPAddr)

AddPeer registers a peer's real UDP endpoint.

func (*TunnelManager) Close

func (tm *TunnelManager) Close() error

func (*TunnelManager) EnableEncryption

func (tm *TunnelManager) EnableEncryption() error

EnableEncryption generates an X25519 keypair and enables tunnel encryption.

func (*TunnelManager) HasCrypto

func (tm *TunnelManager) HasCrypto(nodeID uint32) bool

HasCrypto returns true if we have an encryption context for a peer (proving prior key exchange).

func (*TunnelManager) HasPeer

func (tm *TunnelManager) HasPeer(nodeID uint32) bool

HasPeer checks if we have a tunnel to a node.

func (*TunnelManager) IsEncrypted

func (tm *TunnelManager) IsEncrypted(nodeID uint32) bool

IsEncrypted returns true if the tunnel to a peer is encrypted.

func (*TunnelManager) IsRelayPeer

func (tm *TunnelManager) IsRelayPeer(nodeID uint32) bool

IsRelayPeer returns true if the peer is in relay mode.

func (*TunnelManager) Listen

func (tm *TunnelManager) Listen(addr string) error

Listen starts the UDP listener for incoming tunnel traffic.

func (*TunnelManager) LocalAddr

func (tm *TunnelManager) LocalAddr() net.Addr

func (*TunnelManager) PeerCount

func (tm *TunnelManager) PeerCount() int

PeerCount returns the number of known peers.

func (*TunnelManager) PeerList

func (tm *TunnelManager) PeerList() []PeerInfo

PeerList returns all known peers and their endpoints.

func (*TunnelManager) RecvCh

func (tm *TunnelManager) RecvCh() <-chan *IncomingPacket

RecvCh returns the channel for incoming packets.

func (*TunnelManager) RegisterWithBeacon

func (tm *TunnelManager) RegisterWithBeacon()

RegisterWithBeacon sends a MsgDiscover to the beacon from the tunnel socket using the real nodeID, so the beacon knows our endpoint for punch coordination.

func (*TunnelManager) RemovePeer

func (tm *TunnelManager) RemovePeer(nodeID uint32)

RemovePeer removes a peer.

func (*TunnelManager) RequestHolePunch

func (tm *TunnelManager) RequestHolePunch(targetNodeID uint32)

RequestHolePunch asks the beacon to coordinate NAT hole-punching with a target peer.

func (*TunnelManager) Send

func (tm *TunnelManager) Send(nodeID uint32, pkt *protocol.Packet) error

Send encapsulates and sends a packet to the given node.

func (*TunnelManager) SendTo

func (tm *TunnelManager) SendTo(addr *net.UDPAddr, nodeID uint32, pkt *protocol.Packet) error

SendTo sends a packet to a specific UDP address (relay-aware).

func (*TunnelManager) SetBeaconAddr

func (tm *TunnelManager) SetBeaconAddr(addr string) error

SetBeaconAddr configures the beacon address for NAT hole-punching and relay.

func (*TunnelManager) SetIdentity

func (tm *TunnelManager) SetIdentity(id *crypto.Identity)

SetIdentity sets our Ed25519 identity for signing authenticated key exchanges.

func (*TunnelManager) SetNodeID

func (tm *TunnelManager) SetNodeID(id uint32)

SetNodeID sets our node ID (called after registration).

func (*TunnelManager) SetPeerPubKey

func (tm *TunnelManager) SetPeerPubKey(nodeID uint32, pubKey ed25519.PublicKey)

SetPeerPubKey caches a peer's Ed25519 public key for authentication.

func (*TunnelManager) SetPeerVerifyFunc

func (tm *TunnelManager) SetPeerVerifyFunc(fn func(uint32) (ed25519.PublicKey, error))

SetPeerVerifyFunc sets a callback to fetch a peer's Ed25519 public key from the registry.

func (*TunnelManager) SetRelayPeer

func (tm *TunnelManager) SetRelayPeer(nodeID uint32, relay bool)

SetRelayPeer marks a peer as needing relay through the beacon (symmetric NAT).

func (*TunnelManager) SetWebhook

func (tm *TunnelManager) SetWebhook(wc *WebhookClient)

SetWebhook configures the webhook client for event notifications.

type WebhookClient

type WebhookClient struct {
	// contains filtered or unexported fields
}

WebhookClient dispatches events asynchronously to an HTTP(S) endpoint. If URL is empty, all methods are no-ops (zero overhead when disabled).

func NewWebhookClient

func NewWebhookClient(url string, nodeIDFunc func() uint32) *WebhookClient

NewWebhookClient creates a webhook dispatcher. If url is empty, returns nil.

func (*WebhookClient) Close

func (wc *WebhookClient) Close()

Close drains the queue and stops the background goroutine. Idempotent.

func (*WebhookClient) Emit

func (wc *WebhookClient) Emit(event string, data interface{})

Emit queues an event for async delivery. Non-blocking; drops if buffer full. Safe to call after Close (becomes a no-op).

type WebhookEvent

type WebhookEvent struct {
	Event     string      `json:"event"`
	NodeID    uint32      `json:"node_id"`
	Timestamp time.Time   `json:"timestamp"`
	Data      interface{} `json:"data,omitempty"`
}

WebhookEvent is the JSON payload POSTed to the webhook endpoint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL