config

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MPL-2.0 Imports: 32 Imported by: 1

Documentation

Index

Constants

View Source
const (
	AppConfigFilename         = "config_awl.json"
	AppDataDirectory          = "anywherelan"
	DhtPeerstoreDataDirectory = "peerstore"
	AppDataDirEnvKey          = "AWL_DATA_DIR"

	// TODO 8989 maybe?
	DefaultHTTPPort              = 8639
	AdminHttpServerDomainName    = "admin"
	AdminHttpServerIP            = "127.0.0.66"
	AdminHttpServerListenAddress = "127.0.0.66:80"

	DefaultPeerAlias = "peer"
)
View Source
const (
	DefaultVPNInterfaceName = "awl0"
	// TODO: generate subnets if this has already taken
	DefaultVPNNetworkSubnet  = "10.66.0.1/16"
	DefaultVPNNetworkSubnet6 = "fd00:66:0::/48"
)
View Source
const DevVersion = "dev"

Variables

View Source
var (
	ErrInviteNotFound = errors.New("invite not found")
	ErrInviteRevoked  = errors.New("invite is revoked")
	ErrInviteExpired  = errors.New("invite has expired")
	ErrInviteUsedUp   = errors.New("invite has no uses left")
)

Reasons an invite cannot be redeemed. They double as the metric label in service.AuthStatus, so they are distinguished rather than folded into one.

View Source
var (
	// set via ldflags
	Version         = DevVersion
	UserAgent       = UserAgentPrefix + SystemInfo + "/" + Version
	UserAgentPrefix = "awl/"
	SystemInfo      = runtime.GOOS + "-" + runtime.GOARCH
	// set via ldflags
	IsWindows7 = ""
)
View Source
var DefaultBootstrapPeers []multiaddr.Multiaddr
View Source
var ErrIPv6Disabled = errors.New("IPv6 overlay is disabled")

ErrIPv6Disabled is returned by AllocPeerIPv6Unlocked when the IPv6 overlay is off on our side.

View Source
var LinuxFilesOwnerUID = os.Geteuid()

LinuxFilesOwnerUID is used to set correct files owner uid. This is needed because by default all files belong to root when we run as root, but they are stored in user's directory.

Functions

func CalcAppDataDir

func CalcAppDataDir() string

func ChownFileIfNeeded added in v0.9.0

func ChownFileIfNeeded(path string)

func ImportConfig

func ImportConfig(data []byte, directory string) error

func IsDevVersion added in v0.5.1

func IsDevVersion() bool

IsDevVersion Possible duplicate of *Config.DevMode() Based on build version (unchangeable after build, could be used only by developers)

func SystemInfoFromUserAgent added in v0.7.0

func SystemInfoFromUserAgent(userAgent string) (goos string, goarch string)

func VersionFromUserAgent

func VersionFromUserAgent(userAgent string) string

Types

type AppType added in v0.18.0

type AppType int
const (
	AppTypeAwl AppType = iota
	AppTypeAwlTray
	AppTypeAwlAndroid
)

type BlockedPeer

type BlockedPeer struct {
	// Hex-encoded multihash representing a peer ID
	PeerID      string `json:"peerId"`
	DisplayName string `json:"displayName"`
	// Time of adding to config (decline invitation/remove from KnownPeers)
	CreatedAt time.Time `json:"createdAt"`
}

type Config

type Config struct {
	sync.RWMutex `swaggerignore:"true"`

	Version               string                 `json:"version"`
	LoggerLevel           string                 `json:"loggerLevel"`
	HttpListenAddress     string                 `json:"httpListenAddress"`
	HttpListenOnAdminHost bool                   `json:"httpListenOnAdminHost"`
	HttpBasicAuth         HttpBasicAuthConfig    `json:"httpBasicAuth"`
	P2pNode               P2pNodeConfig          `json:"p2pNode"`
	VPNConfig             VPNConfig              `json:"vpn"`
	VPNGateway            VPNGatewayConfig       `json:"vpnGateway"`
	SOCKS5                SOCKS5Config           `json:"socks5"`
	DNS                   DNSConfig              `json:"dns"`
	KnownPeers            map[string]KnownPeer   `json:"knownPeers"`
	BlockedPeers          map[string]BlockedPeer `json:"blockedPeers"`
	Invites               map[string]Invite      `json:"invites"`
	Update                UpdateConfig           `json:"update"`
	// contains filtered or unexported fields
}

