core

package
v1.9.3 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: GPL-3.0 Imports: 113 Imported by: ? modules, 0 packages

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

Documentation

Index

Constants

View Source
const (
	// UnclosableQUIC is a Hysteria, Hysteria2 or TUIC inbound: this layer has no
	// handle on a QUIC session (see core/usersession).
	UnclosableQUIC = "quic"
	// UnclosableMux is a Shadowsocks inbound running with multiplex on.
	// Shadowsocks has no copy in core/protocol/, so its carrier is out of reach.
	UnclosableMux = "mux"
)

Why a kick left an inbound with a session it could not cut. These are what the panel turns into words, so they are part of the closeSessions answer.

View Source
const IPv6IdentityPrefixBits = 64

IPv6IdentityPrefixBits is how much of an IPv6 address identifies one subscriber. This is policy rather than mechanism -- /128 lets a single SLAAC host exhaust any limit through address rotation, /48 would hold an entire site to one slot -- but unlike the ban list it cannot live in the service layer: the normalized address is the map key every later stage groups on, so it has to be decided at track time. Change the trade-off here.

Exported because anything displaying a normalized v6 address has to say which prefix it stands for: the bare masked address is one no client ever used.

Variables

This section is empty.

Functions

func CertificateProviderRegistry added in v1.8.0

func CertificateProviderRegistry() *sbCertificate.Registry

func CompareUnclosable added in v1.9.1

func CompareUnclosable(a, b UnclosableInbound) int

CompareUnclosable is the order of a report: this panel's own inbounds first, then each node's, by tag within each. It is the one rule for both this package's list and a master's merged one, so a list reads the same however it was put together.

func Context

func Context(
	ctx context.Context,
	inboundRegistry adapter.InboundRegistry,
	outboundRegistry adapter.OutboundRegistry,
	endpointRegistry adapter.EndpointRegistry,
	dnsTransportRegistry adapter.DNSTransportRegistry,
	serviceRegistry adapter.ServiceRegistry,
	certificateProviderRegistry adapter.CertificateProviderRegistry,
) context.Context

func DNSTransportRegistry

func DNSTransportRegistry() *dns.TransportRegistry

func EndpointRegistry

func EndpointRegistry() *endpoint.Registry

func IPLimitActive added in v1.7.0

func IPLimitActive() bool

IPLimitActive reports whether lastActive is being stamped at all. Readers of IPWindow.LastSeen need it: with no limit anywhere the field never moves off the connection's creation time, so an idle test against it measures age, not inactivity.

func InboundRegistry

func InboundRegistry() *inbound.Registry

func NewDefaultFactory

func NewDefaultFactory(
	ctx context.Context,
	formatter log.Formatter,
	writer io.Writer,
	filePath string,
	needObservable bool,
) log.ObservableFactory

func NewFactory

func NewFactory(options log.Options) (log.Factory, error)

func OutboundRegistry

func OutboundRegistry() *outbound.Registry

func ServiceRegistry

func ServiceRegistry() *service.Registry

func SetConnGate added in v1.7.0

func SetConnGate(gate ConnGate)

SetConnGate installs (or with a nil gate, removes) the connection gate. It is read per connection instead of captured in NewConnTracker so that installing it never has to be ordered against core startup: Box, and with it every tracker, is rebuilt from scratch on each Start.

func SetIPLimitActive added in v1.7.0

func SetIPLimitActive(active bool)

SetIPLimitActive tells the trackers whether any client currently has an IP limit. When none does, lastActive has no reader -- planIPLimit only looks at clients with limit_ip > 0 -- so stamping it on every read and write would be a clock call per packet that nothing consumes.

Switching this on leaves already-established connections reporting their creation time until their next read, so the first scan afterwards may see them as idle. That errs towards not counting a connection rather than evicting a live one, and corrects itself on the following scan.

Types

type Box

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

func NewBox

func NewBox(options Options) (*Box, error)

func (*Box) Close

func (s *Box) Close() error

Close tears the box down through its scopeSet rather than an adapter.Scope, which is what keeps a panic in one component's cleanup from skipping the rest (see closeGuarded).

func (*Box) CloseIdleConnections added in v1.9.1

func (s *Box) CloseIdleConnections()

func (*Box) ConnTracker

func (s *Box) ConnTracker() *ConnTracker

func (*Box) CreatedAt added in v1.9.1

func (s *Box) CreatedAt() time.Time

