model

package
v0.35.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 24 Imported by: 1 module, 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 (
	AclOff       = 0
	AclWhitelist = 1
	AclBlacklist = 2
)

ACLMode: 0=off, 1=whitelist(deny-by-default), 2=blacklist(allow-by-default)

View Source
const (
	CompressDefault = ""
	CompressOff     = "off"
	CompressFlate   = "flate"
	CompressZstd    = "zstd"
	CompressSnappy  = "snappy"
)

Tunnel and host override of the compression of a client; "" follows the client.

View Source
const (
	TargetTCP = "tcp"
	TargetUDP = "udp"
	TargetAll = "all" // both
)

Target types of a tunnel: what it forwards to its target.

View Source
const FileServiceKind = "file"

FileServiceKind is the kind npc reports its file services under.

View Source
const ModeService = "service"

ModeService is the mode of a virtual backend.

View Source
const ServiceScheme = "service://"

ServiceScheme starts the target of a virtual backend: the rest is the service id in hex (§8), which depends on nothing a rename changes.

Variables

View Source
var ErrNoTarget = errors.New("all inward-bending targets are offline")

ErrNoTarget is returned when no target address can take a connection.

View Source
var FlowLimitFactor atomic.Int64

FlowLimitFactor is what the flow limits of clients multiply the inbound and outbound traffic by: 1 to count the traffic, 2 to count the actual usage on both sides of the server. A change applies to each client flow at its next use.

View Source
var HostSettings = append([]EntrySetting{
	{Field: "Host", Form: "host", Conf: "host"},
	{Field: "HeaderChange", Form: "header"},
	{Field: "RespHeaderChange", Form: "resp_header"},
	{Field: "HostChange", Form: "hostchange", Conf: "host_change"},
	{Field: "Location", Form: "location", Conf: "location"},
	{Field: "PathRewrite", Form: "path_rewrite", Conf: "path_rewrite"},
	{Field: "RedirectURL", Form: "redirect_url", Conf: "redirect_url"},
	{Field: "Scheme", Form: "scheme", Conf: "scheme", ConfDefault: "all", Custom: true},
	{Field: "HttpsJustProxy", Form: "https_just_proxy", Conf: "https_just_proxy"},
	{Field: "TlsOffload", Form: "tls_offload"},
	{Field: "AutoSSL", Form: "auto_ssl", Conf: "auto_ssl"},
	{Field: "KeyFile", Form: "key_file", Conf: "key_file", ConfPEM: "PRIVATE"},
	{Field: "CertFile", Form: "cert_file", Conf: "cert_file", ConfPEM: "CERTIFICATE"},
	{Field: "AutoHttps", Form: "auto_https", Conf: "auto_https"},
	{Field: "AutoCORS", Form: "auto_cors", Conf: "auto_cors"},
	{Field: "CompatMode", Form: "compat_mode", Conf: "compat_mode"},
	{Field: "TargetIsHttps", Form: "target_is_https", Conf: "target_is_https"},
}, entrySettings...)

HostSettings are the settings of a Host.

View Source
var TunnelSettings = append([]EntrySetting{
	{Field: "Port", Form: "port", Custom: true},
	{Field: "Ports", Conf: "server_port"},
	{Field: "ServerIp", Form: "server_ip", Conf: "server_ip"},
	{Field: "Mode", Form: "type", Conf: "mode", Custom: true},
	{Field: "TargetType", Form: "target_type"},
	{Field: "Target.TargetStr", Conf: "target_port"},
	{Field: "TargetAddr", Conf: "target_ip"},
	{Field: "Password", Form: "password", Conf: "password"},
	{Field: "LocalPath", Conf: "local_path"},
	{Field: "StripPre", Conf: "strip_pre"},
	{Field: "HttpProxy", Form: "enable_http", Conf: "http_proxy"},
	{Field: "Socks5Proxy", Form: "enable_socks5", Conf: "socks5_proxy"},
	{Field: "DestAclMode", Form: "dest_acl_mode", Conf: "dest_acl_mode", Custom: true},
	{Field: "DestAclRules", Form: "dest_acl_rules", FormRaw: true, Conf: "dest_acl_rules", ConfList: true, Custom: true},
	{Field: "ReadOnly", Conf: "read_only"},
	{Field: "NoRelay", Form: "no_relay"},

	{Field: "Target.ProxyProtocolEach", Form: "proxy_protocol_each", Conf: "proxy_protocol_each", Custom: true},
}, entrySettings...)

TunnelSettings are the settings of a Tunnel.

Functions

func ConfigTaskPorts

func ConfigTaskPorts(t *Tunnel) (ports, targets []int, ok bool)

ConfigTaskPorts expands a task delivered by a client configuration into the server ports it is opened on and, for multi-port tcp/udp tasks, the matching target ports. The server reports one add status per returned port, or a single failure status when ok is false, so both sides use this to stay in step on the configuration connection.

func CopyFormSettings

func CopyFormSettings(settings []EntrySetting, dst, src any)