func LoadConfig

func LoadConfig(appType AppType, bus awlevent.Bus) (*Config, error)

LoadConfig reads the config from disk. The caller must call Close. Use LoadConfigReadOnly when the config is only going to be read. A missing file is reported as fs.ErrNotExist, which callers use to tell an ordinary first run apart from a real failure.

func LoadConfigReadOnly added in v0.20.0

func LoadConfigReadOnly(appType AppType) (*Config, error)

LoadConfigReadOnly reads the config from disk for inspection. Save on it is a no-op that DPanics in dev mode.

func NewConfig

func NewConfig(appType AppType, bus awlevent.Bus) *Config

NewConfig returns a config with defaults applied. The caller must call Close. Use NewConfigReadOnly when the config is only going to be read.

func NewConfigReadOnly added in v0.20.0

func NewConfigReadOnly(appType AppType) *Config

NewConfigReadOnly returns a defaults-only config for inspection. Save on it is a no-op that DPanics in dev mode.

func (*Config) AllocPeerIPv6Unlocked added in v0.20.0

func (c *Config) AllocPeerIPv6Unlocked(peerID, announced string) (addr string, rejectErr, err error)

AllocPeerIPv6Unlocked picks our view of the IPv6 address of peerID, which announced the address announced: see pickPeerAddr. rejectErr says why the announced address was not taken. Caller must hold the config write lock and store the result in the same critical section, so that two peers cannot be given the same address.

func (*Config) CheckIPUnique added in v0.15.0

func (c *Config) CheckIPUnique(checkIP string, exceptPeerID string) error

CheckIPUnique is not thread safe. Checks IP for: valid ip, unique across peers, in vpn net mask

func (*Config) CheckInvite added in v0.20.0

func (c *Config) CheckInvite(token string) (Invite, error)

CheckInvite reports whether token matches an invite that can be redeemed right now, consuming nothing. It is a peek, used to decide what to do with an auth request (and to label the rejection metric); the authoritative check is ReserveInviteUnlocked.

func (*Config) Close added in v0.20.0

func (c *Config) Close()

Close stops the writer goroutine after a final flush and releases the event emitter. It is idempotent and safe on a read-only config, which has neither.

Callers of NewConfig and LoadConfig must call it, otherwise the writer goroutine and the emitter's slot on the event bus outlive the config.

func (*Config) CreateInvite added in v0.20.0

func (c *Config) CreateInvite(params CreateInviteParams) (Invite, error)

func (*Config) DNSNamesMapping

func (c *Config) DNSNamesMapping() map[string]netip.Addr

DNSNamesMapping returns the IPv4 addresses of known peers by peer ID and by domain name, and the address of the admin server. Peers with an invalid IP are left out.

func (*Config) DNSNamesMappingV6 added in v0.20.0

func (c *Config) DNSNamesMappingV6() map[string]netip.Addr

DNSNamesMappingV6 is DNSNamesMapping for IPv6, see PeerIPv6Unlocked.

func (*Config) DataDir

func (c *Config) DataDir() string

func (*Config) DevMode

func (c *Config) DevMode() bool

DevMode Possible duplicate of IsDevVersion() Based on Config.LoggerLevel (could be used by any user)

func (*Config) Export

func (c *Config) Export() []byte

func (*Config) GenUniqDomainNameUnlocked added in v0.20.0

func (c *Config) GenUniqDomainNameUnlocked(peerID, name string) string

GenUniqDomainNameUnlocked makes a domain name for peerID out of name, with a suffix if it is taken, see IsUniqDomainNameUnlocked.

func (*Config) GenUniqPeerAlias added in v0.5.1

func (c *Config) GenUniqPeerAlias(name, alias string) string

func (*Config) GenUniqPeerAliasUnlocked added in v0.18.0

func (c *Config) GenUniqPeerAliasUnlocked(name, alias string) string

