Documentation
¶
Index ¶
- Constants
- Variables
- func ConfigTaskPorts(t *Tunnel) (ports, targets []int, ok bool)
- func CopyFormSettings(settings []EntrySetting, dst, src any)
- func GetAccountMap(multiAccount *MultiAccount) map[string]string
- func GlobalConnections() (active, limit int64)
- func ListenIPsOverlap(a, b string) bool
- func MatchTargetPorts(ports, targets []int, single bool) (matched []int, ok bool)
- func NormalizeClientCompress(alg string) string
- func NormalizeCompress(alg string) string
- func NormalizeTargetType(t string) string
- func ParseClientCompress(compress, alg string) (bool, string)
- func ParseServiceTarget(target string) (id []byte, ok bool)
- func PortTaskTarget(host string, port int) string
- func ResolveCompress(c *Client, override string) []string
- func ServiceTarget(kind, name string) string
- func SetClientHistoryLimit(n int)
- func SetFlowLimitActual(actual bool)
- func SetGlobalMaxConn(limit int)
- type Client
- func (s *Client) ControlGroup() *byterate.Group
- func (s *Client) CurrentConnections() int32
- func (s *Client) CurrentRates() (int64, int64)
- func (s *Client) CutConn()
- func (s *Client) EnsureWebPassword()
- func (s *Client) GetConn() bool
- func (s *Client) LastSeenTime() string
- func (s *Client) MarkSeen(now time.Time)
- func (s *Client) RecordConnection(online bool, now time.Time)
- func (s *Client) RegisterHoursLimit(def int) int
- func (s *Client) SetMaxConn(limit int)
- type ClientInfo
- type ClientLink
- type Config
- type ConnectionEvent
- type ConnectionHistory
- type EntrySetting
- type Flow
- func (s *Flow) Add(in, out int64)
- func (s *Flow) AddDirect(in, out int64)
- func (s *Flow) Budget() *byterate.Budget
- func (s *Flow) MarkClient()
- func (s *Flow) MarshalJSON() ([]byte, error)
- func (s *Flow) Over() (traffic, expired bool)
- func (s *Flow) ResetTraffic()
- func (s *Flow) SetFlowLimit(limit int64)
- func (s *Flow) SetLimits(flowLimit int64, timeLimit time.Time)
- func (s *Flow) SetOwner(args ...any)
- func (s *Flow) SetTimeLimit(limit time.Time)
- func (s *Flow) Traffic() *byterate.Counter
- func (s *Flow) Values() FlowValues
- func (s *Flow) Watch(f func()) (stop func())
- type FlowTotal
- type FlowValues
- type Glob
- type HealthCheck
- type Host
- func (s *Host) Clone() *Host
- func (s *Host) ControlGroup() *byterate.Group
- func (s *Host) CurrentConnections() int32
- func (s *Host) HealthCheck() HealthCheck
- func (s *Host) Modify(fn func(s *Host))
- func (s *Host) Route() Route
- func (s *Host) SetHealthCheck(c HealthCheck)
- func (s *Host) SetMaxConn(limit int)
- func (s *Host) Update(h *Host)
- func (s *Host) View() HostView
- type HostInfo
- type HostView
- type KeyKind
- type MultiAccount
- type PipeStat
- type RateLimits
- type Route
- type RouteSet
- func (r *RouteSet) HasOther(node string) bool
- func (r *RouteSet) Holding(target *Target) *Target
- func (r *RouteSet) Len() int
- func (r *RouteSet) Publish(node string, target *Target)
- func (r *RouteSet) Retain(keep func(node string) bool) (removed bool)
- func (r *RouteSet) Target(node string, fallback *Target) *Target
- type ShapedStats
- type SourceLists
- func (l *SourceLists) CompileSourceLists(scope acl.Scope, owner string)
- func (l *SourceLists) CopySourceLists(other *SourceLists)
- func (l *SourceLists) SetSourceLists(priority int, black, white []string, scope acl.Scope, owner string)
- func (l *SourceLists) SourceACL() *acl.Source
- func (l *SourceLists) View() SourceView
- type SourceView
- type Target
- type Tunnel
- func (t *Tunnel) AdoptRuntime(previous *Tunnel)
- func (t *Tunnel) AllowsDestination(addr string) bool
- func (t *Tunnel) Clone() *Tunnel
- func (t *Tunnel) CompileDestACL()
- func (t *Tunnel) ControlGroup() *byterate.Group
- func (t *Tunnel) CurrentConnections() int32
- func (t *Tunnel) CutConn()
- func (t *Tunnel) GetConn() bool
- func (t *Tunnel) HealthCheck() HealthCheck
- func (t *Tunnel) IsVirtualBackend() bool
- func (t *Tunnel) ListenIP() string
- func (t *Tunnel) ListenKinds() (tcp, udp bool)
- func (t *Tunnel) LogRoute() string
- func (t *Tunnel) Modify(fn func(t *Tunnel))
- func (t *Tunnel) RelayTarget() string
- func (t *Tunnel) Route() Route
- func (t *Tunnel) SetHealthCheck(c HealthCheck)
- func (t *Tunnel) SetIsHTTP(isHTTP bool)
- func (t *Tunnel) SetMaxConn(limit int)
- func (t *Tunnel) Update(other *Tunnel)
- func (t *Tunnel) View() TunnelView
- type TunnelInfo
- type TunnelView
Constants ¶
const ( AclOff = 0 AclWhitelist = 1 AclBlacklist = 2 )
ACLMode: 0=off, 1=whitelist(deny-by-default), 2=blacklist(allow-by-default)
const ( CompressDefault = "" CompressOff = "off" CompressFlate = "flate" CompressZstd = "zstd" CompressSnappy = "snappy" )
Tunnel and host override of the compression of a client; "" follows the client.
const ( TargetTCP = "tcp" TargetUDP = "udp" TargetAll = "all" // both )
Target types of a tunnel: what it forwards to its target.
const FileServiceKind = "file"
FileServiceKind is the kind npc reports its file services under.
const ModeService = "service"
ModeService is the mode of a virtual backend.
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 ¶
var ErrNoTarget = errors.New("all inward-bending targets are offline")
ErrNoTarget is returned when no target address can take a connection.
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
NormalizeClientCompress returns alg when it is an algorithm of a client's Compress, "" (snappy) otherwise.
func NormalizeCompress ¶
NormalizeCompress returns alg when it is a compression override (the Compress* constants, "" following the client) and "" otherwise.
func NormalizeTargetType ¶
NormalizeTargetType returns the target type t names, TargetAll for any value other than TargetTCP and TargetUDP.
func ParseClientCompress ¶
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 ¶
ParseServiceTarget returns the service id of a target written by ServiceTarget; ok is false for any other target.
func PortTaskTarget ¶
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 ¶
ResolveCompress is the compression of a stream of a tunnel or host: override, or the client's when it is CompressDefault.
func ServiceTarget ¶
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 (*Client) ControlGroup ¶
ControlGroup is the client level of global -> client -> resource admission.
func (*Client) CurrentConnections ¶
CurrentConnections includes all admitted connections of the client's resources.
func (*Client) CurrentRates ¶
CurrentRates reports the client's visitor upload and download speeds. The existing RateLimit continues to limit their combined throughput.
func (*Client) EnsureWebPassword ¶
func (s *Client) EnsureWebPassword()
func (*Client) LastSeenTime ¶
LastSeenTime snapshots the legacy last-online value without changing its meaning.
func (*Client) MarkSeen ¶
MarkSeen updates the legacy last-online value used by full and live lists.
func (*Client) RegisterHoursLimit ¶
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 ¶
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 ¶ added in v0.35.2
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 ¶
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 ¶
SchedulerDownName is the scheduler of sending to the client, "" on a client without a configuration.
func (*Config) SchedulerUpName ¶
SchedulerUpName is the scheduler npc is told to send with, "" for none.
type ConnectionEvent ¶
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.
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 ¶
Add counts in bytes of inbound and out bytes of outbound traffic that passed outside a FlowConn.
func (*Flow) AddDirect ¶
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 ¶
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 ¶
MarshalJSON snapshots the persisted fields while transfers update them.
func (*Flow) Over ¶
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 ¶
SetFlowLimit sets the traffic limit in MiB, 0 for none.
func (*Flow) SetOwner ¶
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 ¶
SetTimeLimit sets the time limit, the zero time for none.
func (*Flow) Traffic ¶
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.
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) MarshalJSON ¶
func (*FlowTotal) UnmarshalJSON ¶
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 ¶
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 ¶
ControlGroup is a domain's leaf under its client; byte controls share it.
func (*Host) CurrentConnections ¶
func (*Host) HealthCheck ¶
func (s *Host) HealthCheck() HealthCheck
HealthCheck returns the settings of the entry's check, with defaults.
func (*Host) Modify ¶
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) SetHealthCheck ¶
func (s *Host) SetHealthCheck(c HealthCheck)
SetHealthCheck sets the entry's check.
func (*Host) SetMaxConn ¶
SetMaxConn updates the library cap without reclaiming active slots.
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.
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.
type MultiAccount ¶
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 ¶
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 ¶
NewRouteSet returns an empty set. usable tells whether a node can take connections now; nodes are skipped while it returns false.
func (*RouteSet) Holding ¶
Holding returns target if a node of the set has it, and otherwise the target of the first node.
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) 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 ¶
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 ¶
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 ¶
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 ¶
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 (*Tunnel) AdoptRuntime ¶
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 ¶
AllowsDestination reports whether the destination list lets the tunnel reach addr, a host or host:port.
func (*Tunnel) Clone ¶
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 ¶
ControlGroup is a tunnel's leaf under its client, shared across accepted edits.
func (*Tunnel) CurrentConnections ¶
func (*Tunnel) HealthCheck ¶
func (t *Tunnel) HealthCheck() HealthCheck
HealthCheck returns the settings of the entry's check, with defaults.
func (*Tunnel) IsVirtualBackend ¶
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 ¶
ListenIP returns the address t listens on, setting the wildcard address if none is set.
func (*Tunnel) ListenKinds ¶
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 ¶
LogRoute names t in log lines: "<mode>:<port>" for a tunnel, the domain for one built for a host entry.
func (*Tunnel) Modify ¶
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 ¶
RelayTarget names where the tunnel forwards to.
func (*Tunnel) SetHealthCheck ¶
func (t *Tunnel) SetHealthCheck(c HealthCheck)
SetHealthCheck sets the entry's check.
func (*Tunnel) SetMaxConn ¶
SetMaxConn updates the library cap without reclaiming active slots.
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.
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.