CopyFormSettings copies the form settings that are not Custom from src to dst, both a *Tunnel or both a *Host.

func GetAccountMap

func GetAccountMap(multiAccount *MultiAccount) map[string]string

func GlobalConnections

func GlobalConnections() (active, limit int64)

GlobalConnections reports active forwarding slots and their configured limit.

func ListenIPsOverlap

func ListenIPsOverlap(a, b string) bool

ListenIPsOverlap reports whether two listen addresses can accept the same connection: equal, or either is the wildcard (empty, 0.0.0.0 or ::).

func MatchTargetPorts

func MatchTargetPorts(ports, targets []int, single bool) (matched []int, ok bool)

MatchTargetPorts returns the target port of each of ports. The targets pair with the ports one to one; with single set, one target serves every port. ok is false for any other count.

func NormalizeClientCompress

func NormalizeClientCompress(alg string) string

NormalizeClientCompress returns alg when it is an algorithm of a client's Compress, "" (snappy) otherwise.

func NormalizeCompress

func NormalizeCompress(alg string) string

NormalizeCompress returns alg when it is a compression override (the Compress* constants, "" following the client) and "" otherwise.

func NormalizeTargetType

func NormalizeTargetType(t string) string

NormalizeTargetType returns the target type t names, TargetAll for any value other than TargetTCP and TargetUDP.

func ParseClientCompress

func ParseClientCompress(compress, alg string) (bool, string)

ParseClientCompress reads the compression of a client from a form or API call. compress is the single form choice: 0/1 (the old switch), or an algorithm, which turns compression on with it. alg refines an on switch; "off" in either place turns compression off. The result is the Compress and CompressAlg of the client's Config; off leaves no algorithm.

func ParseServiceTarget

func ParseServiceTarget(target string) (id []byte, ok bool)

ParseServiceTarget returns the service id of a target written by ServiceTarget; ok is false for any other target.

func PortTaskTarget

func PortTaskTarget(host string, port int) string

PortTaskTarget is the target of a tunnel opened for one port of a multi-port task: the port on host, or the bare port when host is empty.

func ResolveCompress

func ResolveCompress(c *Client, override string) []string

ResolveCompress is the compression of a stream of a tunnel or host: override, or the client's when it is CompressDefault.

func ServiceTarget

func ServiceTarget(kind, name string) string

ServiceTarget is the target that reaches the service of kind and name.

func SetClientHistoryLimit

func SetClientHistoryLimit(n int)

SetClientHistoryLimit sets how many connections the history of each client keeps; 0 keeps none.

func SetFlowLimitActual

func SetFlowLimitActual(actual bool)

SetFlowLimitActual makes the flow limits of clients count the actual usage, twice the traffic, or the traffic itself.

func SetGlobalMaxConn

func SetGlobalMaxConn(limit int)

SetGlobalMaxConn updates admission without disconnecting existing transfers.

Types

type Client

type Client struct {
	Cnf       *Config
	Id        int    // id
	VerifyKey string // verify key
	Mode      string // bridge mode
	Addr      string // client ip
	LocalAddr string // client local ip
	Remark    string // remark
	Status    bool   // allowed to connect
	// LaunchForm is the start command form the web page saved, opaque to the
	// server; it holds no vkey.
	LaunchForm string `json:",omitempty"`
	IsConnect  bool   // connected now
	CanUpdate  bool   `json:",omitempty"` // a connected npc can be updated from the web; set when listed
	// Shaped sums the shaping statistics of the connected npc in the
	// direction the server sends; set when listed for a client with shaping.
	Shaped *ShapedStats `json:",omitempty"`
	// Link is how the core sessions of the connected npc are carried; set
	// when listed.
	Link            *ClientLink `json:",omitempty"`
	RateLimit       int         // rate limit (KB/s)
	Flow            *Flow       // flow
	ExportFlow      FlowTotal   // outbound flow of the client's hosts and tasks
	InletFlow       FlowTotal   // inbound flow of the client's hosts and tasks
	Rate            *rate.Rate  // rate limiter
	NoStore         bool        // do not store to file
	NoDisplay       bool        // do not display on web
	KeyKind         KeyKind     `json:"-"` // what the vkey may do on the bridge
	MaxConn         int         // max concurrent connections
	NowConn         int32       // legacy JSON snapshot; use CurrentConnections at runtime
	WebUserName     string      // web username
	WebPassword     string      // web password
	WebTotpSecret   string      // web totp secret
	ConfigConnAllow bool        // allowed by config file
	MaxTunnelNum    int
	Version         string
	SourceLists
	CreateTime        string
	LastOnlineTime    string
	ConnectionHistory *ConnectionHistory `json:",omitempty"`
	// RegisterKey, if set, lets visitors register their address for the
	// client on the registration page, as the verify key does.
	RegisterKey string
	// RegisterMaxHours bounds how long a registration made on the page
	// lasts; 0 means the server default.
	RegisterMaxHours int
	sync.RWMutex
}

func NewClient

func NewClient(vKey string, noStore bool, noDisplay bool) *Client