GenUniqPeerAliasUnlocked is GenUniqPeerAlias without locking; the caller must hold the lock.

func (*Config) GenerateNextIpAddr

func (c *Config) GenerateNextIpAddr() string

GenerateNextIpAddr is not thread safe.

func (*Config) GenerateNextIpAddrExcept added in v0.15.0

func (c *Config) GenerateNextIpAddrExcept(except []string) string

GenerateNextIpAddrExcept is not thread safe.

func (*Config) GetBlockedPeer

func (c *Config) GetBlockedPeer(peerID string) (BlockedPeer, bool)

func (*Config) GetBootstrapPeers

func (c *Config) GetBootstrapPeers() []peer.AddrInfo

func (*Config) GetInvite added in v0.20.0

func (c *Config) GetInvite(id string) (Invite, bool)

func (*Config) GetListenAddresses

func (c *Config) GetListenAddresses() []multiaddr.Multiaddr

func (*Config) GetPeer

func (c *Config) GetPeer(peerID string) (KnownPeer, bool)

func (*Config) GetPeerUnlocked added in v0.18.0

func (c *Config) GetPeerUnlocked(peerID string) (KnownPeer, bool)

GetPeerUnlocked is GetPeer without locking; the caller must hold the lock.

func (*Config) IsUniqDomainNameUnlocked added in v0.20.0

func (c *Config) IsUniqDomainNameUnlocked(peerID, domain string) bool

IsUniqDomainNameUnlocked reports whether domain is free for peerID: it is not the domain name or the peer ID of another peer, both of which awl DNS serves, and it is not reserved. domain must be normalized, see awldns.IsValidDomainName.

func (*Config) IsUniqPeerAlias added in v0.5.1

func (c *Config) IsUniqPeerAlias(excludePeerID, alias string) bool

func (*Config) IsUniqPeerAliasUnlocked added in v0.18.0

func (c *Config) IsUniqPeerAliasUnlocked(excludePeerID, alias string) bool

IsUniqPeerAliasUnlocked is IsUniqPeerAlias without locking; the caller must hold the lock.

func (*Config) ListInvites added in v0.20.0

func (c *Config) ListInvites() []Invite

ListInvites returns a copy of all invites, spent ones included.

func (*Config) LogLevel

func (c *Config) LogLevel() zapcore.Level

func (*Config) NetstackDNSIP added in v0.20.0

func (c *Config) NetstackDNSIP() net.IP

NetstackDNSIP returns the in-subnet IP reserved for the awl DNS server, computed once in setDefaults and fixed for the session (see the netstackDNSIP field). nil when the subnet has no free address, in which case DNS is disabled. Used on Android, where DNS queries to it are intercepted inside the tunnel.

func (*Config) NodeName added in v0.18.0

func (c *Config) NodeName() string

NodeName returns this node's name under the read lock. P2pNode.Name is mutated at runtime (UpdateMySettings), so it must not be read directly without the lock.

func (*Config) PeerIPv6Unlocked added in v0.20.0

func (c *Config) PeerIPv6Unlocked(kp KnownPeer) (netip.Addr, bool)

PeerIPv6Unlocked returns the IPv6 address of kp for routing and DNS. ok is false while either side has IPv6 off. The stored address is not re-validated: it was checked when assigned (AllocPeerIPv6Unlocked), and editing it by hand is on whoever does it.

func (*Config) PeerstoreDir

func (c *Config) PeerstoreDir() string

func (*Config) PrivKey

func (c *Config) PrivKey() []byte

func (*Config) RemoveBlockedPeer

func (c *Config) RemoveBlockedPeer(peerID string) bool

func (*Config) RemovePeer

func (c *Config) RemovePeer(peerID string) (KnownPeer, bool)

func (*Config) ReserveInviteUnlocked added in v0.20.0

func (c *Config) ReserveInviteUnlocked(token string) (Invite, error)

ReserveInviteUnlocked consumes one use of the invite matching token. The caller must hold the write lock, and must perform the write that redeems the invite — inserting the peer, confirming it — inside the same critical section.

func (*Config) RevokeInvite added in v0.20.0

func (c *Config) RevokeInvite(id string) bool

