functions

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 68 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	TestIPv4 = "1.1.1.1"
	TestIPv6 = "2606:4700:4700::1111"
)
View Source
const (
	// ACK - acknowledgement signal for MQ
	ACK = 1
	// DONE - done signal for MQ
	DONE = 2
	// CheckInInterval - interval in minutes for mq checkins
	CheckInInterval = 1
)
View Source
const (
	// BuildProfile is the compile-time product flavor.
	BuildProfile = "headless"
)
View Source
const (

	// ExitOverlayProbeGrace is how long after a network connects before overlay
	// latency probes run. Right after connect the mesh is still settling and
	// probes time out or report inflated RTT.
	ExitOverlayProbeGrace = 4 * time.Second
)
View Source
const MDMDeniedMessage = "Access blocked: this device is not enrolled or compliant in your organization MDM."

MDMDeniedMessage is the exact string netclient prints when the server refuses access because the host is not enrolled or compliant in the organization MDM. Wording is part of the user-facing contract.

View Source
const MQTimeout = 30

MQTimeout - time out for mqtt connections

View Source
const (

	// MQ_TIMEOUT - timeout for MQ
	MQ_TIMEOUT = 30
)
View Source
const MinVersion = "v0.18.0"

Variables

View Source
var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	slog.Info("default message handler -- received message but not handling", "topic", msg.Topic())
}

All -- mqtt message hander for all ('#') topics

View Source
var GUI struct {
	PrepareConnect        func(network string) string
	RememberConnection    func(network string)
	ForgetConnection      func(network string)
	FinishConnect         func(network, token string)
	FilterPreserved       func(keep map[string]struct{}) map[string]struct{}
	ReassertDesired       func()
	WantsIGW              func() bool
	WantsUnadvertisedExit func(pull models.HostPull, pullErr error) bool
	// HoldIGWTeardown skips ChangeDefaultGw=false RestoreInternetGw while a
	// desktop exit select or session restore still wants an exit. Nil on headless.
	HoldIGWTeardown func() bool
	// NotePendingExitReconcile marks that teardown was deferred so release
	// callbacks can re-drive selection or finish LAN restore. Nil on headless.
	NotePendingExitReconcile func()
	RememberWantIGW          func()
	ReconcileExit            func()
	ExitDecision             func() string
	ApplyStartup             func()
	RefreshHostPull          func(prev models.HostPull, prevErr error) (models.HostPull, error)
	ForgetNetwork            func(network string)

	// Desktop-only control plane. Nil on headless builds.
	StartUIAPI                 func(ctx context.Context)
	StopUIAPI                  func() error
	RefreshUIAPI               func()
	ForceLogout                func()
	IsSessionActive            func() bool
	EnsureSessionLoaded        func()
	KeepServerDomainForRelogin func() bool
}

GUI is filled by the desktop package at init when built with -tags desktop. A nil field is the default headless path: no session, no uiapi listener, no demote for re-login, no desired-state filter, no exit re-select.

View Source
var (
	Mqclient mqtt.Client
)

Functions

func ApplyConnectionChange added in v1.8.0

func ApplyConnectionChange(op string) error

ApplyConnectionChange brings the live interface in line with the new node set without bouncing the daemon, falling back to a restart only if that fails.

func ApplyPendingRegistrationReset added in v1.8.0

func ApplyPendingRegistrationReset() <-chan struct{}

ApplyPendingRegistrationReset rebuilds the daemon in place after the login response has been written. The returned channel is closed when that rebuild finishes. Nil means nothing was pending.

func ApplyReconnectInProcess added in v1.8.0

func ApplyReconnectInProcess(pull models.HostPull, wantIGW bool) error

ApplyReconnectInProcess brings the live iface and exit routes up without a daemon restart.

func ArmIgnoreStaleDeleteHost added in v1.8.0

func ArmIgnoreStaleDeleteHost(tenantID, hostID string)