func (*Client) ControlGroup

func (s *Client) ControlGroup() *byterate.Group

ControlGroup is the client level of global -> client -> resource admission.

func (*Client) CurrentConnections

func (s *Client) CurrentConnections() int32

CurrentConnections includes all admitted connections of the client's resources.

func (*Client) CurrentRates

func (s *Client) CurrentRates() (int64, int64)

CurrentRates reports the client's visitor upload and download speeds. The existing RateLimit continues to limit their combined throughput.

func (*Client) CutConn

func (s *Client) CutConn()

func (*Client) EnsureWebPassword

func (s *Client) EnsureWebPassword()

func (*Client) GetConn

func (s *Client) GetConn() bool

GetConn and CutConn adapt legacy callers to byterate's balanced slot API.

func (*Client) LastSeenTime

func (s *Client) LastSeenTime() string

LastSeenTime snapshots the legacy last-online value without changing its meaning.

func (*Client) MarkSeen

func (s *Client) MarkSeen(now time.Time)

MarkSeen updates the legacy last-online value used by full and live lists.

func (*Client) RecordConnection

func (s *Client) RecordConnection(online bool, now time.Time)

func (*Client) RegisterHoursLimit

func (s *Client) RegisterHoursLimit(def int) int

RegisterHoursLimit returns how long a registration made on the page may last at most, in hours: the client's limit, or def when it sets none.

func (*Client) SetMaxConn

func (s *Client) SetMaxConn(limit int)

SetMaxConn updates the client configuration and its library cap together.

type ClientInfo

type ClientInfo struct {
	ID      int    `json:"id"`
	Remark  string `json:"remark,omitempty"`
	Addr    string `json:"addr,omitempty"`
	Version string `json:"version,omitempty"`
}

ClientInfo describes a client in events. Like TunnelInfo and HostInfo it holds no keys, passwords or certificates.

type ClientLink struct {
	// Pipes counts the pipes in use by carrier, most first: "tls×2 + quic".
	Pipes string `json:",omitempty"`
	// PipeList describes each pipe in use, by session and then pipe order.
	PipeList []PipeStat `json:",omitempty"`
	// Records are the distinct record modes of the sessions: "sealed",
	// "bound" or "trusted".
	Records []string `json:",omitempty"`
}

ClientLink is what the connected core sessions of a client show of how they are carried, as listed.

type Config

type Config struct {
	U        string // username
	P        string // password
	Compress bool
	Crypt    bool
	// Shaping turns on traffic shaping for this client (off by default); it
	// takes effect only with a shaping source configured on the server.
	Shaping bool `json:",omitempty"`
	// CompressAlg is the algorithm of Compress for npc on the core
	// protocol (flate, zstd, snappy); empty is snappy, the old protocol's
	// compression (§7.1).
	CompressAlg string `json:",omitempty"`
	// SchedulerDown is how nps schedules sending to this client on the core
	// protocol (connprofile.Schedulers); empty is affinity.
	SchedulerDown string `json:",omitempty"`
	// SchedulerUp is the scheduler npc is told to use for sending to nps
	// (connprofile.Schedulers); empty tells nothing and npc keeps its own.
	SchedulerUp string `json:",omitempty"`
}

func (*Config) CompressList

func (c *Config) CompressList() []string

CompressList is the default compression of a client: algorithms in order of preference, nil for none (§7). The result is shared and not modified.

func (*Config) SchedulerDownName

func (c *Config) SchedulerDownName() string

SchedulerDownName is the scheduler of sending to the client, "" on a client without a configuration.

func (*Config) SchedulerUpName

func (c *Config) SchedulerUpName() string

SchedulerUpName is the scheduler npc is told to send with, "" for none.

type ConnectionEvent

type ConnectionEvent struct {
	OnlineTime  string
	OfflineTime string
}

ConnectionEvent pairs one connection with its confirmed disconnection. OfflineTime remains empty while online or when shutdown prevented recording it.

type ConnectionHistory

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

ConnectionHistory keeps a bounded, concurrency-safe persisted session history.

func (*ConnectionHistory) MarshalJSON

func (h *ConnectionHistory) MarshalJSON() ([]byte, error)

func (*ConnectionHistory) UnmarshalJSON

func (h *ConnectionHistory) UnmarshalJSON(b []byte) error

type EntrySetting

type EntrySetting struct {
	// Field is the model field, with the fields of pointer fields reached
	// through dots, as "Target.ProxyProtocol". It is a string, int, int64,
	// bool or time.Time field.
	Field string
	Form  string // web form and API parameter; "" if the web does not set it
	Conf  string // npc.conf key; "" if npc.conf does not set it

	// ConfPEM is the PEM block type of an npc.conf value that is PEM text or
	// the path of a PEM file.
	ConfPEM string
	// ConfDefault is the value an npc.conf entry has without the key.
	ConfDefault string

	// FormRaw keeps the form value as entered; other form values are
	// HTML-escaped.
	FormRaw bool
	// ConfList takes commas in the npc.conf value for line breaks.
	ConfList bool
	// Min0 stores a negative number as zero.
	Min0 bool
	// Custom marks a form value the web service checks or derives the stored
	// value from itself; it copies the other form values as they are.
	Custom bool
}

