Documentation
¶
Overview ¶
Package xray provides integration with the Xray proxy core. It includes API client functionality, configuration management, traffic monitoring, and process control for Xray instances.
Index ¶
- func BuildSessionIPBlockRouterConfig(ruleTag, email, cidr string) (*routerpb.Config, error)
- func EnsureAPIRoutingOutbound(cfg *Config)
- func EnsureAPIServicesRoutingService(cfg *Config)
- func EnsurePolicyStatsUserOnline(cfg *Config)
- func GetAccessLogPath() (string, error)
- func GetAccessPersistentLogPath() string
- func GetAccessPersistentPrevLogPath() string
- func GetBinaryName() string
- func GetBinaryPath() string
- func GetConfigPath() string
- func GetErrorLogPath() (string, error)
- func GetGeoipPath() string
- func GetGeositePath() string
- func GetIPLimitBannedLogPath() string
- func GetIPLimitBannedPrevLogPath() string
- func GetIPLimitLogPath() string
- func LeafCertSHA256FromFile(path string) (string, error)
- func LeafCertSHA256FromPEM(pemData string) (string, error)
- func LeafCertSHA256Hex(cert *x509.Certificate) string
- func NormalizeSubscriptionStreamSettings(stream map[string]any) map[string]any
- func PinnedPeerCertSha256FromTLS(tls map[string]any) string
- func SanitizeClientTLSSettings(tls map[string]any) map[string]any
- func SessionIPBlockAddRuleTypedMessage(ruleTag, email, cidr string) (*serial.TypedMessage, error)
- func SessionIPBlockRuleTag(clientId int, normalizedIP string) string
- func UpdateConfigFileAfterUserAddition(processConfig *Config, inboundTag string, user map[string]interface{}) error
- func UpdateConfigFileAfterUserRemoval(processConfig *Config, inboundTag, email string) error
- func ValidateInboundConfigJSON(inbound []byte) error
- func WriteConfigFile(xrayConfig *Config) (string, error)
- type ClientTraffic
- type Config
- type InboundConfig
- type LogWriter
- type OnlineIPSession
- type Process
- func (p *Process) GetAPIPort() int
- func (p *Process) GetConfig() *Config
- func (p Process) GetErr() error
- func (p *Process) GetOnlineClients() []string
- func (p Process) GetResult() string
- func (p *Process) GetUptime() uint64
- func (p Process) GetVersion() string
- func (p Process) IsRunning() bool
- func (p *Process) SetOnlineClients(users []string)
- func (p Process) Start() (err error)
- func (p Process) Stop() error
- type Traffic
- type XrayAPI
- func (x *XrayAPI) AddInbound(inbound []byte) error
- func (x *XrayAPI) AddSessionIPBlockRule(ctx context.Context, ruleTag, email, cidr string) error
- func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error
- func (x *XrayAPI) Close()
- func (x *XrayAPI) DelInbound(tag string) error
- func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error)
- func (x *XrayAPI) GetUserOnlineIPList(ctx context.Context, email string, reset bool) ([]OnlineIPSession, error)
- func (x *XrayAPI) Init(apiPort int) error
- func (x *XrayAPI) IsConnected() bool
- func (x *XrayAPI) RemoveSessionIPBlockRule(ctx context.Context, ruleTag string) error
- func (x *XrayAPI) RemoveUser(inboundTag, email string) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildSessionIPBlockRouterConfig ¶
BuildSessionIPBlockRouterConfig builds router.Config for RoutingService.AddRule (one session-IP block). Uses infra/conf ToCidrList so GeoIP/CIDR encoding matches JSON routing rules in the panel config.
func EnsureAPIRoutingOutbound ¶
func EnsureAPIRoutingOutbound(cfg *Config)
EnsureAPIRoutingOutbound appends a minimal freedom outbound tagged "api" when routing references it (inboundTag api -> outboundTag api) but no outbound with tag "api" exists — avoids "non existing outTag: api" from the dispatcher.
func EnsureAPIServicesRoutingService ¶
func EnsureAPIServicesRoutingService(cfg *Config)
EnsureAPIServicesRoutingService appends "RoutingService" to config.api.services when missing, so RoutingService.AddRule / RemoveRule work without a full template migration.
func EnsurePolicyStatsUserOnline ¶
func EnsurePolicyStatsUserOnline(cfg *Config)
EnsurePolicyStatsUserOnline forces statsUserUplink, statsUserDownlink, and statsUserOnline on every policy level so Xray records per-user traffic and online (user>>>email>>>...).
func GetAccessLogPath ¶
GetAccessLogPath reads the Xray config and returns the access log file path. Returns an error if the config file doesn't exist (e.g., in multi-node mode).
func GetAccessPersistentLogPath ¶
func GetAccessPersistentLogPath() string
GetAccessPersistentLogPath returns the path to the persistent access log file.
func GetAccessPersistentPrevLogPath ¶
func GetAccessPersistentPrevLogPath() string
GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
func GetBinaryName ¶
func GetBinaryName() string
GetBinaryName returns the Xray binary filename for the current OS and architecture.
func GetBinaryPath ¶
func GetBinaryPath() string
GetBinaryPath returns the full path to the Xray binary executable.
func GetConfigPath ¶
func GetConfigPath() string
GetConfigPath returns the path to the Xray configuration file in the binary folder.
func GetErrorLogPath ¶
GetErrorLogPath reads the Xray config and returns the error log file path. Returns an error if the config file doesn't exist (e.g., in multi-node mode).
func GetGeoipPath ¶
func GetGeoipPath() string
GetGeoipPath returns the path to the geoip data file used by Xray.
func GetGeositePath ¶
func GetGeositePath() string
GetGeositePath returns the path to the geosite data file used by Xray.
func GetIPLimitBannedLogPath ¶
func GetIPLimitBannedLogPath() string
GetIPLimitBannedLogPath returns the path to the banned IP log file.
func GetIPLimitBannedPrevLogPath ¶
func GetIPLimitBannedPrevLogPath() string
GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
func GetIPLimitLogPath ¶
func GetIPLimitLogPath() string
GetIPLimitLogPath returns the path to the IP limit log file.
func LeafCertSHA256FromFile ¶
LeafCertSHA256FromFile reads a PEM/DER certificate file and returns its pin.
func LeafCertSHA256FromPEM ¶
LeafCertSHA256FromPEM parses PEM and returns the pin for the first certificate block.
func LeafCertSHA256Hex ¶
func LeafCertSHA256Hex(cert *x509.Certificate) string
LeafCertSHA256Hex returns the SHA-256 fingerprint of the first PEM certificate block (Xray pinnedPeerCertSha256 format: lowercase hex, no colons).
func NormalizeSubscriptionStreamSettings ¶
NormalizeSubscriptionStreamSettings sanitizes inbound streamSettings for client subscriptions. Legacy panel / Xray 2026+ configs may store pinnedPeerCertSha256 as a JSON array; INCY and older Xray clients expect a comma-separated string in tlsSettings.
func PinnedPeerCertSha256FromTLS ¶
PinnedPeerCertSha256FromTLS extracts a comma-separated pin list from tlsSettings (any supported key).
func SanitizeClientTLSSettings ¶
SanitizeClientTLSSettings prepares tlsSettings for Xray client outbounds / streamSettings. Removes deprecated allowInsecure, normalizes pin field name, lifts fingerprint from legacy nested settings.
func SessionIPBlockAddRuleTypedMessage ¶
func SessionIPBlockAddRuleTypedMessage(ruleTag, email, cidr string) (*serial.TypedMessage, error)
SessionIPBlockAddRuleTypedMessage serializes router.Config for RoutingService.AddRule.
func SessionIPBlockRuleTag ¶
SessionIPBlockRuleTag returns a stable Xray routing ruleTag for panel session-IP blocks (hot API + file merge).
func UpdateConfigFileAfterUserAddition ¶
func UpdateConfigFileAfterUserAddition(processConfig *Config, inboundTag string, user map[string]interface{}) error
UpdateConfigFileAfterUserAddition updates the Xray config file after adding a user via API. This ensures the config file stays in sync with the running Xray instance. processConfig should be the current config from the Xray process (via process.GetConfig()).
func UpdateConfigFileAfterUserRemoval ¶
UpdateConfigFileAfterUserRemoval updates the Xray config file after removing a user via API. This ensures the config file stays in sync with the running Xray instance. processConfig should be the current config from the Xray process (via process.GetConfig()).
func ValidateInboundConfigJSON ¶
ValidateInboundConfigJSON checks that inbound JSON can be parsed and built for HandlerService.AddInbound.
func WriteConfigFile ¶
WriteConfigFile writes the Xray configuration to a file. This is used both for starting Xray and for pre-generating config at startup. It returns the path to the written config file.
Types ¶
type ClientTraffic ¶
type ClientTraffic struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
InboundId int `json:"inboundId" form:"inboundId"`
Enable bool `json:"enable" form:"enable"`
Email string `json:"email" form:"email" gorm:"unique"`
UUID string `json:"uuid" form:"uuid" gorm:"-"`
SubId string `json:"subId" form:"subId" gorm:"-"`
Up int64 `json:"up" form:"up"`
Down int64 `json:"down" form:"down"`
AllTime int64 `json:"allTime" form:"allTime"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`
Total int64 `json:"total" form:"total"`
Reset int `json:"reset" form:"reset" gorm:"default:0"`
LastOnline int64 `json:"lastOnline" form:"lastOnline" gorm:"default:0"`
}
ClientTraffic represents traffic statistics and limits for a specific client. It tracks upload/download usage, expiry times, and online status for inbound clients.
type Config ¶
type Config struct {
LogConfig json_util.RawMessage `json:"log"`
RouterConfig json_util.RawMessage `json:"routing"`
DNSConfig json_util.RawMessage `json:"dns"`
InboundConfigs []InboundConfig `json:"inbounds"`
OutboundConfigs json_util.RawMessage `json:"outbounds"`
Transport json_util.RawMessage `json:"transport"`
Policy json_util.RawMessage `json:"policy"`
API json_util.RawMessage `json:"api"`
Stats json_util.RawMessage `json:"stats"`
Reverse json_util.RawMessage `json:"reverse"`
FakeDNS json_util.RawMessage `json:"fakedns"`
Observatory json_util.RawMessage `json:"observatory"`
BurstObservatory json_util.RawMessage `json:"burstObservatory"`
Metrics json_util.RawMessage `json:"metrics"`
}
Config represents the complete Xray configuration structure. It contains all sections of an Xray config file including inbounds, outbounds, routing, etc.
func (*Config) EqualCanonical ¶
EqualCanonical reports whether two configs are equivalent after canonical JSON normalization. Falls back to Equals when canonicalization fails.
type InboundConfig ¶
type InboundConfig struct {
Listen json_util.RawMessage `json:"listen"` // listen cannot be an empty string
Port int `json:"port"`
Protocol string `json:"protocol"`
Settings json_util.RawMessage `json:"settings"`
StreamSettings json_util.RawMessage `json:"streamSettings"`
Tag string `json:"tag"`
Sniffing json_util.RawMessage `json:"sniffing"`
AcceptProxyProtocol bool `json:"acceptProxyProtocol,omitempty"`
}
InboundConfig represents an Xray inbound configuration. It defines how Xray accepts incoming connections including protocol, port, and settings.
func (*InboundConfig) Equals ¶
func (c *InboundConfig) Equals(other *InboundConfig) bool
Equals compares two InboundConfig instances for deep equality.
type LogWriter ¶
type LogWriter struct {
// contains filtered or unexported fields
}
LogWriter processes and filters log output from the Xray process, handling crash detection and message filtering.
func NewLogWriter ¶
func NewLogWriter() *LogWriter
NewLogWriter returns a new LogWriter for processing Xray log output.
type OnlineIPSession ¶
type OnlineIPSession struct {
IP string `json:"ip"`
LastSeen int64 `json:"lastSeen"` // Unix seconds (from Xray online map); Telemt may use collector time
// Protocol is "mtproto" for Telemt-sourced rows; empty for Xray.
Protocol string `json:"protocol,omitempty"`
// Remark is Telemt inbound tag when Protocol is mtproto (optional).
Remark string `json:"remark,omitempty"`
}
OnlineIPSession is one client IP tracked by Xray policy statsUserOnline (user>>>email>>>online), or an analogous row from Telemt (MTProto) Control API.
type Process ¶
type Process struct {
// contains filtered or unexported fields
}
Process wraps an Xray process instance and provides management methods.
func NewProcess ¶
NewProcess creates a new Xray process and sets up cleanup on garbage collection.
func (*Process) GetAPIPort ¶
GetAPIPort returns the API port used by the Xray process.
func (Process) GetErr ¶
func (p Process) GetErr() error
GetErr returns the last error encountered by the Xray process.
func (*Process) GetOnlineClients ¶
GetOnlineClients returns the list of online clients for the Xray process.
func (Process) GetResult ¶
func (p Process) GetResult() string
GetResult returns the last log line or error from the Xray process.
func (Process) GetVersion ¶
func (p Process) GetVersion() string
GetVersion returns the version string of the Xray process.
func (Process) IsRunning ¶
func (p Process) IsRunning() bool
IsRunning returns true if the Xray process is currently running.
func (*Process) SetOnlineClients ¶
SetOnlineClients sets the list of online clients for the Xray process.
type Traffic ¶
Traffic represents network traffic statistics for Xray connections. It tracks upload and download bytes for inbound or outbound traffic.
type XrayAPI ¶
type XrayAPI struct {
HandlerServiceClient *command.HandlerServiceClient
StatsServiceClient *statsService.StatsServiceClient
RoutingServiceClient routercmd.RoutingServiceClient
// contains filtered or unexported fields
}
XrayAPI is a gRPC client for managing Xray core configuration, inbounds, outbounds, and statistics.
func (*XrayAPI) AddInbound ¶
AddInbound adds a new inbound configuration to the Xray core via gRPC.
func (*XrayAPI) AddSessionIPBlockRule ¶
AddSessionIPBlockRule adds one dynamic routing rule (user + source -> blocked) via RoutingService.
func (*XrayAPI) AddUser ¶
AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
func (*XrayAPI) Close ¶
func (x *XrayAPI) Close()
Close closes the gRPC connection and resets the XrayAPI client state.
func (*XrayAPI) DelInbound ¶
DelInbound removes an inbound configuration from the Xray core by tag.
func (*XrayAPI) GetTraffic ¶
func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error)
GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
func (*XrayAPI) GetUserOnlineIPList ¶
func (x *XrayAPI) GetUserOnlineIPList(ctx context.Context, email string, reset bool) ([]OnlineIPSession, error)
GetUserOnlineIPList returns IP -> last-seen unix time for the given client email via gRPC GetStatsOnlineIpList.
func (*XrayAPI) Init ¶
Init connects to the Xray API server and initializes handler and stats service clients.
func (*XrayAPI) IsConnected ¶
IsConnected checks if the gRPC connection is still active.
func (*XrayAPI) RemoveSessionIPBlockRule ¶
RemoveSessionIPBlockRule removes a routing rule by ruleTag via RoutingService.
func (*XrayAPI) RemoveUser ¶
RemoveUser removes a user from an inbound in the Xray core by email.