func (*Box) Endpoint

func (s *Box) Endpoint() adapter.EndpointManager

func (*Box) Inbound

func (s *Box) Inbound() adapter.InboundManager

func (*Box) LogFactory added in v1.8.0

func (s *Box) LogFactory() log.Factory

func (*Box) Network

func (s *Box) Network() adapter.NetworkManager

func (*Box) Outbound

func (s *Box) Outbound() adapter.OutboundManager

func (*Box) PreStart

func (s *Box) PreStart() error

func (*Box) Router

func (s *Box) Router() adapter.Router

func (*Box) Service added in v1.8.2

func (s *Box) Service() adapter.ServiceManager

func (*Box) Start

func (s *Box) Start() error

func (*Box) StatsTracker

func (s *Box) StatsTracker() *StatsTracker

func (*Box) Uptime

func (s *Box) Uptime() uint32

type CheckOutboundResult

type CheckOutboundResult struct {
	OK    bool
	Delay uint16
	Error string
}

type ConnGate added in v1.7.0

type ConnGate func(user string, source netip.Addr) bool

ConnGate reports whether a freshly routed connection may proceed. The panel installs one to enforce per-client IP limits; the deny state behind it is policy that has to outlive a core restart, so it lives in the service layer and is reached through the package-level gate below rather than being copied into each tracker.

type ConnTracker

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

func NewConnTracker

func NewConnTracker() *ConnTracker

func (*ConnTracker) CloseConnByInbound

func (c *ConnTracker) CloseConnByInbound(inbound string) int

func (*ConnTracker) CloseConnByInboundUsers added in v1.6.0

func (c *ConnTracker) CloseConnByInboundUsers(inbound string, keepUsers map[string]struct{}) int

func (*ConnTracker) CloseConnByUser added in v1.9.0

func (c *ConnTracker) CloseConnByUser(user string) (closed int, inbounds map[string]struct{})

CloseConnByUser closes every routed connection of one user, and reports the inbounds they were on. That is all it can do: a multiplex or QUIC session keeps serving new streams after its routed connections are gone, which is what Core.DisconnectUser is for.

The inbounds come out of the same pass on purpose. They are the only sign of where the user is connected, and collecting them separately would walk every connection a second time under the lock each connection setup takes.

func (*ConnTracker) CloseConnByUserIPs added in v1.7.0

func (c *ConnTracker) CloseConnByUserIPs(drop map[string]map[netip.Addr]struct{}) int

CloseConnByUserIPs closes every tracked connection whose (user, source IP) pair appears in drop. Unlike CloseConnByInboundUsers this takes a drop set rather than a keep set: the caller has already decided exactly which IPs lose their slot, and inverting that would force it to enumerate everyone staying.

func (*ConnTracker) Generation added in v1.7.0

func (c *ConnTracker) Generation() uint64

Generation identifies this tracker instance. Box is rebuilt on every core Start, so a caller holding state derived from the previous tracker's clock can use this to notice that the basis changed and discard it.

func (*ConnTracker) Reset

func (c *ConnTracker) Reset()

func (*ConnTracker) RoutedConnection