EntrySetting is one setting of a tunnel or host: the model field it sets, the web form and API parameter and the npc.conf key that set it. TunnelSettings and HostSettings are the only lists of them; the web form, the API and npc.conf are all read through these lists.

func (EntrySetting) Set

func (s EntrySetting) Set(entry any, raw string) error

Set stores raw in the field of entry, a *Tunnel or *Host, parsing it for the type of the field. A number that cannot be parsed is stored as zero; a boolean that cannot be parsed is stored as false and reported.

type Flow

type Flow struct {
	ExportFlow int64     // outbound traffic
	InletFlow  int64     // inbound traffic
	FlowLimit  int64     // traffic limit
	TimeLimit  time.Time // expire time
	// DirectIn and DirectOut are the bytes of a point-to-point tunnel that
	// went over direct paths, as its providers reported them: statistics
	// only, outside the quota and the rates (Over, the budget and the
	// counter never see them). Only tunnels record them.
	DirectIn  int64 `json:",omitempty"`
	DirectOut int64 `json:",omitempty"`

	sync.RWMutex
	// contains filtered or unexported fields
}

Flow is the payload traffic of a client, tunnel or host and its limits. The exported fields are what is persisted: InletFlow and ExportFlow give the traffic counted before, which the Flow takes over on first use; read the current values with Values. The traffic counts in a Counter, and the limits are kept by a Budget that stops all bytes at FlowLimit MiB and after TimeLimit; FlowConn charges both directions of its connection to it.

func (*Flow) Add

func (s *Flow) Add(in, out int64)

Add counts in bytes of inbound and out bytes of outbound traffic that passed outside a FlowConn.

func (*Flow) AddDirect

func (s *Flow) AddDirect(in, out int64)

AddDirect counts bytes of direct traffic reported by a provider: in were received and out sent by it. It is not charged to the budget.

func (*Flow) Budget

func (s *Flow) Budget() *byterate.Budget

Budget returns the budget that the traffic of s is charged to, nil for a nil s.

func (*Flow) MarkClient

func (s *Flow) MarkClient()

MarkClient marks f as the flow of a client, see FlowLimitFactor.

func (*Flow) MarshalJSON

func (s *Flow) MarshalJSON() ([]byte, error)

MarshalJSON snapshots the persisted fields while transfers update them.

func (*Flow) Over

func (s *Flow) Over() (traffic, expired bool)

Over reports whether the flow is over its traffic limit (FlowLimit MiB of inbound and outbound traffic together, scaled for a client by FlowLimitFactor) or past its time limit.

func (*Flow) ResetTraffic

func (s *Flow) ResetTraffic()

ResetTraffic zeroes the inbound and outbound traffic, the direct traffic included.

func (*Flow) SetFlowLimit

func (s *Flow) SetFlowLimit(limit int64)

SetFlowLimit sets the traffic limit in MiB, 0 for none.

func (*Flow) SetLimits

func (s *Flow) SetLimits(flowLimit int64, timeLimit time.Time)

SetLimits sets the traffic limit in MiB and the time limit together.

func (*Flow) SetOwner

func (s *Flow) SetOwner(args ...any)

SetOwner names the entry of f in its quota_reached events, as fields such as "client", 3 or "tunnel", 7, "client", 3.

func (*Flow) SetTimeLimit

func (s *Flow) SetTimeLimit(limit time.Time)

SetTimeLimit sets the time limit, the zero time for none.

func (*Flow) Traffic

func (s *Flow) Traffic() *byterate.Counter

Traffic returns the counter of s, whose reads are the outbound traffic and whose writes are the inbound traffic, nil for a nil s.

func (*Flow) Values

func (s *Flow) Values() FlowValues

Values returns a snapshot of the flow; a nil flow gives zero values.

func (*Flow) Watch added in v0.35.2

func (s *Flow) Watch(f func()) (stop func())

Watch calls f, which must return quickly, after each change of the limits of s or reset of its traffic, until the function it returns is called. A nil s is never changed.

type FlowTotal

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

FlowTotal is a traffic total that is updated while it is read and marshalled; it is stored and read atomically and encodes as a JSON number.

func (*FlowTotal) Load

func (t *FlowTotal) Load() int64

func (*FlowTotal) MarshalJSON

func (t *FlowTotal) MarshalJSON() ([]byte, error)

func (*FlowTotal) Store

func (t *FlowTotal) Store(n int64)

func (*FlowTotal) UnmarshalJSON

func (t *FlowTotal) UnmarshalJSON(b []byte) error

type FlowValues

type FlowValues struct {
	InletFlow, ExportFlow, FlowLimit, Used int64
	// DirectIn and DirectOut are Flow.DirectIn and Flow.DirectOut.
	DirectIn, DirectOut int64
	TimeLimit           time.Time
}