ArmIgnoreStaleDeleteHost suppresses DELETE_HOST ForceLogout / local teardown for staleDeleteHostGrace when the message matches tenantID (and hostID when non-empty). Safe to call repeatedly; extends the window and replaces identity. Must be called before leaveHostOnTenant / unregister HTTP so an immediate MQTT echo cannot race past the ignore. Pass the tenant (and host) being left, captured before clearLocalEnrollmentAfterTenantLeave.

func AttachExitNodeOverlayLatencies added in v1.8.0

func AttachExitNodeOverlayLatencies(network string, nodes []models.DeviceExitNode)

attachExitNodeOverlayLatencies probes each exit's overlay metrics port. Used after connect. A successful probe marks the exit healthy. A miss marks it unhealthy when another exit in the same check answered, or when this exit's peer has already handshaked. A miss while nothing has answered yet is the tunnel still coming up, not proof every exit is down.

func AttachExitNodePublicLatencies added in v1.8.0

func AttachExitNodePublicLatencies(network string, nodes []models.DeviceExitNode)

AttachExitNodePublicLatencies probes each exit's public AllowedEndpoints (ICMP + TCP 443/22). Desktop exit ranking no longer uses this; overlay VPN probes run only after the network is connected.

func BoxDecrypt

func BoxDecrypt(encrypted []byte, senderPublicKey *[32]byte, recipientPrivateKey *[32]byte) ([]byte, error)

BoxDecrypt - decrypts traffic box

func BoxEncrypt

func BoxEncrypt(message []byte, recipientPubKey *[32]byte, senderPrivateKey *[32]byte) ([]byte, error)

BoxEncrypt - encrypts traffic box

func CheckEgressDomainUpdates added in v1.1.0

func CheckEgressDomainUpdates()

func Checkin

func Checkin(ctx context.Context, wg *sync.WaitGroup)

Checkin -- go routine that checks for public or local ip changes, publishes changes

if there are no updates, simply "pings" the server as a checkin

func Chunk

func Chunk(message []byte, recipientPubKey *[32]byte, senderPrivateKey *[32]byte) ([]byte, error)

Chunk - chunks a message and encrypts each chunk

func ClearEnrollmentIfHostMissing added in v1.8.0

func ClearEnrollmentIfHostMissing(serverName string, err error) bool

ClearEnrollmentIfHostMissing clears local enrollment when authenticate/pull reports the host is gone on the server (400 record not found). Headless deletes the server entry; Desktop demotes it for re-login. Stops treating the host as enrolled so mqFallback stops spamming Pull.

func Connect

func Connect(network string) error

Connect will attempt to connect a node on given network

func ConnectWithoutRestart added in v1.8.0

func ConnectWithoutRestart(network string) error

ConnectWithoutRestart marks the network connected and publishes the update without rebuilding the daemon. Desktop session restore uses this.

func DNSSync added in v0.26.0

func DNSSync(client mqtt.Client, msg mqtt.Message)

DNSSync -- mqtt message handler for host/dns/sync/<network id> topic

func Daemon

func Daemon()

Daemon runs netclient daemon

func DeChunk

func DeChunk(chunkedMsg []byte, senderPublicKey *[32]byte, recipientPrivateKey *[32]byte) ([]byte, error)

DeChunk - "de" chunks and decrypts a message

func DeriveSharedKey added in v1.8.0

func DeriveSharedKey(localPrivate, remotePublic *[32]byte) ([]byte, error)

DeriveSharedKey derives a symmetric AES-256 key from the X25519 ECDH shared secret between localPrivate and remotePublic, via HKDF-SHA256.

This must be used instead of either key's raw bytes as a symmetric key: a public key is, by definition, not secret (it is readable via the API), so using it directly as an AES key provides no confidentiality. The ECDH shared secret cannot be computed by anyone who only knows the two public keys -- it also requires one of the two private keys.

func DesktopSessionActive added in v1.8.0

func DesktopSessionActive() bool

DesktopSessionActive reports whether a Desktop UI session is loaded. Headless builds (nil hooks) always return false.

func Disconnect

func Disconnect(network string) error

Disconnect disconnects a node from the given network

func DisconnectWithoutRestart added in v1.8.0

