engine

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultUDPGlobalMaxSessions caps the total number of active UDP sessions
	// across all rules owned by one Manager. A zero ManagerOptions value uses
	// this limit rather than disabling the guard.
	DefaultUDPGlobalMaxSessions = 256

	// MaxUDPGlobalMaxSessions bounds configuration mistakes. A generic UDP
	// proxy consumes a socket and receive loop per active client address, so a
	// larger value is not a practical safe default for this implementation.
	MaxUDPGlobalMaxSessions = 4_096
)
View Source
const DefaultTCPIdleTimeout = 5 * time.Minute

DefaultTCPIdleTimeout bounds how long a TCP forwarding connection may stay idle (no data in either direction) before being reaped. It keeps Stop/reload from hanging on stuck or silent clients and caps per-connection resource hold time. Overridable per rule via idle_timeout (seconds); 0 means use this default.

View Source
const (
	// DefaultUDPRuleMaxSessions is the per-rule fallback when max_conn is zero.
	// Each UDP session owns a socket and receive goroutine, so zero cannot mean
	// unbounded without exposing the process to trivial resource exhaustion.
	DefaultUDPRuleMaxSessions = DefaultUDPGlobalMaxSessions
)

Variables

View Source
var (
	ErrTrafficQuotaExceeded = errors.New("traffic quota exceeded")
	ErrQuotaStatePersist    = errors.New("persist traffic quota state")
)

Functions

func ParseSourceIPPrefix added in v0.3.0

func ParseSourceIPPrefix(value string) (netip.Prefix, error)

ParseSourceIPPrefix parses one literal source IP or CIDR. Literal addresses are represented as /32 or /128 prefixes, and IPv4-mapped IPv6 values are normalized to IPv4 so socket-family representation cannot bypass a policy.

Types

type ApplyAction

type ApplyAction string
const (
	ApplyActionStarted   ApplyAction = "started"
	ApplyActionRestarted ApplyAction = "restarted"
	ApplyActionStopped   ApplyAction = "stopped"
	ApplyActionRemoved   ApplyAction = "removed"
	ApplyActionUnchanged ApplyAction = "unchanged"
	ApplyActionFailed    ApplyAction = "failed"
)

type ApplyFailure added in v0.3.0

type ApplyFailure struct {
	RuleID   string `json:"rule_id,omitempty"`
	Revision int64  `json:"revision,omitempty"`
	Error    string `json:"error"`
}

ApplyFailure identifies the operation that prevented a transactional snapshot from being committed. Validation failures are also listed in Apply.Items; this field points at the first failure that stopped the batch.

type ApplyItemResult

type ApplyItemResult struct {
	RuleID   string      `json:"rule_id"`
	Revision int64       `json:"revision,omitempty"`
	Action   ApplyAction `json:"action"`
	Status   string      `json:"status"`
	Error    string      `json:"error,omitempty"`
}

type ApplyResult

type ApplyResult struct {
	AppliedRules int               `json:"applied_rules"`
	StoppedRules int               `json:"stopped_rules"`
	FailedRules  int               `json:"failed_rules"`
	TotalRules   int               `json:"total_rules"`
	Items        []ApplyItemResult `json:"items"`
}

type ApplySnapshotOptions

type ApplySnapshotOptions struct {
	ReplaceAll bool `json:"replace_all"`
}

type BandwidthLimit added in v0.3.0

type BandwidthLimit struct {
	Rate     ByteRate `json:"rate,omitempty" yaml:"rate,omitempty"`
	Upload   ByteRate `json:"upload,omitempty" yaml:"upload,omitempty"`
	Download ByteRate `json:"download,omitempty" yaml:"download,omitempty"`
}

BandwidthLimit caps aggregate traffic for an entire rule. Rate applies the same full-duplex limit to upload and download; Upload and Download provide asymmetric limits and cannot be combined with Rate.

func (BandwidthLimit) DownloadBytesPerSecond added in v0.3.0

func (limit BandwidthLimit) DownloadBytesPerSecond() int64

func (BandwidthLimit) UploadBytesPerSecond added in v0.3.0

func (limit BandwidthLimit) UploadBytesPerSecond() int64

type ByteRate added in v0.3.0