func (c *ConnTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn

Closing the connection is the only way a tracker can refuse one: sing-box hands our return value straight to the outbound handler and has no reject path, so the outbound still dials once before the copy fails. Refusing at the inbound instead would mean editing the protocol copies in core/protocol/, which have to stay verbatim against upstream.

func (*ConnTracker) RoutedFlow added in v1.8.0

func (t *ConnTracker) RoutedFlow(ctx context.Context, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) tun.FlowTracker

RoutedFlow is sing-box 1.14's hook for tracking a TUN flow. The panel tracks connections, not flows -- nil opts this tracker out without affecting the connection tracking above.

func (*ConnTracker) RoutedPacketConnection

func (c *ConnTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn

func (*ConnTracker) Sessions added in v1.9.0

func (c *ConnTracker) Sessions(want func(info *ConnectionInfo) bool) []SessionInfo

Sessions snapshots the live connections want accepts (nil means all).

Only the pointer list is taken under the lock: formatting every address on a busy server takes milliseconds, and this mutex is the one every connection setup and teardown takes. The fields read afterwards are written once before the connection is tracked, and the counters are atomic.

func (*ConnTracker) UserIPs added in v1.7.0

func (c *ConnTracker) UserIPs(want func(user string) bool) (map[string]map[netip.Addr]IPWindow, int64)

UserIPs snapshots the live source IPs of every user want accepts, returning now in the same monotonic basis as the windows so a caller never mixes clocks. The maps are freshly built because the caller reads them on a cron goroutine, well after the tracker lock is gone.

want filters (nil means every user) because this runs under the mutex that every connection setup and teardown takes: the walk over c.connections is unavoidable, but building a nested map for each of hundreds of users when the caller wants one of them is allocation held against the data plane. Both callers know exactly which names they need.

type ConnectionInfo

type ConnectionInfo struct {
	ID         string
	Conn       net.Conn
	PacketConn network.PacketConn
	Inbound    string
	User       string
	Type       string // "tcp" or "udp"

	// Source is the normalized client address, invalid when the inbound routed
	// by domain rather than IP. CreatedAt and lastActive are nanoseconds since
	// the owning tracker's epoch: a monotonic basis, so an NTP step cannot
	// reorder who connected first.
	Source    netip.Addr
	CreatedAt int64

	// What the sessions list shows, captured once at routing time and never
	// written again, so a snapshot can read them without the tracker lock.
	// RawSource is the address as it arrived, port included: Source above is
	// the masked identity, and a masked v6 address is one no client ever used.
	RawSource   M.Socksaddr
	Destination M.Socksaddr
	Domain      string
	Outbound    string
	Rule        string
	// contains filtered or unexported fields
}

type Core

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

func NewCore

func NewCore() *Core

func (*Core) AddEndpoint

func (c *Core) AddEndpoint(config []byte) error

func (*Core) AddInbound

func (c *Core) AddInbound(config []byte) error

func (*Core) AddOutbound

func (c *Core) AddOutbound(config []byte) error

func (*Core) AddService

func (c *Core) AddService(config []byte) error

func (*Core) CheckOutbound added in v1.8.2

func (c *Core) CheckOutbound(tag string, link string) (result CheckOutboundResult)

CheckOutbound is a method rather than a package function taking a context: it needs the outbound manager of the box that is running right now, and the caller used to supply the context separately from a nil check on a package var, which is two reads of a state that changes on every config save.

func (*Core) DisconnectUser added in v1.9.0

func (c *Core) DisconnectUser(user string) (DisconnectResult, error)

DisconnectUser drops every live connection of a user who stays enabled: an operator action, so nothing stops them from connecting again.

It deliberately never rebuilds an inbound. That is the only way to end a QUIC session here (see core/usersession), and it would disconnect everyone else on the inbound too -- a price a removal pays, but not a button that is meant for looking at one client. UnclosableInbounds says where that limit was hit.

func (*Core) EndpointDependents added in v1.9.1

func (c *Core) EndpointDependents(tag string) []string

EndpointDependents names what depends on endpoint tag in the running core. An endpoint something depends on cannot be replaced in place: a selector resolved it at Start and would keep the closed instance (core/managers.go).

func (*Core) GetCtx

func (c *Core) GetCtx() context.Context

func (*Core) GetInstance

func (c *Core) GetInstance() *Box

func (*Core) HasEndpoint added in v1.9.1

func (c *Core) HasEndpoint(tag string) bool

HasEndpoint reports whether the running core holds endpoint tag.

func (*Core) HasOutbound added in v1.9.1

func (c *Core) HasOutbound(tag string) bool

HasOutbound reports whether the running core holds outbound tag -- in the outbound table itself, not an endpoint of that name.

func (*Core) IsRunning

func (c *Core) IsRunning() bool

func (*Core) OutboundDependents added in v1.9.1

func (c *Core) OutboundDependents(tag string) []string

OutboundDependents names what depends on outbound tag in the running core. An outbound something depends on cannot be replaced in place: a selector resolved it at Start and would keep the closed instance (core/managers.go).

func (*Core) RemoveEndpoint

func (c *Core) RemoveEndpoint(tag string) error

func (*Core) RemoveInbound

func (c *Core) RemoveInbound(tag string) error

func (*Core) RemoveOutbound

func (c *Core) RemoveOutbound(tag string) error

func (*Core) RemoveService

func (c *Core) RemoveService(tag string) error

func (*Core) RenameEndpoint added in v1.9.1

func (c *Core) RenameEndpoint(oldTag string, config []byte) error

RenameEndpoint is RenameInbound for an endpoint. One something depends on, or that route.final names, is refused like a removal.

func (*Core) RenameInbound added in v1.9.1

func (c *Core) RenameInbound(oldTag string, config []byte) error

RenameInbound replaces inbound oldTag with config, which names another tag. A rename that does not start leaves the old inbound running (see componentTable.rename); Remove then Add left none.

func (*Core) RenameService added in v1.9.1

func (c *Core) RenameService(oldTag string, config []byte) error

RenameService is RenameInbound for a service.

func (*Core) SetStateForTest added in v1.8.2

func (c *Core) SetStateForTest(isRunning bool, instance *Box)

SetStateForTest puts the core into a state Start and Stop only ever pass through, so a caller that reads the two fields separately can be tested against it.

Named for tests because nothing else may use it: Start and Stop write both fields under one lock precisely so this combination is never observable, and a caller reaching for it would be writing the bug back in.

func (*Core) Start

func (c *Core) Start(sbConfig []byte) error

func (*Core) Stop

func (c *Core) Stop() error

func (*Core) UpdateInboundUsers added in v1.6.0

func (c *Core) UpdateInboundUsers(config []byte) (bool, error)

func (*Core) ValidateEndpoint added in v1.9.1

func (c *Core) ValidateEndpoint(config []byte) error

ValidateEndpoint is ValidateOutbound for an endpoint.

func (*Core) ValidateOutbound added in v1.9.1

func (c *Core) ValidateOutbound(config []byte) error

ValidateOutbound vets config as far as can be done without touching the running core: it parses it, and checks that what it depends on exists and does not lead back to it. It is for an edit applied by a restart instead of in place, which nothing else vets before the commit -- and a cycle or a missing detour there would fail the whole core on the restart rather than just the save. What only shows at Start (a port already taken) still gets through.

It does not build the outbound. Building is not free of side effects: a wireguard endpoint creates its gVisor stack in its constructor and registers the cleanup for it only in Start, so one built here and dropped would leak the stack for the life of the process.

type Counter

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

type DisconnectResult added in v1.9.0

type DisconnectResult struct {
	// Connections counts the routed connections closed.
	Connections int `json:"connections"`
	// Sessions counts the multiplex / anytls sessions cut outright.
	Sessions int `json:"sessions"`
	// UnclosableInbounds names the inbounds where the user is likely still
	// connected by a session this layer cannot reach, in CompareUnclosable
	// order. Their routed connections are closed, but the client opens new
	// streams on the session it still has.
	UnclosableInbounds []UnclosableInbound `json:"unclosableInbounds,omitempty"`
}

DisconnectResult is what disconnecting one user managed to do. It is sent as DisconnectWire.

There is deliberately no count field. Masters from before the list read only "unclosable", so the wire form still carries one -- derived from the list, so the two cannot disagree. Reading an answer back has nowhere to put it, which is how a count-only answer from such a node is dropped (see service.nodeUnclosable).

func (*DisconnectResult) AddUnclosable added in v1.9.1

func (r *DisconnectResult) AddUnclosable(tag string, reason string)

AddUnclosable records one inbound left with a session that could not be cut.

func (DisconnectResult) MarshalJSON added in v1.9.1

func (r DisconnectResult) MarshalJSON() ([]byte, error)

func (DisconnectResult) Wire added in v1.9.1

Wire is r as it is sent. A type that carries a DisconnectResult next to fields of its own embeds this rather than r: r's MarshalJSON would be promoted and marshal r alone.

type DisconnectWire added in v1.9.1

type DisconnectWire struct {

	// Unclosable is len(UnclosableInbounds), for masters that predate the list:
	// they read only this count, and warn when it is not zero.
	Unclosable int `json:"unclosable"`
	// contains filtered or unexported fields
}

DisconnectWire is DisconnectResult as it is sent. Its JSON is

connections, sessions, unclosableInbounds  -- every field of DisconnectResult
unclosable                                 -- the count derived from the list

The first three come from the embedded copy, so a field added to DisconnectResult is sent with nothing to change here. They are fields of a DisconnectWire too (w.Connections), though godoc lists only the count.

type IPWindow added in v1.7.0

type IPWindow struct {
	FirstSeen int64
	LastSeen  int64
}

IPWindow is one source IP's liveness window for a user, expressed in the owning tracker's monotonic basis (see ConnTracker.epoch).

type Options

type Options struct {
	option.Options
	Context                    context.Context
	PlatformLogWriter          log.PlatformWriter
	NetworkNamespaceHolderArgs []string
}

type PlatformWriter

type PlatformWriter struct{}

func (PlatformWriter) DisableColors

func (p PlatformWriter) DisableColors() bool

func (PlatformWriter) WriteMessage

func (p PlatformWriter) WriteMessage(level log.Level, message string)

type SessionInfo added in v1.9.0

type SessionInfo struct {
	ID          string `json:"id"`
	Inbound     string `json:"inbound,omitempty"`
	User        string `json:"user,omitempty"`
	Outbound    string `json:"outbound,omitempty"`
	Network     string `json:"network"`
	Source      string `json:"source,omitempty"`
	Destination string `json:"destination,omitempty"`
	Domain      string `json:"domain,omitempty"`
	Rule        string `json:"rule,omitempty"`
	// CreatedAt is wall-clock unix seconds, for display only.
	CreatedAt int64 `json:"createdAt"`
	Upload    int64 `json:"up"`
	Download  int64 `json:"down"`
	// Node is set by a master merging the list a node returned; this package
	// never fills it.
	Node string `json:"node,omitempty"`
}

SessionInfo is one live routed connection as the API hands it out.

type StatsTracker

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

func NewStatsTracker

func NewStatsTracker() *StatsTracker

func (*StatsTracker) GetStats

func (c *StatsTracker) GetStats() *[]model.Stats

func (*StatsTracker) Reset

func (c *StatsTracker) Reset()

func (*StatsTracker) RoutedConnection

func (c *StatsTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn

func (*StatsTracker) RoutedFlow added in v1.8.0

func (c *StatsTracker) RoutedFlow(ctx context.Context, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) tun.FlowTracker

RoutedFlow is sing-box 1.14's hook for tracking a TUN flow. Counters here are per inbound/outbound tag, which a flow does not add to; see ConnTracker.

func (*StatsTracker) RoutedPacketConnection

func (c *StatsTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn

func (*StatsTracker) SampleUsers added in v1.9.3

func (c *StatsTracker) SampleUsers(now time.Time, minWindow time.Duration) (moved map[string]UserBytes, window time.Duration, ok bool)

SampleUsers reports what each user moved since the previous sample, and how long ago that was. It reads the counters without emptying them -- GetStats owns that, on its own schedule -- so a user's bytes since the last sample are its counter now, plus whatever GetStats drained in between, minus the counter as the last sample read it. Bytes added between the read here and a later drain are not lost: the drain books them, and the next sample counts them. Users that moved nothing are left out. The first sample measures from when the tracker was made or last Reset, when every counter was zero.

A window shorter than minWindow is not closed: ok is false, nothing moves, and its bytes roll into the next sample. Dividing a few milliseconds' bytes by a floored window would show a speed nobody had; dividing by the real one would show a burst nobody sent.

type UnclosableInbound added in v1.9.1

type UnclosableInbound struct {
	Tag    string `json:"tag"`
	Reason string `json:"reason"`
	// Node is set by a master merging the answer a node returned; this package
	// never fills it.
	Node string `json:"node,omitempty"`
}

UnclosableInbound is one inbound where a kicked user may still hold a session.

type UserBytes added in v1.9.3

type UserBytes struct {
	Up   int64
	Down int64
}

UserBytes is one user's traffic in each direction, named from the client's side as the stats rows are: Up is what it sent, Down what it received.

Directories

Path Synopsis
protocol
anytls
Verbatim copy of sing-box protocol/anytls/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/anytls/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
hysteria
Verbatim copy of sing-box protocol/hysteria/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/hysteria/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
hysteria2
Verbatim copy of sing-box protocol/hysteria2/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/hysteria2/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
trojan
Verbatim copy of sing-box protocol/trojan/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/trojan/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
tuic
Verbatim copy of sing-box protocol/tuic/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/tuic/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
vless
Verbatim copy of sing-box protocol/vless/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/vless/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
vmess
Verbatim copy of sing-box protocol/vmess/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Verbatim copy of sing-box protocol/vmess/inbound.go, moved into this module so the panel can reach the unexported `service`/`users` fields that the sing-box Inbound type does not expose.
Package quicgrace makes closing a QUIC inbound tell its clients so.
Package quicgrace makes closing a QUIC inbound tell its clients so.
Package usersession tracks the client sessions of an inbound, so that the sessions of a user who was just removed can actually be cut.
Package usersession tracks the client sessions of an inbound, so that the sessions of a user who was just removed can actually be cut.

Jump to

Keyboard shortcuts

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