RevokeInvite closes an invite to new connections. Peers already added through it keep working; revoking is not kicking anyone out.

func (*Config) Save

func (c *Config) Save()

Save schedules a write of the config and returns immediately; the writer goroutine performs it. It is safe to call with or without the config lock held, because it touches no config state — only saveTrigger.

func (*Config) SetIdentity

func (c *Config) SetIdentity(key crypto.PrivKey, id peer.ID)

func (*Config) SetListenAddresses

func (c *Config) SetListenAddresses(multiaddrs []multiaddr.Multiaddr)

func (*Config) UpdatePeerFields added in v0.18.0

func (c *Config) UpdatePeerFields(peerID string, mutate func(*KnownPeer)) bool

UpdatePeerFields atomically applies mutate to the stored KnownPeer under the write lock. It returns false if the peer is unknown.

mutate must only change the fields it owns and must NOT replace the struct wholesale, so that fields updated concurrently by other callers are not clobbered. mutate runs while the lock is held, so it must not call other Config methods that take the lock (use the *Unlocked variants instead).

func (*Config) UpdatePeerLastSeen

func (c *Config) UpdatePeerLastSeen(peerID string)

func (*Config) UpsertBlockedPeer

func (c *Config) UpsertBlockedPeer(peerID, displayName string)

func (*Config) UpsertPeer

func (c *Config) UpsertPeer(peer KnownPeer)

func (*Config) UpsertPeerUnlocked added in v0.15.0

func (c *Config) UpsertPeerUnlocked(peer KnownPeer)

func (*Config) VPNLocalIPMaskUnlocked added in v0.15.0

func (c *Config) VPNLocalIPMaskUnlocked() (net.IP, net.IPMask)

TODO: remove after unification with ipv6

func (*Config) VPNPrefix added in v0.20.0

func (c *Config) VPNPrefix() netip.Prefix

VPNPrefix returns our IPv4 address with the prefix length of the awl subnet. setDefaults replaces an invalid vpn.ipNet with the default, so the result is valid for any config built by NewConfig or LoadConfig.

func (*Config) VPNPrefixV6 added in v0.20.0

func (c *Config) VPNPrefixV6() (prefix netip.Prefix, ok bool)

VPNPrefixV6 returns our IPv6 address with the prefix length of the awl IPv6 subnet. When IPv6 is off, ok is false and the prefix is invalid.

func (*Config) ValidateForStartup added in v0.20.0

func (c *Config) ValidateForStartup() error

ValidateForStartup returns config errors that must abort startup; recoverable problems are fixed up in setDefaults.

type CreateInviteParams added in v0.20.0

type CreateInviteParams struct {
	Label string
	// Alias for the peer that redeems the invite. Only meaningful for
	// single-use invites — aliases must be unique.
	Alias                string
	AllowUsingAsExitNode bool
	// MaxUses below 1 is clamped to 1; the API layer bounds the upper end.
	MaxUses int
	// ExpiresAt zero means the invite never expires.
	ExpiresAt time.Time
}

CreateInviteParams are the caller-chosen fields of a new invite; ID, Token and CreatedAt are generated.

type DNSConfig added in v0.16.0

type DNSConfig struct {
	DisableDNS    bool   `json:"disableDNS"`
	ListenAddress string `json:"listenAddress"`
	// UpstreamDNSAddress is the public resolver (host:port) that the awl
	// DNS resolver forwards non-.awl queries to. Used as a fallback when
	// the OS exposes no base nameserver, and forced as the sole upstream in
	// VPN gateway client mode so DNS traverses the tunnel and does not leak.
	// On Android the host reads this value to configure VpnService DNS.
	UpstreamDNSAddress string `json:"upstreamDNSAddress"`
}

type HttpBasicAuthConfig added in v0.17.0

type HttpBasicAuthConfig struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type Invite added in v0.20.0