type ByteRate int64

ByteRate is a normalized byte-per-second value. Configuration accepts common network units such as "100 Mbps" and byte-rate units such as "10 MiB/s".

func (ByteRate) MarshalText added in v0.3.0

func (value ByteRate) MarshalText() ([]byte, error)

func (ByteRate) String added in v0.3.0

func (value ByteRate) String() string

func (*ByteRate) UnmarshalJSON added in v0.3.0

func (value *ByteRate) UnmarshalJSON(data []byte) error

func (*ByteRate) UnmarshalText added in v0.3.0

func (value *ByteRate) UnmarshalText(text []byte) error

type ByteSize added in v0.3.0

type ByteSize int64

ByteSize is a normalized byte count. Configuration accepts decimal provider units (GB/TB) and IEC units (GiB/TiB).

func (ByteSize) MarshalText added in v0.3.0

func (value ByteSize) MarshalText() ([]byte, error)

func (ByteSize) String added in v0.3.0

func (value ByteSize) String() string

func (*ByteSize) UnmarshalJSON added in v0.3.0

func (value *ByteSize) UnmarshalJSON(data []byte) error

func (*ByteSize) UnmarshalText added in v0.3.0

func (value *ByteSize) UnmarshalText(text []byte) error

type CertProvider

type CertProvider interface {
	GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
	Obtain(ctx context.Context, domains []string) error
}

type Collector

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

func NewCollector

func NewCollector() *Collector

func (*Collector) AddDownload

func (collector *Collector) AddDownload(ruleID string, n int64)

func (*Collector) AddQuotaRejectedBytes added in v0.3.0

func (collector *Collector) AddQuotaRejectedBytes(ruleID string, n int64)

func (*Collector) AddUpload

func (collector *Collector) AddUpload(ruleID string, n int64)

func (*Collector) BandwidthPolicies added in v0.3.0

func (collector *Collector) BandwidthPolicies() map[string]BandwidthLimit

BandwidthPolicies returns isolated rule-level limits for metrics and other read-only observers. Map membership distinguishes an unlimited direction from a rule with no aggregate bandwidth policy.

func (*Collector) DecConns

func (collector *Collector) DecConns(ruleID string)

func (*Collector) EnsureRule

func (collector *Collector) EnsureRule(ruleID string)

func (*Collector) EnsureRuleProtocol added in v0.3.0

func (collector *Collector) EnsureRuleProtocol(ruleID string, protocol Protocol)

func (*Collector) IncConns

func (collector *Collector) IncConns(ruleID string)

func (*Collector) IncSourceIPDenied added in v0.3.0

func (collector *Collector) IncSourceIPDenied(ruleID string)

func (*Collector) IncUDPPacketsDropped added in v0.3.0

func (collector *Collector) IncUDPPacketsDropped(ruleID string)

func (*Collector) IncUDPSessionRejected added in v0.3.0

func (collector *Collector) IncUDPSessionRejected(ruleID string)

func (*Collector) QuotaPolicy added in v0.3.0

func (collector *Collector) QuotaPolicy(ruleID string) *TrafficQuota

func (*Collector) RemoveRule

func (collector *Collector) RemoveRule(ruleID string)

RemoveRule discards a rule's counters and protocol metadata. Forwarding for the rule must be stopped first; Manager.RemoveRule enforces that ordering.

func (*Collector) Restore added in v0.3.0

func (collector *Collector) Restore(snapshots []TrafficSnapshot)

Restore seeds cumulative counters from persisted snapshots. Call before any forwarding starts. Conns (live connection count) is intentionally not restored: a freshly started daemon has zero connections, and restoring the old value would show a bogus active-connection count.

func (*Collector) RuleProtocols added in v0.3.0

func (collector *Collector) RuleProtocols() map[string]Protocol

func (*Collector) SetBandwidthPolicy added in v0.3.0

func (collector *Collector) SetBandwidthPolicy(ruleID string, limit *BandwidthLimit)

func (*Collector) SetConns

func (collector *Collector) SetConns(ruleID string, value int64)

func (*Collector) SetQuotaPolicy added in v0.3.0

func (collector *Collector) SetQuotaPolicy(ruleID string, quota *TrafficQuota)

func (*Collector) Snapshot