FlowValues is a snapshot of a Flow. Used is the traffic its limit counts: the inbound and outbound traffic, scaled by FlowLimitFactor for a client.

type Glob

type Glob struct {
	SourceLists
	MaxConn int // total concurrent forwarded connections; zero means unlimited
	// RateLimit limits all forwarded traffic together, in KB/s; 0 means
	// unlimited.
	RateLimit int
	// InletFlow and ExportFlow are the bytes forwarded in total, from
	// visitors to clients and back, as of the last store; the running
	// totals are kept by package rate.
	InletFlow  int64
	ExportFlow int64
	sync.RWMutex
}

func (*Glob) ApplyLimits

func (g *Glob) ApplyLimits()

ApplyLimits applies the global bandwidth and connection limits.

type HealthCheck

type HealthCheck struct {
	Enabled  bool
	Type     string // tcp, http or https
	Path     string // of an http or https check
	Interval int    // seconds
	Timeout  int    // seconds
	MaxFail  int
}

HealthCheck is what can be set for a health check given by the server.

func (HealthCheck) Normalized

func (c HealthCheck) Normalized() HealthCheck

Normalized returns c with what is unset or unusable replaced by defaults.

type Host

type Host struct {
	RateLimits
	// Compress overrides the client's compression (Compress* constants).
	Compress         string `json:",omitempty"`
	Id               int
	Host             string // host
	HeaderChange     string // request header change
	RespHeaderChange string // response header change
	HostChange       string // host change
	Location         string // url router
	PathRewrite      string // url rewrite
	Remark           string // remark
	Scheme           string // http/https/all
	RedirectURL      string // 307
	HttpsJustProxy   bool
	TlsOffload       bool
	AutoSSL          bool
	CertType         string
	CertHash         string
	CertFile         string
	KeyFile          string
	NoStore          bool
	IsClose          bool
	AutoHttps        bool
	AutoCORS         bool
	CompatMode       bool
	Flow             *Flow
	MaxConn          int // concurrent HTTP requests and HTTPS connections; zero means unlimited
	NowConn          int32
	Client           *Client
	TargetIsHttps    bool
	Target           *Target
	Routes           *RouteSet `json:"-"`
	UserAuth         *MultiAccount
	MultiAccount     *MultiAccount
	SourceLists
	// HealthConfig is as in Tunnel.
	HealthConfig *HealthCheck `json:",omitempty"`
	sync.RWMutex
}

func (*Host) Clone

func (s *Host) Clone() *Host

Clone returns a copy of s that holds every stored field, taken under the lock, so it can be marshaled while s is being updated. Flow is copied by value; Client, Target and the account settings are shared.

func (*Host) ControlGroup

func (s *Host) ControlGroup() *byterate.Group

ControlGroup is a domain's leaf under its client; byte controls share it.

func (*Host) CurrentConnections

func (s *Host) CurrentConnections() int32

func (*Host) HealthCheck

func (s *Host) HealthCheck() HealthCheck

HealthCheck returns the settings of the entry's check, with defaults.

func (*Host) Modify

func (s *Host) Modify(fn func(s *Host))

Modify runs fn with s locked for writing, for an edit of the settings of a host that is serving. fn must not call methods of s that take its lock.

func (*Host) Route

func (s *Host) Route() Route

Route picks the route of one request of s.

func (*Host) SetHealthCheck

func (s *Host) SetHealthCheck(c HealthCheck)

SetHealthCheck sets the entry's check.

func (*Host) SetMaxConn

func (s *Host) SetMaxConn(limit int)

SetMaxConn updates the library cap without reclaiming active slots.

func (*Host) Update

func (s *Host) Update(h *Host)

func (*Host) View

func (s *Host) View() HostView

View returns the current settings of s.

type HostInfo

type HostInfo struct {
	ID         int    `json:"id"`
	ClientID   int    `json:"client_id"`
	Host       string `json:"host"`
	Location   string `json:"location,omitempty"`
	Scheme     string `json:"scheme,omitempty"`
	Target     string `json:"target,omitempty"`
	Remark     string `json:"remark,omitempty"`
	Enabled    bool   `json:"enabled"`
	FromClient bool   `json:"from_client"`
}

HostInfo describes a domain entry in events.

func NewHostInfo

func NewHostInfo(h *Host) HostInfo

NewHostInfo snapshots h.

type HostView

type HostView struct {
	HeaderChange     string
	RespHeaderChange string
	HostChange       string
	PathRewrite      string
	Remark           string
	RedirectURL      string
	CertType         string
	CertHash         string
	CertFile         string
	KeyFile          string
	HttpsJustProxy   bool
	AutoSSL          bool
	AutoHttps        bool
	AutoCORS         bool
	CompatMode       bool
	TargetIsHttps    bool
	Target           *Target
	MultiAccount     *MultiAccount
	Source           SourceView
}

HostView is an immutable copy of the settings of a host that an update from the client's configuration can replace while the host is serving. Target and MultiAccount are replaced by an update, never modified, so the view may keep reading through them.