type Invite struct {
	// ID is a short non-secret identifier, the key in Config.Invites. UI, CLI
	// and logs refer to an invite by it so the token stays out of sight.
	ID string `json:"id"`
	// Token is the bearer secret embedded in the link. Stored in the clear
	// because the link has to be displayable again.
	Token string `json:"token"`
	// Label is an optional human-readable note.
	Label string `json:"label,omitempty"`
	// Alias to give the new peer; single-use invites only, aliases are unique.
	Alias string `json:"alias,omitempty"`
	// WeAllowUsingAsExitNode is applied to the new peer's KnownPeer.
	WeAllowUsingAsExitNode bool `json:"weAllowUsingAsExitNode"`
	MaxUses                int  `json:"maxUses"`
	UsedCount              int  `json:"usedCount"`
	// ExpiresAt is checked against our own clock at redemption time; zero
	// means the invite never expires.
	ExpiresAt time.Time `json:"expiresAt"`
	CreatedAt time.Time `json:"createdAt"`
	Revoked   bool      `json:"revoked"`
}

Invite is a link we handed out: whoever presents Token is added automatically, with the settings stored here, until the invite is used up, expires or is revoked. Invites are kept forever, including spent ones, as history and as the target of KnownPeer.InviteID.

func (Invite) IsExpired added in v0.20.0

func (i Invite) IsExpired(now time.Time) bool

IsExpired reports whether the invite is past its expiry by our own clock. Clock skew between nodes plays no part: only the creator checks this.

func (Invite) IsUsedUp added in v0.20.0

func (i Invite) IsUsedUp() bool

type KnownPeer

type KnownPeer struct {
	// Hex-encoded multihash representing a peer ID
	PeerID string `json:"peerId"`
	// Peer provided name
	Name string `json:"name"`
	// User provided name
	Alias string `json:"alias"`
	// IPAddr used for forwarding
	IPAddr string `json:"ipAddr"`
	// IPAddrV6 is our view of the peer's IPv6 overlay address: the address the
	// peer announced if it is valid in our subnet, otherwise one derived from
	// its peer ID. Assigned once and not changed by later announcements, see
	// Config.AllocPeerIPv6Unlocked. Used only while RemoteIPv6Enabled.
	IPAddrV6 string `json:"ipAddrV6"`
	// DomainName without zone suffix (.awl)
	DomainName string `json:"domainName"`
	// Time of adding to config (accept/invite)
	CreatedAt time.Time `json:"createdAt"`
	// Time of last connection
	LastSeen time.Time `json:"lastSeen"`
	// Confirmed means the remote peer keeps us in its KnownPeers: it accepted
	// our invitation or added us itself. Learned from the auth and status
	// exchanges, cleared when the peer declines us. Grants nothing by itself.
	Confirmed bool `json:"confirmed"`
	// Declined means the remote peer has blocked us: it declined our
	// invitation or removed us from its peers.
	Declined               bool `json:"declined"`
	WeAllowUsingAsExitNode bool `json:"weAllowUsingAsExitNode"`
	AllowedUsingAsExitNode bool `json:"allowedUsingAsExitNode"`
	// RemoteVPNGatewayServerEnabled is the remote peer's VPNGatewayConfig.ServerEnabled
	// as advertised via the status protocol. Combined with AllowedUsingAsExitNode
	// (also from status) it determines whether this peer is currently a valid
	// VPN gateway target for us — see KnownPeer.CanUseAsVPNGateway.
	RemoteVPNGatewayServerEnabled bool `json:"remoteVPNGatewayServerEnabled"`
	// RemoteIPv6Enabled is whether the remote peer announces an IPv6 overlay
	// address via the status protocol. IPAddrV6 is kept while it is false, so
	// the peer gets the same address back when it enables IPv6 again.
	RemoteIPv6Enabled bool `json:"remoteIPv6Enabled"`
	// InviteID marks a peer we let in through one of our invite links
	// (Config.Invites). Non-secret, kept forever: it is what lets the UI say
	// "added via invite X".
	InviteID string `json:"inviteID,omitempty"`
	// PendingInviteToken is the secret from an invite link we are redeeming:
	// we present it in every auth request until the peer confirms us, then it
	// is dropped. Set only on the side that used the link.
	PendingInviteToken string `json:"pendingInviteToken,omitempty"`
}

func (KnownPeer) CanUseAsVPNGateway added in v0.18.0

func (kp KnownPeer) CanUseAsVPNGateway() bool