func (collector *Collector) Snapshot(ruleID string) TrafficSnapshot

func (*Collector) SnapshotAll

func (collector *Collector) SnapshotAll() []TrafficSnapshot

type Manager

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

func NewManager

func NewManager(collector *Collector) *Manager

func NewManagerWithCert

func NewManagerWithCert(collector *Collector, certMgr CertProvider) *Manager

func NewManagerWithCertOptions added in v0.3.0

func NewManagerWithCertOptions(collector *Collector, certMgr CertProvider, opts ManagerOptions) *Manager

NewManagerWithCertOptions creates a manager with a certificate provider and explicit manager-wide resource limits.

func NewManagerWithOptions added in v0.3.0

func NewManagerWithOptions(collector *Collector, opts ManagerOptions) *Manager

NewManagerWithOptions creates a manager with explicit manager-wide resource limits. Zero-valued limits use safe defaults.

func (*Manager) ApplySnapshot

func (manager *Manager) ApplySnapshot(rules []Rule, opts ApplySnapshotOptions) ApplyResult

func (*Manager) ApplySnapshotTransactional added in v0.3.0

func (manager *Manager) ApplySnapshotTransactional(rules []Rule, opts ApplySnapshotOptions) TransactionalApplyResult

ApplySnapshotTransactional applies a complete desired snapshot as one operation. Every rule is validated before runtime state changes. If a later operation fails, prior operations are undone in reverse order and collector state is restored to its pre-apply snapshot on a best-effort basis.

func (*Manager) BandwidthPolicies added in v0.3.0

func (manager *Manager) BandwidthPolicies() map[string]BandwidthLimit

BandwidthPolicies reports configured aggregate limits for retained rules.

func (*Manager) BeginApplySnapshotTransactional added in v0.3.0

func (manager *Manager) BeginApplySnapshotTransactional(rules []Rule, opts ApplySnapshotOptions) (*SnapshotApplyTransaction, TransactionalApplyResult)

BeginApplySnapshotTransactional applies a desired snapshot while retaining an undo journal. A non-nil transaction means the apply succeeded and the caller must call Commit or Rollback. Failed applies are rolled back before this method returns and produce a nil transaction.

func (*Manager) RemoveRule

func (manager *Manager) RemoveRule(ruleID string)

func (*Manager) RestartRule

func (manager *Manager) RestartRule(rule Rule) error

func (*Manager) RuleProtocols added in v0.3.0

func (manager *Manager) RuleProtocols() map[string]Protocol

RuleProtocols returns protocol metadata for running, stopped, and disabled rules whose counters are still retained by this manager.

func (*Manager) RunningCount

func (manager *Manager) RunningCount() int

func (*Manager) RunningRules

func (manager *Manager) RunningRules() []Rule

func (*Manager) SaveQuotaStateExact added in v0.3.0

func (manager *Manager) SaveQuotaStateExact() error

SaveQuotaStateExact persists actual quota usage after forwarding has stopped.

func (*Manager) SetUDPMaxSessions added in v0.3.0

func (manager *Manager) SetUDPMaxSessions(limit int)

SetUDPMaxSessions updates admission for future UDP sessions. Existing sessions are not terminated when the limit is lowered; new sessions remain blocked until usage falls below the new limit.

func (*Manager) Snapshot

func (manager *Manager) Snapshot(ruleID string) TrafficSnapshot

func (*Manager) SnapshotAll

func (manager *Manager) SnapshotAll() []TrafficSnapshot

func (*Manager) StartRule

func (manager *Manager) StartRule(rule Rule) error

func (*Manager) StopAll

func (manager *Manager) StopAll()

func (*Manager) StopRule

func (manager *Manager) StopRule(ruleID string)

func (*Manager) UDPMaxSessions added in v0.3.0

func (manager *Manager) UDPMaxSessions() (limit, active int)

UDPMaxSessions reports the configured global limit and current usage.

type ManagerOptions added in v0.3.0