func DisconnectWithoutRestart(network string, forgetDesired bool) error

DisconnectWithoutRestart marks the network disconnected without a daemon restart. forgetDesired clears the desktop user's desired-connection record when that hook is registered.

func DisposeServerEnrollment added in v1.8.0

func DisposeServerEnrollment(serverName string)

DisposeServerEnrollment demotes or deletes a servers.json entry after the host is gone remotely (DELETE_HOST, missing-host auth, mismatched MQID).

Headless (nil KeepServerDomainForRelogin): DeleteServer — full wipe. Desktop: DemoteServerToPartial so Settings/Login keep the domain+API.

func FilterDnsNameservers added in v1.2.0

func FilterDnsNameservers(nameservers []models.Nameserver) []models.Nameserver

func GetLocalListenPort

func GetLocalListenPort(ifacename string) (int, error)

GetLocalListenPort - Gets the port running on the local interface

func GetNodePeers

func GetNodePeers(node config.Node) ([]wgtypes.PeerConfig, error)

GetNodePeers returns the peers for a given node

func GetPublicIP added in v0.24.3

func GetPublicIP(proto uint) (net.IP, error)

func HandleRegisterResponse added in v1.8.0

func HandleRegisterResponse(registerResponse *models.RegisterResponse)

HandleRegisterResponse applies a device or CLI register response to local config.

func HostPeerUpdate

func HostPeerUpdate(client mqtt.Client, msg mqtt.Message)

HostPeerUpdate - mq handler for host peer update peers/host/<HOSTID>/<SERVERNAME>

func HostPullHasConnectedNetworks added in v1.8.0

func HostPullHasConnectedNetworks(pull models.HostPull, networks []string) bool

HostPullHasConnectedNetworks reports whether the pull lists those networks as connected.

func HostPullReadyForReconnect added in v1.8.0

func HostPullReadyForReconnect(pull models.HostPull, networks []string, wantIGW bool) bool

HostPullReadyForReconnect reports whether a pull already shows the networks connected.

func HostUpdate

func HostUpdate(client mqtt.Client, msg mqtt.Message)

HostUpdate - mq handler for host update host/update/<HOSTID>/<SERVERNAME>

func Install

func Install() error

Install - installs binary/daemon

func IsContainerized added in v1.5.1

func IsContainerized() bool

IsContainerized returns true if the process appears to be running inside a Docker container, Kubernetes pod, or other containerd-based runtime.

func IsDesktopBuild added in v1.8.0

func IsDesktopBuild() bool

IsDesktopBuild reports whether this binary was built with -tags desktop.

func IsServerFullyRegistered added in v1.8.0

func IsServerFullyRegistered(name string) bool

IsServerFullyRegistered reports whether CurrServer (or name) still has a full enrollment (Server and/or TenantID present). Partial Settings entries do not count.

func IsVersionComptatible

func IsVersionComptatible(ver string) bool

IsVersionCompatible checks that the version passed is compabtible (>=) with MinVersion

func KeepLocallyConnected added in v1.8.0

func KeepLocallyConnected(networks map[string]struct{})

KeepLocallyConnected is the desktop package's entry to the unfiltered restore.

func LeaveNetwork

func LeaveNetwork(network string, isDaemon bool) ([]error, error)

LeaveNetwork - client exits a network

func LeaveServer added in v0.21.0

func LeaveServer(s string) error

LeaveServer - leave the named server

func List

func List(net string, long bool)

List displays this host's networks from the server (GET /api/v1/host). Unlike the old local-only path, disconnected nodes still appear so connect can target them. A successful list also refreshes nodes.json (without reasserting desktop desired connections).

long fetches per-network peers via GET /api/nodes/{network}/{nodeID}.

func ListServers added in v0.21.0

func ListServers() error

ListServers - lists all registered servers

func LogElapsed added in v1.8.0

func LogElapsed(label string) func()

LogElapsed logs how long the labelled phase took. Desktop logout uses it.

func MQFallbackPull added in v1.8.0

func MQFallbackPull(pullResponse models.HostPull, resetInterface, replacePeers bool)