CanUseAsVPNGateway reports whether this peer can currently be used as a VPN gateway. It requires both that the peer permits being used as an exit node (shared with SOCKS5 via AllowedUsingAsExitNode) and that the peer has VPN gateway server enabled on its side (RemoteVPNGatewayServerEnabled). Both flags are populated from the status protocol exchange in service/auth_status.go.

func (KnownPeer) DisplayName

func (kp KnownPeer) DisplayName() string

func (KnownPeer) PeerId

func (kp KnownPeer) PeerId() peer.ID

func (KnownPeer) ReconnectEagerly added in v0.20.0

func (kp KnownPeer) ReconnectEagerly(now time.Time) bool

ReconnectEagerly reports whether the peer is to be retried at full pace, with no backoff. A peer that has not confirmed us yet does not know about us and will not connect on its own, so we are the only side that can make the connection happen. The window is there for the peer that never shows up: it is not looked up at full pace forever.

type P2pNodeConfig

type P2pNodeConfig struct {
	// Hex-encoded multihash representing a peer ID, calculated from Identity
	PeerID         string   `json:"peerId"`
	Name           string   `json:"name"`
	Identity       string   `json:"identity"`
	BootstrapPeers []string `json:"bootstrapPeers"`
	// With this option only BootstrapPeers from config will be used
	IgnoreDefaultBootstrapPeers *bool    `json:"ignoreDefaultBootstrapPeers,omitempty"`
	ListenAddresses             []string `json:"listenAddresses"`
	// Pace of the reconnection rounds, and the first pause before a peer that
	// could not be reached is tried again. Each next pause is twice as long,
	// up to 10 minutes
	ReconnectionIntervalSec time.Duration `json:"reconnectionIntervalSec" swaggertype:"primitive,integer"` //nolint:staticcheck
	AutoAcceptAuthRequests  bool          `json:"autoAcceptAuthRequests"`

	UseDedicatedConnForEachStream bool `json:"useDedicatedConnForEachStream"`
	ParallelSendingStreamsCount   int  `json:"parallelSendingStreamsCount"`
}

type SOCKS5Config added in v0.12.0

type SOCKS5Config struct {
	ListenerEnabled bool `json:"listenerEnabled"`
	// allow using my host as proxy
	ProxyingEnabled bool   `json:"proxyingEnabled"`
	ListenAddress   string `json:"listenAddress"`
	// peer that is set as proxy
	UsingPeerID string `json:"usingPeerID"`
	// Optional local auth credentials. If both are set, SOCKS5 clients must authenticate.
	Username string `json:"username"`
	Password string `json:"password"`
}

type UpdateConfig

type UpdateConfig struct {
	LowestPriorityChan    string `json:"lowestPriorityChan"`
	UpdateServerURL       string `json:"updateServerURL"`
	TrayAutoCheckEnabled  bool   `json:"trayAutoCheckEnabled"`
	TrayAutoCheckInterval string `json:"trayAutoCheckInterval"`
}

type VPNConfig

type VPNConfig struct {
	DisableVPNInterface bool   `json:"disableVPNInterface"`
	InterfaceName       string `json:"interfaceName"`
	IPNet               string `json:"ipNet"`
	IPNetV6             string `json:"ipNetV6"`
}

type VPNGatewayConfig added in v0.18.0

type VPNGatewayConfig struct {
	// ClientEnabled — route all traffic through GatewayPeerID (client side).
	ClientEnabled bool `json:"clientEnabled"`
	// GatewayPeerID — selected gateway peer ID.
	GatewayPeerID string `json:"gatewayPeerID"`
	// ServerEnabled — this node serves as a VPN gateway for others.
	// Propagated via the status protocol so peers know whether to offer
	// this node as an option in their UI.
	ServerEnabled bool `json:"serverEnabled"`
}

VPNGatewayConfig configures full-tunnel VPN gateway mode.

VPN gateway is a separate feature from SOCKS5 exit-node: a peer can allow being used as a SOCKS5 exit (KnownPeer.AllowedUsingAsExitNode, propagated via the status protocol) without serving as a VPN gateway, and vice versa. KnownPeer.CanUseAsVPNGateway() combines both.

Jump to

Keyboard shortcuts

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