Code that reads these fields on a host other than one it is still building takes a view and reads the view; the fields themselves are only touched under the host's lock, here and in Update.

func (HostView) HasCert

func (v HostView) HasCert() bool

HasCert reports whether the host has a certificate configured.

type KeyKind

type KeyKind uint8

KeyKind is the scope of a client's vkey on the bridge.

const (
	KeyControl KeyKind = iota // a stored client: every workflow
	KeyPublic                 // public_vkey: every workflow but the main one
	KeyVisitor                // visitor_vkey: visiting secret and P2P tasks
)

type MultiAccount

type MultiAccount struct {
	Content    string
	AccountMap map[string]string // multi account and pwd
}

type PipeStat added in v0.35.4

type PipeStat struct {
	Carrier  string
	RTTMs    int64  // smoothed round-trip time, 0 before a sample
	UpSec    int64  // seconds since the pipe attached
	Sent     uint64 // bytes the server sent on it
	Received uint64 // bytes the server received on it
	Rate     uint64 // estimated delivery rate, bytes per second
	Standby  bool
}

PipeStat is one pipe of a client's sessions for the web pages.

type RateLimits

type RateLimits struct {
	UploadLimit   int
	DownloadLimit int
	// contains filtered or unexported fields
}

RateLimits stores per-entry limits in KiB/s. Runtime buckets are never persisted. Upload runs from visitors to the backend; download runs in the other direction.

func (*RateLimits) ClearDownloadLimit

func (r *RateLimits) ClearDownloadLimit()

ClearDownloadLimit removes only the download limit.

func (*RateLimits) ClearUploadLimit

func (r *RateLimits) ClearUploadLimit()

ClearUploadLimit removes only the upload limit.

func (*RateLimits) CurrentRates

func (r *RateLimits) CurrentRates() (int64, int64)

CurrentRates returns measured upload and download speeds in bytes per second.

func (*RateLimits) RateLimiter

func (r *RateLimits) RateLimiter() *rate.Directional

RateLimiter returns the shared buckets, initializing loaded configuration lazily.

func (*RateLimits) SetRateLimits

func (r *RateLimits) SetRateLimits(upload, download int)

SetRateLimits applies configuration to existing connections as well as new ones.

type Route

type Route struct {
	Node   string
	Target *Target
}

Route is where one request of a Tunnel or Host goes: to Target through Node, or through any node of the client if Node is empty.

type RouteSet

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

RouteSet holds the npc instances, by node UUID, that publish one configuration-mode entry, each with its own target. The settings of the entry other than the target are shared, the last publisher's being used. A nil RouteSet, as on entries managed on the web, has no routes.

func NewRouteSet

func NewRouteSet(usable func(node string) bool) *RouteSet

NewRouteSet returns an empty set. usable tells whether a node can take connections now; nodes are skipped while it returns false.

func (*RouteSet) HasOther

func (r *RouteSet) HasOther(node string) bool

HasOther reports whether a node other than node is in the set.

func (*RouteSet) Holding

func (r *RouteSet) Holding(target *Target) *Target

Holding returns target if a node of the set has it, and otherwise the target of the first node.

func (*RouteSet) Len

func (r *RouteSet) Len() int

Len returns the number of nodes.

func (*RouteSet) Publish

func (r *RouteSet) Publish(node string, target *Target)

Publish adds node with target, or gives it a new target.

func (*RouteSet) Retain

func (r *RouteSet) Retain(keep func(node string) bool) (removed bool)

Retain removes the nodes keep rejects and reports whether it removed any.

func (*RouteSet) Target

func (r *RouteSet) Target(node string, fallback *Target) *Target

Target returns the target of node, or fallback if node has none.

type ShapedStats

type ShapedStats struct {
	Wire          uint64 // wire bytes added
	StallMs       int64  // waits applied, in milliseconds
	Injected      uint64 // records sent for shaping only
	Clamped       uint64
	InjectDropped uint64
	Faults        uint64 // shaper calls that failed
}

ShapedStats are the shaping statistics of a client, as listed.

type SourceLists

type SourceLists struct {
	// IpListPriority decides an address on both lists or on neither when
	// both are set: acl.DenyFirst (0) or acl.AllowFirst (1).
	IpListPriority int
	BlackIpList    []string
	WhiteIpList    []string

	// RegisteredOnly additionally requires the visitor address to be
	// registered for the client, see package ipreg. The global settings do
	// not use it.
	RegisteredOnly bool
	// contains filtered or unexported fields
}

SourceLists are the source access lists of a level, the global settings, a client, a tunnel or a host: which visitor addresses may connect. Every level has to allow an address.

func (*SourceLists) CompileSourceLists

func (l *SourceLists) CompileSourceLists(scope acl.Scope, owner string)

CompileSourceLists compiles the lists. Rules that cannot be used, such as geoip: rules without geodata, are logged and skipped.

func (*SourceLists) CopySourceLists

func (l *SourceLists) CopySourceLists(other *SourceLists)

CopySourceLists copies the lists of other and their compiled form.