type ManagerOptions struct {
	// UDPMaxSessions uses DefaultUDPGlobalMaxSessions when non-positive and is
	// clamped to MaxUDPGlobalMaxSessions when larger than the supported bound.
	UDPMaxSessions int

	// QuotaLedger supplies calendar-period accounting and optional strict
	// persistence. Nil uses an in-memory ledger.
	QuotaLedger *QuotaLedger

	// Resolver controls outbound target name resolution. Nil uses vmflow's
	// automatic system-first failover policy.
	Resolver *dnsresolver.Resolver
}

ManagerOptions controls manager-wide forwarding resource limits.

type Protocol

type Protocol string
const (
	ProtocolTCP    Protocol = "tcp"
	ProtocolUDP    Protocol = "udp"
	ProtocolTCPUDP Protocol = "tcp+udp"
	ProtocolHTTP   Protocol = "http"
	ProtocolHTTPS  Protocol = "https"
)

type QuotaLedger added in v0.3.0

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

func NewQuotaLedger added in v0.3.0

func NewQuotaLedger(store QuotaStateStore) (*QuotaLedger, error)

func (*QuotaLedger) SaveExact added in v0.3.0

func (ledger *QuotaLedger) SaveExact() error

SaveExact must be called only after all forwarding runners have stopped. It replaces conservative durable credits with actual successful byte counts.

type QuotaPeriodSnapshot added in v0.3.0

type QuotaPeriodSnapshot struct {
	Period         string `json:"period"`
	UsedBytes      int64  `json:"used_bytes"`
	LimitBytes     int64  `json:"limit_bytes"`
	RemainingBytes int64  `json:"remaining_bytes"`
	ResetTime      int64  `json:"reset_time"`
	Exhausted      bool   `json:"exhausted"`
}

type QuotaPersistentState added in v0.3.0

type QuotaPersistentState struct {
	RuleID  string           `json:"rule_id"`
	Daily   map[string]int64 `json:"daily,omitempty"`
	Monthly map[string]int64 `json:"monthly,omitempty"`
}

QuotaPersistentState is the durable high-water mark for one rule. Period maps retain prior keys so a clock rollback cannot recreate an empty period.

type QuotaStateStore added in v0.3.0

type QuotaStateStore interface {
	LoadQuotaState() ([]QuotaPersistentState, error)
	SaveQuotaState([]QuotaPersistentState) error
}

QuotaStateStore provides strict persistence for enforced traffic quotas.

type RollbackItemResult added in v0.3.0

type RollbackItemResult struct {
	RuleID string      `json:"rule_id"`
	Action ApplyAction `json:"action"`
	Status string      `json:"status"`
	Error  string      `json:"error,omitempty"`
}

RollbackItemResult reports the outcome of reverting one successfully applied rule operation. Action is the original operation being reverted.

type RollbackResult added in v0.3.0

type RollbackResult struct {
	Attempted bool                 `json:"attempted"`
	Failed    bool                 `json:"failed"`
	Items     []RollbackItemResult `json:"items,omitempty"`
}

type Rule

type Rule struct {
	RuleID       string          `json:"rule_id" yaml:"rule_id"`
	Name         string          `json:"name" yaml:"name"`
	Protocol     Protocol        `json:"protocol" yaml:"protocol"`
	ListenAddr   string          `json:"listen_addr" yaml:"listen_addr"`
	ListenPort   int             `json:"listen_port" yaml:"listen_port"`
	TargetAddr   string          `json:"target_addr" yaml:"target_addr"`
	TargetPort   int             `json:"target_port" yaml:"target_port"`
	Enabled      bool            `json:"enabled" yaml:"enabled"`
	SpeedLimit   int64           `json:"speed_limit" yaml:"speed_limit"`
	Bandwidth    *BandwidthLimit `json:"bandwidth_limit,omitempty" yaml:"bandwidth_limit,omitempty"`
	TrafficQuota *TrafficQuota   `json:"traffic_quota,omitempty" yaml:"traffic_quota,omitempty"`
	MaxConn      int             `json:"max_conn" yaml:"max_conn"`
	IdleTimeout  int             `json:"idle_timeout,omitempty" yaml:"idle_timeout,omitempty"`
	SourceIPMode SourceIPMode    `json:"source_ip_mode,omitempty" yaml:"source_ip_mode,omitempty"`
	SourceIPs    []string        `json:"source_ips,omitempty" yaml:"source_ips,omitempty"`
	Domains      []string        `json:"domains,omitempty" yaml:"domains,omitempty"`
	Remark       string          `json:"remark,omitempty" yaml:"remark,omitempty"`
	Revision     int64           `json:"revision,omitempty" yaml:"revision,omitempty"`
	CreatedTime  int64           `json:"created_time,omitempty" yaml:"created_time,omitempty"`
	UpdatedTime  int64           `json:"updated_time,omitempty" yaml:"updated_time,omitempty"`
}