MQFallbackPull applies a host pull when MQTT is down. Desktop sync uses this.

func MarkRegistrationResetPending added in v1.8.0

func MarkRegistrationResetPending()

MarkRegistrationResetPending asks the daemon to rebuild against the server context written by a desktop login (e.g. CurrServer change). This is not a new device enroll — do not set registrationEnrollmentPending.

func NodeUpdate

func NodeUpdate(client mqtt.Client, msg mqtt.Message)

NodeUpdate -- mqtt message handler for /update/<NodeID> topic

func NoteExitOverlayConnected added in v1.8.0

func NoteExitOverlayConnected(network string)

NoteExitOverlayConnected starts the post-connect grace clock for overlay latency probes on this network.

func PickNearestAvailableExitNode added in v1.8.0

func PickNearestAvailableExitNode(nodes []models.DeviceExitNode, exclude map[string]struct{}) (models.DeviceExitNode, bool)

pickNearestAvailableExitNode returns the best exit to auto-connect. Always prefers the lowest measured LatencyMs among Status=true nodes. Nearest is only a tie-breaker. Never selects Status=false exits. Egress IDs in exclude are skipped.

func PingPeers added in v1.4.0

func PingPeers(networkFilter, peerFilter string, jsonOutput bool, packetCount int, ipVersion string) error

PingPeers checks connectivity to peers and displays status and latency. If networkFilter is non-empty, only peers in that network are considered. If peerFilter is non-empty, only peers whose name, address, or ID match (case-insensitive) are considered. packetCount controls how many packets/probes are sent per peer (<=0 uses a sensible default). ipVersion can be "4" for IPv4, "6" for IPv6, or "" for default address.

func PostureStatus added in v1.7.0

func PostureStatus(jsonOutput bool) (int, error)

PostureStatus calls GET /api/v1/host/{hostid}/posture_status on the current server, renders the result, and returns a suggested process exit code.

Exit codes:

0 - all networks pass
1 - one or more networks have status=fail
2 - transport/auth error or MDM denial

On MDM denial (server returns the well-known sentinel error) the standard user-facing message is printed to stderr.

func PrepareRegistrationHost added in v1.8.0

func PrepareRegistrationHost() (schema.Host, error)

func PreserveConnectionsAfterSync added in v1.8.0

func PreserveConnectionsAfterSync(nodes []models.Node)

PreserveConnectionsAfterSync replaces the local node map with the server's list, then puts back Connected flags that were already true locally.

That unfiltered restore is the reconnect race: the server often still reports Connected=false until it processes PublishNodeUpdate. When the desktop package is linked, FilterPreserved applies the logout latch and desired-network filter before the restore. Headless leaves the snapshot unchanged.

func PublicProbeHost added in v1.8.0

func PublicProbeHost(raw string) string

func PublishHostUpdate

func PublishHostUpdate(server string, hostAction models.HostMqAction) error

PublishHostUpdate - publishes host updates to server

func PublishNodeUpdate

func PublishNodeUpdate(node *config.Node) error

PublishNodeUpdate -- pushes node to broker

func PublishNodeUpdateOnce added in v1.8.0

func PublishNodeUpdateOnce(node *config.Node, timeout time.Duration) error

PublishNodeUpdateOnce pushes a node update with one short attempt. Interactive disconnect uses this; a failure is logged and ignored by the caller so local teardown still finishes.

func Pull

func Pull(restart bool, resetIfFailedOvered bool, refresh bool) (models.HostPull, bool, bool, error)

Pull pulls the latest config from the server. refresh asks the server to recompute host peer cache on demand (startup only). A 401 does not delete local server registration (servers.json).

func Push added in v0.21.1

func Push(restart bool) error

Push - updates server with new host config

func Register added in v0.18.2

func Register(token string) error

Register - should be simple to register with a token

func RegistrationEnrollmentPending added in v1.8.0

func RegistrationEnrollmentPending() bool

RegistrationEnrollmentPending reports a real RegisterDevice enroll in this login (not merely a server-context rebuild). GUI "Setting up…" uses this.