func (*SourceLists) SetSourceLists

func (l *SourceLists) SetSourceLists(priority int, black, white []string, scope acl.Scope, owner string)

SetSourceLists replaces the lists and compiles them.

func (*SourceLists) SourceACL

func (l *SourceLists) SourceACL() *acl.Source

SourceACL returns the compiled lists, compiling them as user lists if that has not happened yet.

func (*SourceLists) View

func (l *SourceLists) View() SourceView

View returns the view of l, compiling the lists as user lists if that has not happened yet. The caller has to keep l from being rewritten meanwhile.

type SourceView

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

SourceView is an immutable view of an entry's source lists: the compiled lists and whether the visitor address has to be registered. The zero value stands for no entry and allows everything.

func (SourceView) ACL

func (v SourceView) ACL() *acl.Source

ACL returns the compiled lists.

func (SourceView) RegisteredOnly

func (v SourceView) RegisteredOnly() bool

RegisteredOnly reports whether only registered visitor addresses are let in.

type Target

type Target struct {
	TargetStr  string
	LocalProxy bool
	// ProxyProtocolEach puts the PROXY header in front of every UDP datagram
	// instead of the first of a session only. TCP and hosts ignore it. Left
	// out of JSON when false, as entries of released peers have it.
	ProxyProtocolEach bool `json:",omitempty"`
	ProxyProtocol     int  // 0=off, 1=v1, 2=v2
	// contains filtered or unexported fields
}

func (*Target) Addresses

func (s *Target) Addresses() []string

Addresses returns the distinct addresses a health check can reach. A target the server dials itself has none: its own dials judge it.

func (*Target) Dial

func (s *Target) Dial(dial func(addr string) (direct bool, err error)) error

Dial connects to a target: it calls dial with the next healthy target address, in weighted round-robin order, and again with another address each time dial fails for that address, trying each address at most once. dial reports whether it reached the address itself; only such results judge the address, while a failure on the way to it, such as on the link to the client that dials it, ends Dial without a retry. Dial returns ErrNoTarget if no address can be tried, and otherwise dial's last error.

func (*Target) SetHealthy

func (s *Target) SetHealthy(addr string, healthy bool) bool

SetHealthy takes addr out of the rotation or puts it back, and reports whether addr is one of the configured targets. The client's checks override failed dials: an address it reports healthy again is no longer ejected for them.

type Tunnel

type Tunnel struct {
	RateLimits
	MaxConn      int // concurrent connections; zero means unlimited
	Id           int
	Port         int
	ServerIp     string
	Mode         string
	Status       bool
	RunStatus    bool
	Client       *Client
	Ports        string
	Flow         *Flow
	NowConn      int32
	Password     string
	Remark       string
	TargetAddr   string
	TargetType   string
	DestAclMode  int    // 0=off, 1=whitelist, 2=blacklist
	DestAclRules string // one rule per line

	SourceLists
	NoStore     bool
	IsHttp      bool
	HttpProxy   bool
	Socks5Proxy bool
	LocalPath   string
	StripPre    string
	ReadOnly    bool
	// NoRelay keeps the server from relaying a secret tunnel's links: the
	// visitor and the provider must reach each other directly.
	NoRelay      bool `json:",omitempty"`
	Target       *Target
	Routes       *RouteSet `json:"-"`
	UserAuth     *MultiAccount
	MultiAccount *MultiAccount
	// HealthConfig is the check the server gives the client; replaced, never
	// modified, under the entry's lock.
	HealthConfig *HealthCheck `json:",omitempty"`
	sync.RWMutex
	// Compress overrides the client's compression (Compress* constants).
	Compress string `json:",omitempty"`
	// ServiceKind and ServiceName are what npc reports a virtual backend
	// under (§8). The server shows them and treats them as opaque; together
	// they decide the identifier in Target, so neither is ever edited.
	ServiceKind string `json:",omitempty"`
	ServiceName string `json:",omitempty"`
	// Generated marks a tunnel converted from a file tunnel with a port.
	Generated bool `json:",omitempty"`
	// LaunchForm is the start command form the web page saved, opaque to the
	// server; it holds no access key.
	LaunchForm string `json:",omitempty"`
	// contains filtered or unexported fields
}

func ConvertFileTunnel

func ConvertFileTunnel(t *Tunnel) ([]*Tunnel, bool)

ConvertFileTunnel makes the file tunnel t the description of a local virtual service, in place, and returns one tcp tunnel per port of t that listens there and targets the service; a tunnel with no port gets none. npc serves what t describes; the server keeps only the returned tunnels. It reports false, changing nothing, for what is no file tunnel or is a backend already, so applying it twice is applying it once. The returned tunnels have no Id.

The service is named by the first port, or by the remark without one, so that its identifier stays the same across restarts and renames.

func NewTunnelByHost

func NewTunnelByHost(host *Host, port int) *Tunnel

func (*Tunnel) AdoptRuntime

func (t *Tunnel) AdoptRuntime(previous *Tunnel)