func (Rule) RuntimeEqual

func (rule Rule) RuntimeEqual(other Rule) bool

func (Rule) Standardize

func (rule Rule) Standardize() Rule

func (Rule) Validate

func (rule Rule) Validate() error

type Runner

type Runner interface {
	Start() error
	Stop()
}

type SnapshotApplyTransaction added in v0.3.0

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

SnapshotApplyTransaction keeps a successful runtime apply reversible until its caller commits the associated external state (for example a config file rename). It owns Manager.applyMu until Commit or Rollback is called.

func (*SnapshotApplyTransaction) Commit added in v0.3.0

func (transaction *SnapshotApplyTransaction) Commit()

Commit makes the applied runtime snapshot final and releases the manager.

func (*SnapshotApplyTransaction) Rollback added in v0.3.0

func (transaction *SnapshotApplyTransaction) Rollback() RollbackResult

Rollback restores the runtime state captured before BeginApplySnapshotTransactional. It is idempotent; calling it after Commit returns an unattempted result.

type SourceIPMode added in v0.3.0

type SourceIPMode string

SourceIPMode controls how a rule interprets its SourceIPs entries.

const (
	SourceIPModeOff       SourceIPMode = "off"
	SourceIPModeAllowlist SourceIPMode = "allowlist"
	SourceIPModeDenylist  SourceIPMode = "denylist"

	// MaxSourceIPsPerRule bounds the work performed for every new connection or
	// UDP datagram. Exact addresses use a map; CIDR prefixes are scanned.
	MaxSourceIPsPerRule = 256
)

type TrafficQuota added in v0.3.0

type TrafficQuota struct {
	Daily    ByteSize `json:"daily,omitempty" yaml:"daily,omitempty"`
	Monthly  ByteSize `json:"monthly,omitempty" yaml:"monthly,omitempty"`
	Timezone string   `json:"timezone,omitempty" yaml:"timezone,omitempty"`
	Action   string   `json:"action,omitempty" yaml:"action,omitempty"`
}

TrafficQuota limits the combined successful upload and download payload for calendar-day and calendar-month periods in Timezone.

type TrafficQuotaSnapshot added in v0.3.0

type TrafficQuotaSnapshot struct {
	Daily   *QuotaPeriodSnapshot `json:"daily,omitempty"`
	Monthly *QuotaPeriodSnapshot `json:"monthly,omitempty"`
	Blocked bool                 `json:"blocked"`
}

TrafficQuotaSnapshot describes the active calendar-period budgets for a rule.

type TrafficSnapshot

type TrafficSnapshot struct {
	RuleID             string                `json:"rule_id"`
	UploadBytes        int64                 `json:"upload_bytes"`
	DownloadBytes      int64                 `json:"download_bytes"`
	Conns              int64                 `json:"conns"`
	SourceIPDenied     int64                 `json:"source_ip_denied_total,omitempty"`
	UDPSessionRejected int64                 `json:"udp_session_rejected_total,omitempty"`
	UDPPacketsDropped  int64                 `json:"udp_packets_dropped_total,omitempty"`
	QuotaRejectedBytes int64                 `json:"quota_rejected_bytes_total,omitempty"`
	Quota              *TrafficQuotaSnapshot `json:"quota,omitempty"`
	UpdatedTime        int64                 `json:"updated_time"`
}

type TransactionalApplyResult added in v0.3.0

type TransactionalApplyResult struct {
	Apply        ApplyResult    `json:"apply"`
	ApplyFailure *ApplyFailure  `json:"apply_failure,omitempty"`
	Rollback     RollbackResult `json:"rollback"`
}

TransactionalApplyResult separates the error that stopped the desired snapshot from any error encountered while restoring the previous snapshot.

Jump to

Keyboard shortcuts

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