func RegistrationResetPending added in v1.8.0

func RegistrationResetPending() bool

RegistrationResetPending reports that a desktop registration finished and the daemon still needs to pick up the new server. The GUI uses this window to show a registration transition instead of treating login as failed.

func ResetInterface added in v1.8.0

func ResetInterface()

func RestoreInternetGwAndDNS added in v1.8.0

func RestoreInternetGwAndDNS()

RestoreInternetGwAndDNS restores LAN default routes and reapplies OS DNS.

func ShouldIgnoreStaleDeleteHost added in v1.8.0

func ShouldIgnoreStaleDeleteHost(host schema.Host) bool

ShouldIgnoreStaleDeleteHost reports whether a DELETE_HOST should be treated as the echo of an intentional leave rather than an admin/server eviction. Only messages whose host matches the armed left-tenant (and host ID when set) are suppressed; genuine same-tenant evictions proceed.

func ShowPeers added in v1.4.0

func ShowPeers(jsonOutput bool, networkFilter string) error

ShowPeers displays peer information from the WireGuard interface, grouped per network. If networkFilter is non-empty, only that network's peers are displayed.

func ShowStatus added in v1.8.0

func ShowStatus(wgShow bool) error

ShowStatus prints the current host and network state. When wgShow is set, it prints the live WireGuard device in the same form as `wg show`.

func SignalPeer added in v0.22.0

func SignalPeer(signal models.Signal) error

SignalPeer - signals the peer with host's turn relay endpoint

func StartEgressDomainMonitor added in v1.6.0

func StartEgressDomainMonitor(ctx context.Context, wg *sync.WaitGroup)

StartEgressDomainMonitor periodically re-resolves egress domains on the egress gateway node.

func StopAllTCPUplink()

StopAllTCPUplink tears down client/server sessions and drains async Bind sends. Must run before userspace Device.Close / iface recreate (disable, SIGHUP, shutdown).

func SwitchServer added in v0.20.2

func SwitchServer(server string) error

SwitchServer - switches netclient server context

func Uninstall

func Uninstall() ([]error, error)

Uninstall - uninstalls networks from client

func UpdateHostFromServer added in v1.7.0

func UpdateHostFromServer(host *schema.Host) (resetInterface, restart, sendHostUpdate bool)

UpdateHostFromServer merges a server host payload into local config. Posture identity fields are never taken from the server; they are restored from local config and then refreshed from the machine.

func UpdateHostSettings

func UpdateHostSettings(fallback bool) error

UpdateHostSettings - checks local host settings, if different, mod config and publish

func UpdateKeys

func UpdateKeys() error

UpdateKeys -- updates private key and returns new publickey

func UseVersion

func UseVersion(version string, rebootDaemon bool) (skip bool, err error)

UseVersion switches the current netclient version to the one specified if available in the github releases page

func WaitExitOverlayProbeGrace added in v1.8.0

func WaitExitOverlayProbeGrace(network string)

WaitExitOverlayProbeGrace blocks until ExitOverlayProbeGrace has elapsed since the network connected. Used by async post-connect auto-exit ranking.

func WaitForReconnectHostPull added in v1.8.0

func WaitForReconnectHostPull(networks []string, wantIGW bool) (models.HostPull, error)

WaitForReconnectHostPull polls until the host pull reflects the reconnect.

func WaitForReconnectHostPullTimeout added in v1.8.0

func WaitForReconnectHostPullTimeout(networks []string, wantIGW bool, timeout time.Duration) (models.HostPull, error)

WaitForReconnectHostPullTimeout is WaitForReconnectHostPull with an explicit deadline.

Types

type PingResult added in v1.4.0

type PingResult struct {
	Network   string `json:"network"`
	Name      string `json:"name"`
	Address   string `json:"address"`
	IsExt     bool   `json:"is_extclient"`
	Connected bool   `json:"connected"`
	LatencyMs int64  `json:"latency_ms"`
	UserName  string `json:"username,omitempty"`
}

PingResult holds the result of a single peer connectivity check

Jump to

Keyboard shortcuts

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