AdoptRuntime makes t, an accepted edit of previous, take over the rate buckets, connection slots and flow of previous, so that the connections already open keep counting against the edited tunnel.

func (*Tunnel) AllowsDestination

func (t *Tunnel) AllowsDestination(addr string) bool

AllowsDestination reports whether the destination list lets the tunnel reach addr, a host or host:port.

func (*Tunnel) Clone

func (t *Tunnel) Clone() *Tunnel

Clone returns a copy of t that can be edited and then stored with UpdateTask without touching t until the update is accepted. Flow and the health state are copied; Client, Target and the account settings are shared and are expected to be replaced rather than modified. Connection reservations are reattached on accepted updates, so an edit cannot forget active slots.

func (*Tunnel) CompileDestACL

func (t *Tunnel) CompileDestACL()

CompileDestACL compiles the destination list. Rules that cannot be used are logged and skipped.

func (*Tunnel) ControlGroup

func (t *Tunnel) ControlGroup() *byterate.Group

ControlGroup is a tunnel's leaf under its client, shared across accepted edits.

func (*Tunnel) CurrentConnections

func (t *Tunnel) CurrentConnections() int32

func (*Tunnel) CutConn

func (t *Tunnel) CutConn()

func (*Tunnel) GetConn

func (t *Tunnel) GetConn() bool

func (*Tunnel) HealthCheck

func (t *Tunnel) HealthCheck() HealthCheck

HealthCheck returns the settings of the entry's check, with defaults.

func (*Tunnel) IsVirtualBackend

func (t *Tunnel) IsVirtualBackend() bool

IsVirtualBackend reports whether t describes a virtual service of npc, which is never stored: the server only ever sees what a session reports.

func (*Tunnel) ListenIP

func (t *Tunnel) ListenIP() string

ListenIP returns the address t listens on, setting the wildcard address if none is set.

func (*Tunnel) ListenKinds

func (t *Tunnel) ListenKinds() (tcp, udp bool)

ListenKinds reports the protocols t listens on at its port: TCP unless the mode is udp, and UDP for udp, socks5 and a mixed proxy with SOCKS5. A secret tunnel listens nowhere.

func (*Tunnel) LogRoute

func (t *Tunnel) LogRoute() string

LogRoute names t in log lines: "<mode>:<port>" for a tunnel, the domain for one built for a host entry.

func (*Tunnel) Modify

func (t *Tunnel) Modify(fn func(t *Tunnel))

Modify runs fn with t locked for writing, for an edit of the settings of a tunnel that is serving. fn must not call methods of t that take its lock.

func (*Tunnel) RelayTarget

func (t *Tunnel) RelayTarget() string

RelayTarget names where the tunnel forwards to.

func (*Tunnel) Route

func (t *Tunnel) Route() Route

Route picks the route of one request of t.

func (*Tunnel) SetHealthCheck

func (t *Tunnel) SetHealthCheck(c HealthCheck)

SetHealthCheck sets the entry's check.

func (*Tunnel) SetIsHTTP

func (t *Tunnel) SetIsHTTP(isHTTP bool)

SetIsHTTP records whether the tunnel's traffic looks like HTTP.

func (*Tunnel) SetMaxConn

func (t *Tunnel) SetMaxConn(limit int)

SetMaxConn updates the library cap without reclaiming active slots.

func (*Tunnel) Update

func (t *Tunnel) Update(other *Tunnel)

func (*Tunnel) View

func (t *Tunnel) View() TunnelView

View returns the current settings of t.

type TunnelInfo

type TunnelInfo struct {
	ID       int    `json:"id"`
	ClientID int    `json:"client_id"`
	Mode     string `json:"mode"`
	ServerIP string `json:"server_ip,omitempty"`
	Port     int    `json:"port"`
	Target   string `json:"target,omitempty"`
	Remark   string `json:"remark,omitempty"`
	Enabled  bool   `json:"enabled"`
	// FromClient marks an entry delivered by the client's configuration, which
	// goes when the client does.
	FromClient bool `json:"from_client"`
}

TunnelInfo describes a tunnel in events.

func NewTunnelInfo

func NewTunnelInfo(t *Tunnel) TunnelInfo

NewTunnelInfo snapshots t.

type TunnelView

type TunnelView struct {
	ServerIp     string
	Mode         string
	Password     string
	Remark       string
	TargetType   string
	HttpProxy    bool
	Socks5Proxy  bool
	ReadOnly     bool
	NoRelay      bool
	DestAclMode  int
	DestAclRules string
	LocalPath    string
	StripPre     string
	Target       *Target
	MultiAccount *MultiAccount
	Source       SourceView
}

TunnelView is an immutable copy of the settings of a tunnel that an update from the client's configuration can replace while the tunnel is serving. Target and MultiAccount are replaced by an update, never modified, so the view may keep reading through them.

Code that reads these fields on a tunnel other than one it is still building takes a view and reads the view; the fields themselves are only touched under the tunnel's lock, here and in Update.

Jump to

Keyboard shortcuts

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