init xboard node
This commit is contained in:
@@ -0,0 +1,553 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/cedar2025/xboard-node/internal/config"
|
||||
"github.com/cedar2025/xboard-node/internal/kernel"
|
||||
"github.com/cedar2025/xboard-node/internal/panel"
|
||||
)
|
||||
|
||||
// M is a shorthand for building JSON-like maps
|
||||
type M = map[string]interface{}
|
||||
|
||||
func buildConfig(kcfg config.KernelConfig, nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
outbounds := []M{
|
||||
{"protocol": "freedom", "tag": "direct"},
|
||||
{"protocol": "blackhole", "tag": "block"},
|
||||
}
|
||||
|
||||
// Panel-defined custom outbounds (structured, converted to Xray native)
|
||||
for _, co := range nc.CustomOutbounds {
|
||||
outbounds = append(outbounds, outboundConfigToXray(co))
|
||||
}
|
||||
// Static outbounds from local config file (already kernel-native format)
|
||||
for _, co := range kcfg.CustomOutbound {
|
||||
outbounds = append(outbounds, M(co))
|
||||
}
|
||||
|
||||
cfg := M{
|
||||
"log": M{
|
||||
"loglevel": xrayLogLevel(kcfg.LogLevel),
|
||||
},
|
||||
"stats": M{},
|
||||
"policy": M{
|
||||
"levels": M{
|
||||
"0": M{
|
||||
"statsUserUplink": true,
|
||||
"statsUserDownlink": true,
|
||||
},
|
||||
},
|
||||
"system": M{
|
||||
"statsInboundUplink": true,
|
||||
"statsInboundDownlink": true,
|
||||
"statsOutboundUplink": true,
|
||||
"statsOutboundDownlink": true,
|
||||
},
|
||||
},
|
||||
"outbounds": outbounds,
|
||||
}
|
||||
|
||||
inbound := buildInbound(nc, users, certFile, keyFile)
|
||||
if inbound != nil {
|
||||
cfg["inbounds"] = []M{inbound}
|
||||
} else {
|
||||
slog.Warn("xray: unsupported protocol, no inbound configured — node will not accept connections",
|
||||
"protocol", nc.Protocol,
|
||||
"supported", "vmess, vless, trojan, shadowsocks, socks, http")
|
||||
}
|
||||
|
||||
// Merge panel routes and static config routes
|
||||
cfg["routing"] = buildRouting(nc.Routes, mergeRouteList(nc.CustomRoutes, kcfg.CustomRoute))
|
||||
|
||||
mergeCustomXray(cfg, kcfg)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// outboundConfigToXray converts a structured OutboundConfig (from the panel)
|
||||
// into an Xray outbound object. Xray uses a nested layout where protocol-
|
||||
// specific fields go inside a "settings" key, and chain proxying uses "proxySettings".
|
||||
func outboundConfigToXray(oc panel.OutboundConfig) M {
|
||||
m := M{
|
||||
"protocol": oc.Protocol,
|
||||
"tag": oc.Tag,
|
||||
}
|
||||
if len(oc.Settings) > 0 {
|
||||
m["settings"] = oc.Settings
|
||||
}
|
||||
if oc.ProxyTag != "" {
|
||||
m["proxySettings"] = M{"tag": oc.ProxyTag}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func mergeRouteList(a, b []map[string]any) []map[string]any {
|
||||
res := make([]map[string]any, 0, len(a)+len(b))
|
||||
res = append(res, a...)
|
||||
res = append(res, b...)
|
||||
return res
|
||||
}
|
||||
|
||||
// mergeCustomXray deep-merges a custom Xray config file into the generated config.
|
||||
// Merge strategy (compatible with V2bX/XrayR custom DNS etc.):
|
||||
// - dns: custom replaces auto-generated
|
||||
// - outbounds: custom entries appended
|
||||
// - routing.rules: custom rules prepended (matched first)
|
||||
// - policy, api: custom deep-merges
|
||||
// - inbounds: NOT merged (panel-managed, authoritative)
|
||||
func mergeCustomXray(cfg M, kcfg config.KernelConfig) {
|
||||
custom, err := kernel.LoadCustomConfig(kcfg.CustomConfig)
|
||||
if err != nil {
|
||||
slog.Error("failed to load custom xray config", "error", err)
|
||||
return
|
||||
}
|
||||
if custom == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// dns — custom replaces (same as V2bX DnsConfigPath)
|
||||
if v, ok := custom["dns"]; ok {
|
||||
cfg["dns"] = v
|
||||
}
|
||||
|
||||
// outbounds — append custom entries
|
||||
if v, ok := custom["outbounds"]; ok {
|
||||
if existing, ok := cfg["outbounds"].([]M); ok {
|
||||
cfg["outbounds"] = kernel.MergeAppendList(existing, v)
|
||||
}
|
||||
}
|
||||
|
||||
// routing — merge sub-fields
|
||||
if customRouting, ok := custom["routing"]; ok {
|
||||
if customRoutingMap, ok := customRouting.(map[string]any); ok {
|
||||
mergeCustomXrayRouting(cfg, customRoutingMap)
|
||||
}
|
||||
}
|
||||
|
||||
// other top-level keys (policy, api, transport, etc.) — custom overrides,
|
||||
// but we protect auto-generated inbounds, stats, log, routing, outbounds
|
||||
protected := map[string]bool{
|
||||
"inbounds": true, "outbounds": true, "routing": true,
|
||||
"dns": true, "log": true, "stats": true, "policy": true,
|
||||
}
|
||||
for k, v := range custom {
|
||||
if !protected[k] {
|
||||
cfg[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeCustomXrayRouting(cfg M, customRouting map[string]any) {
|
||||
routing, ok := cfg["routing"].(M)
|
||||
if !ok {
|
||||
routing = M{}
|
||||
cfg["routing"] = routing
|
||||
}
|
||||
|
||||
// rules — custom rules prepended (so they match before panel rules)
|
||||
if v, ok := customRouting["rules"]; ok {
|
||||
if existing, ok := routing["rules"].([]M); ok {
|
||||
routing["rules"] = kernel.MergePrependList(existing, v)
|
||||
}
|
||||
}
|
||||
|
||||
// domainStrategy, balancers, etc. — custom overrides
|
||||
for k, v := range customRouting {
|
||||
if k == "rules" {
|
||||
continue
|
||||
}
|
||||
routing[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
func xrayLogLevel(singboxLevel string) string {
|
||||
switch singboxLevel {
|
||||
case "trace", "debug":
|
||||
return "debug"
|
||||
case "info":
|
||||
return "info"
|
||||
case "warn":
|
||||
return "warning"
|
||||
case "error":
|
||||
return "error"
|
||||
case "fatal", "panic":
|
||||
return "error"
|
||||
default:
|
||||
return "warning"
|
||||
}
|
||||
}
|
||||
|
||||
func buildInbound(nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
listenAddr := "::"
|
||||
if nc.ListenIP != "" {
|
||||
listenAddr = nc.ListenIP
|
||||
}
|
||||
base := M{
|
||||
"tag": nc.Protocol + "-in",
|
||||
"listen": listenAddr,
|
||||
"port": nc.ServerPort,
|
||||
"protocol": nc.Protocol,
|
||||
}
|
||||
|
||||
switch nc.Protocol {
|
||||
case "vmess":
|
||||
return buildVMess(base, nc, users, certFile, keyFile)
|
||||
case "vless":
|
||||
return buildVLESS(base, nc, users, certFile, keyFile)
|
||||
case "trojan":
|
||||
return buildTrojan(base, nc, users, certFile, keyFile)
|
||||
case "shadowsocks":
|
||||
return buildShadowsocks(base, nc, users)
|
||||
case "socks":
|
||||
return buildSocks(base, users)
|
||||
case "http":
|
||||
return buildHTTP(base, nc, users, certFile, keyFile)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// userEmail returns the stats-tracking email for a user.
|
||||
// Format: "user@<id>" so we can parse back the user ID from stats counters.
|
||||
func userEmail(userID int) string {
|
||||
return fmt.Sprintf("user@%d", userID)
|
||||
}
|
||||
|
||||
func buildVMess(base M, nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
clients := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
clients = append(clients, M{
|
||||
"id": u.UUID,
|
||||
"alterId": 0,
|
||||
"email": userEmail(u.ID),
|
||||
})
|
||||
}
|
||||
base["settings"] = M{"clients": clients}
|
||||
|
||||
applyStreamSettings(base, nc, certFile, keyFile)
|
||||
return base
|
||||
}
|
||||
|
||||
func buildVLESS(base M, nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
clients := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
client := M{
|
||||
"id": u.UUID,
|
||||
"email": userEmail(u.ID),
|
||||
}
|
||||
if nc.Flow != "" {
|
||||
client["flow"] = nc.Flow
|
||||
}
|
||||
clients = append(clients, client)
|
||||
}
|
||||
base["settings"] = M{
|
||||
"clients": clients,
|
||||
"decryption": "none",
|
||||
}
|
||||
|
||||
applyStreamSettings(base, nc, certFile, keyFile)
|
||||
return base
|
||||
}
|
||||
|
||||
func buildTrojan(base M, nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
clients := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
clients = append(clients, M{
|
||||
"password": u.UUID,
|
||||
"email": userEmail(u.ID),
|
||||
})
|
||||
}
|
||||
base["settings"] = M{"clients": clients}
|
||||
|
||||
applyStreamSettings(base, nc, certFile, keyFile)
|
||||
return base
|
||||
}
|
||||
|
||||
func buildShadowsocks(base M, nc *panel.NodeConfig, users []panel.User) M {
|
||||
// Single-user mode for traditional ciphers
|
||||
if !strings.HasPrefix(nc.Cipher, "2022-blake3-") {
|
||||
if len(users) > 0 {
|
||||
base["settings"] = M{
|
||||
"method": nc.Cipher,
|
||||
"password": users[0].UUID,
|
||||
"email": userEmail(users[0].ID),
|
||||
"network": "tcp,udp",
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// Multi-user mode for 2022-blake3 ciphers
|
||||
clients := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
clients = append(clients, M{
|
||||
"password": u.UUID,
|
||||
"email": userEmail(u.ID),
|
||||
})
|
||||
}
|
||||
base["settings"] = M{
|
||||
"method": nc.Cipher,
|
||||
"password": nc.ServerKey,
|
||||
"clients": clients,
|
||||
"network": "tcp,udp",
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func buildSocks(base M, users []panel.User) M {
|
||||
base["protocol"] = "socks"
|
||||
accounts := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
accounts = append(accounts, M{
|
||||
"user": u.UUID,
|
||||
"pass": u.UUID,
|
||||
})
|
||||
}
|
||||
base["settings"] = M{
|
||||
"auth": "password",
|
||||
"accounts": accounts,
|
||||
"udp": true,
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func buildHTTP(base M, nc *panel.NodeConfig, users []panel.User, certFile, keyFile string) M {
|
||||
base["protocol"] = "http"
|
||||
accounts := make([]M, 0, len(users))
|
||||
for _, u := range users {
|
||||
accounts = append(accounts, M{
|
||||
"user": u.UUID,
|
||||
"pass": u.UUID,
|
||||
})
|
||||
}
|
||||
base["settings"] = M{
|
||||
"accounts": accounts,
|
||||
}
|
||||
|
||||
if nc.TLS == 1 {
|
||||
applyStreamSettings(base, nc, certFile, keyFile)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func applyStreamSettings(base M, nc *panel.NodeConfig, certFile, keyFile string) {
|
||||
ss := M{}
|
||||
|
||||
// Network / transport
|
||||
network := nc.Network
|
||||
if network == "" {
|
||||
network = "tcp"
|
||||
}
|
||||
ss["network"] = network
|
||||
|
||||
switch network {
|
||||
case "ws":
|
||||
wsSettings := M{}
|
||||
if nc.NetworkSettings != nil {
|
||||
if v, ok := nc.NetworkSettings["path"]; ok {
|
||||
wsSettings["path"] = v
|
||||
}
|
||||
headers := M{}
|
||||
if v, ok := nc.NetworkSettings["headers"]; ok {
|
||||
if headersMap, ok := v.(map[string]interface{}); ok {
|
||||
for k, val := range headersMap {
|
||||
headers[k] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
if v, ok := nc.NetworkSettings["host"]; ok {
|
||||
headers["Host"] = v
|
||||
}
|
||||
if len(headers) > 0 {
|
||||
wsSettings["headers"] = headers
|
||||
}
|
||||
}
|
||||
ss["wsSettings"] = wsSettings
|
||||
|
||||
case "grpc":
|
||||
grpcSettings := M{}
|
||||
if nc.NetworkSettings != nil {
|
||||
if v, ok := nc.NetworkSettings["service_name"]; ok {
|
||||
grpcSettings["serviceName"] = v
|
||||
}
|
||||
}
|
||||
ss["grpcSettings"] = grpcSettings
|
||||
|
||||
case "httpupgrade":
|
||||
huSettings := M{}
|
||||
if nc.NetworkSettings != nil {
|
||||
if v, ok := nc.NetworkSettings["path"]; ok {
|
||||
huSettings["path"] = v
|
||||
}
|
||||
if v, ok := nc.NetworkSettings["host"]; ok {
|
||||
huSettings["host"] = v
|
||||
}
|
||||
}
|
||||
ss["httpupgradeSettings"] = huSettings
|
||||
|
||||
case "h2", "http":
|
||||
ss["network"] = "h2"
|
||||
h2Settings := M{}
|
||||
if nc.NetworkSettings != nil {
|
||||
if v, ok := nc.NetworkSettings["path"]; ok {
|
||||
h2Settings["path"] = v
|
||||
}
|
||||
if v, ok := nc.NetworkSettings["host"]; ok {
|
||||
h2Settings["host"] = []interface{}{v}
|
||||
}
|
||||
}
|
||||
ss["httpSettings"] = h2Settings
|
||||
|
||||
case "tcp":
|
||||
// default, no extra settings
|
||||
}
|
||||
|
||||
// TLS
|
||||
if nc.TLS == 1 {
|
||||
tlsSettings := M{}
|
||||
serverName := nc.ServerName
|
||||
if serverName == "" && nc.Host != "" {
|
||||
serverName = nc.Host
|
||||
}
|
||||
if serverName != "" {
|
||||
tlsSettings["serverName"] = serverName
|
||||
}
|
||||
if nc.TLSSettings != nil {
|
||||
if sn, ok := nc.TLSSettings["server_name"]; ok && sn != "" {
|
||||
tlsSettings["serverName"] = sn
|
||||
}
|
||||
}
|
||||
if certFile != "" && keyFile != "" {
|
||||
tlsSettings["certificates"] = []M{
|
||||
{
|
||||
"certificateFile": certFile,
|
||||
"keyFile": keyFile,
|
||||
},
|
||||
}
|
||||
}
|
||||
ss["security"] = "tls"
|
||||
ss["tlsSettings"] = tlsSettings
|
||||
} else if nc.TLS == 2 {
|
||||
ss["security"] = "reality"
|
||||
ss["realitySettings"] = buildRealitySettings(nc)
|
||||
}
|
||||
|
||||
base["streamSettings"] = ss
|
||||
}
|
||||
|
||||
func buildRealitySettings(nc *panel.NodeConfig) M {
|
||||
reality := M{"show": false}
|
||||
|
||||
if nc.TLSSettings == nil {
|
||||
return reality
|
||||
}
|
||||
|
||||
if pk, ok := nc.TLSSettings["private_key"]; ok {
|
||||
reality["privateKey"] = pk
|
||||
}
|
||||
if sid, ok := nc.TLSSettings["short_id"]; ok {
|
||||
switch v := sid.(type) {
|
||||
case string:
|
||||
reality["shortIds"] = []string{v}
|
||||
case []interface{}:
|
||||
ids := make([]string, 0, len(v))
|
||||
for _, item := range v {
|
||||
ids = append(ids, fmt.Sprintf("%v", item))
|
||||
}
|
||||
reality["shortIds"] = ids
|
||||
}
|
||||
}
|
||||
|
||||
if dest, ok := nc.TLSSettings["dest"]; ok {
|
||||
destStr := fmt.Sprintf("%v", dest)
|
||||
reality["dest"] = destStr
|
||||
}
|
||||
if sn, ok := nc.TLSSettings["server_name"]; ok {
|
||||
reality["serverNames"] = []string{fmt.Sprintf("%v", sn)}
|
||||
if _, exists := reality["dest"]; !exists {
|
||||
reality["dest"] = fmt.Sprintf("%v:443", sn)
|
||||
}
|
||||
}
|
||||
|
||||
return reality
|
||||
}
|
||||
|
||||
func buildRouting(rules []panel.RouteRule, customRules []map[string]any) M {
|
||||
var xrayRules []M
|
||||
|
||||
// Custom route rules (from Panel CustomRoutes or local config) have HIGHEST priority
|
||||
for _, cr := range customRules {
|
||||
xrayRules = append(xrayRules, M(cr))
|
||||
}
|
||||
|
||||
xrayRules = append(xrayRules, M{
|
||||
"type": "field",
|
||||
"ip": []string{
|
||||
"10.0.0.0/8",
|
||||
"100.64.0.0/10",
|
||||
"127.0.0.0/8",
|
||||
"169.254.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"192.0.0.0/24",
|
||||
"192.168.0.0/16",
|
||||
"198.18.0.0/15",
|
||||
"fc00::/7",
|
||||
"fe80::/10",
|
||||
"::1/128",
|
||||
},
|
||||
"outboundTag": "block",
|
||||
})
|
||||
|
||||
for _, rule := range rules {
|
||||
if len(rule.Match) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var ips, domains []string
|
||||
for _, m := range rule.Match {
|
||||
m = strings.TrimSpace(m)
|
||||
if m == "" {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(m, "geoip:") {
|
||||
ips = append(ips, m) // "geoip:cn" → ip field, passed as-is
|
||||
} else if strings.HasPrefix(m, "geosite:") {
|
||||
domains = append(domains, m) // "geosite:google" → domain field, passed as-is
|
||||
} else if strings.Contains(m, "/") {
|
||||
ips = append(ips, m)
|
||||
} else {
|
||||
m = strings.TrimPrefix(m, "*.")
|
||||
domains = append(domains, "domain:"+m)
|
||||
}
|
||||
}
|
||||
|
||||
outbound := "block"
|
||||
if rule.Action == "direct" {
|
||||
outbound = "direct"
|
||||
} else if rule.Action == "proxy" && rule.ActionValue != "" {
|
||||
outbound = rule.ActionValue
|
||||
}
|
||||
|
||||
if len(domains) > 0 {
|
||||
xrayRules = append(xrayRules, M{
|
||||
"type": "field",
|
||||
"domain": domains,
|
||||
"outboundTag": outbound,
|
||||
})
|
||||
}
|
||||
if len(ips) > 0 {
|
||||
xrayRules = append(xrayRules, M{
|
||||
"type": "field",
|
||||
"ip": ips,
|
||||
"outboundTag": outbound,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return M{
|
||||
"domainStrategy": "AsIs",
|
||||
"rules": xrayRules,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/cedar2025/xboard-node/internal/config"
|
||||
"github.com/cedar2025/xboard-node/internal/panel"
|
||||
)
|
||||
|
||||
var testKernelCfg = config.KernelConfig{
|
||||
Type: "xray",
|
||||
LogLevel: "warn",
|
||||
}
|
||||
|
||||
var testUsers = []panel.User{
|
||||
{ID: 1, UUID: "279d4f89-3a2c-488d-a67c-2d39a72acdde"},
|
||||
{ID: 5, UUID: "4d5965c8-a60c-452a-a943-af83ec0bb0db"},
|
||||
}
|
||||
|
||||
func TestBuildConfig_AllProtocols_ValidJSON(t *testing.T) {
|
||||
protocols := []struct {
|
||||
name string
|
||||
nc panel.NodeConfig
|
||||
}{
|
||||
{
|
||||
name: "vmess",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "vmess",
|
||||
ServerPort: 10086,
|
||||
Network: "ws",
|
||||
TLS: 1,
|
||||
NetworkSettings: map[string]interface{}{
|
||||
"path": "/vmess",
|
||||
"host": "example.com",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "vless",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "vless",
|
||||
ServerPort: 443,
|
||||
Network: "tcp",
|
||||
TLS: 2,
|
||||
Flow: "xtls-rprx-vision",
|
||||
TLSSettings: map[string]interface{}{
|
||||
"private_key": "test-pk",
|
||||
"short_id": "abcd",
|
||||
"server_name": "www.example.com",
|
||||
"dest": "www.example.com:443",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "trojan",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "trojan",
|
||||
ServerPort: 443,
|
||||
Network: "grpc",
|
||||
TLS: 1,
|
||||
ServerName: "example.com",
|
||||
NetworkSettings: map[string]interface{}{
|
||||
"service_name": "trojan-grpc",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "shadowsocks-aes",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "shadowsocks",
|
||||
ServerPort: 8388,
|
||||
Cipher: "aes-128-gcm",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "shadowsocks-2022",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "shadowsocks",
|
||||
ServerPort: 8388,
|
||||
Cipher: "2022-blake3-aes-128-gcm",
|
||||
ServerKey: "test-server-key",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "socks",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "socks",
|
||||
ServerPort: 1080,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "http",
|
||||
nc: panel.NodeConfig{
|
||||
Protocol: "http",
|
||||
ServerPort: 8080,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range protocols {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := buildConfig(testKernelCfg, &tc.nc, testUsers, "/cert.pem", "/key.pem")
|
||||
|
||||
data, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal failed: %v", err)
|
||||
}
|
||||
|
||||
var parsed map[string]interface{}
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Fatalf("invalid JSON: %v", err)
|
||||
}
|
||||
|
||||
// Check required top-level fields
|
||||
for _, key := range []string{"log", "stats", "policy", "outbounds", "routing"} {
|
||||
if _, ok := parsed[key]; !ok {
|
||||
t.Errorf("missing top-level key: %s", key)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := parsed["inbounds"]; !ok {
|
||||
t.Error("missing inbounds")
|
||||
}
|
||||
|
||||
t.Logf("config size: %d bytes", len(data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_VMess_Users(t *testing.T) {
|
||||
nc := panel.NodeConfig{
|
||||
Protocol: "vmess",
|
||||
ServerPort: 10086,
|
||||
}
|
||||
cfg := buildConfig(testKernelCfg, &nc, testUsers, "", "")
|
||||
data, _ := json.Marshal(cfg)
|
||||
|
||||
var parsed map[string]interface{}
|
||||
json.Unmarshal(data, &parsed)
|
||||
|
||||
inbounds := parsed["inbounds"].([]interface{})
|
||||
ib := inbounds[0].(map[string]interface{})
|
||||
|
||||
if ib["protocol"] != "vmess" {
|
||||
t.Errorf("expected protocol vmess, got %v", ib["protocol"])
|
||||
}
|
||||
|
||||
settings := ib["settings"].(map[string]interface{})
|
||||
clients := settings["clients"].([]interface{})
|
||||
|
||||
if len(clients) != 2 {
|
||||
t.Fatalf("expected 2 clients, got %d", len(clients))
|
||||
}
|
||||
|
||||
c1 := clients[0].(map[string]interface{})
|
||||
if c1["email"] != "user@1" {
|
||||
t.Errorf("expected email user@1, got %v", c1["email"])
|
||||
}
|
||||
if c1["id"] != "279d4f89-3a2c-488d-a67c-2d39a72acdde" {
|
||||
t.Errorf("unexpected UUID: %v", c1["id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_VLESS_Flow(t *testing.T) {
|
||||
nc := panel.NodeConfig{
|
||||
Protocol: "vless",
|
||||
ServerPort: 443,
|
||||
Flow: "xtls-rprx-vision",
|
||||
TLS: 2,
|
||||
TLSSettings: map[string]interface{}{
|
||||
"private_key": "pk",
|
||||
"server_name": "example.com",
|
||||
},
|
||||
}
|
||||
cfg := buildConfig(testKernelCfg, &nc, testUsers, "", "")
|
||||
data, _ := json.Marshal(cfg)
|
||||
|
||||
var parsed map[string]interface{}
|
||||
json.Unmarshal(data, &parsed)
|
||||
|
||||
inbounds := parsed["inbounds"].([]interface{})
|
||||
ib := inbounds[0].(map[string]interface{})
|
||||
settings := ib["settings"].(map[string]interface{})
|
||||
clients := settings["clients"].([]interface{})
|
||||
c1 := clients[0].(map[string]interface{})
|
||||
|
||||
if c1["flow"] != "xtls-rprx-vision" {
|
||||
t.Errorf("expected flow xtls-rprx-vision, got %v", c1["flow"])
|
||||
}
|
||||
|
||||
ss := ib["streamSettings"].(map[string]interface{})
|
||||
if ss["security"] != "reality" {
|
||||
t.Errorf("expected security reality, got %v", ss["security"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRouting_Default(t *testing.T) {
|
||||
routing := buildRouting(nil, nil)
|
||||
rules := routing["rules"].([]M)
|
||||
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 default rule, got %d", len(rules))
|
||||
}
|
||||
|
||||
if rules[0]["outboundTag"] != "block" {
|
||||
t.Errorf("expected block outbound, got %v", rules[0]["outboundTag"])
|
||||
}
|
||||
ips := rules[0]["ip"].([]string)
|
||||
if len(ips) < 5 {
|
||||
t.Errorf("expected multiple private CIDRs, got %d", len(ips))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRouting_WithRules(t *testing.T) {
|
||||
rules := []panel.RouteRule{
|
||||
{
|
||||
ID: 1,
|
||||
Match: []string{"*.baidu.com", "*.qq.com", "10.0.0.0/8"},
|
||||
Action: "block",
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Match: []string{"*.google.com"},
|
||||
Action: "direct",
|
||||
},
|
||||
}
|
||||
|
||||
routing := buildRouting(rules, nil)
|
||||
xrayRules := routing["rules"].([]M)
|
||||
|
||||
// 1 default + 2 domain rules + 1 IP rule = 4
|
||||
if len(xrayRules) != 4 {
|
||||
t.Fatalf("expected 4 rules, got %d", len(xrayRules))
|
||||
}
|
||||
|
||||
// Rule 1: domains block
|
||||
r1 := xrayRules[1]
|
||||
domains := r1["domain"].([]string)
|
||||
if len(domains) != 2 {
|
||||
t.Fatalf("expected 2 domains, got %d", len(domains))
|
||||
}
|
||||
if domains[0] != "domain:baidu.com" || domains[1] != "domain:qq.com" {
|
||||
t.Errorf("unexpected domains: %v", domains)
|
||||
}
|
||||
if r1["outboundTag"] != "block" {
|
||||
t.Errorf("expected block, got %v", r1["outboundTag"])
|
||||
}
|
||||
|
||||
// Rule 2: IP block
|
||||
r2 := xrayRules[2]
|
||||
ips := r2["ip"].([]string)
|
||||
if len(ips) != 1 || ips[0] != "10.0.0.0/8" {
|
||||
t.Errorf("unexpected IPs: %v", ips)
|
||||
}
|
||||
|
||||
// Rule 3: direct
|
||||
r3 := xrayRules[3]
|
||||
if r3["outboundTag"] != "direct" {
|
||||
t.Errorf("expected direct, got %v", r3["outboundTag"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_LogLevel(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"debug", "debug"},
|
||||
{"info", "info"},
|
||||
{"warn", "warning"},
|
||||
{"error", "error"},
|
||||
{"", "warning"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.input, func(t *testing.T) {
|
||||
result := xrayLogLevel(tc.input)
|
||||
if result != tc.expected {
|
||||
t.Errorf("xrayLogLevel(%q) = %q, want %q", tc.input, result, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_StatsEnabled(t *testing.T) {
|
||||
nc := panel.NodeConfig{
|
||||
Protocol: "vmess",
|
||||
ServerPort: 10086,
|
||||
}
|
||||
cfg := buildConfig(testKernelCfg, &nc, testUsers, "", "")
|
||||
data, _ := json.Marshal(cfg)
|
||||
|
||||
var parsed map[string]interface{}
|
||||
json.Unmarshal(data, &parsed)
|
||||
|
||||
// Verify stats is enabled
|
||||
if _, ok := parsed["stats"]; !ok {
|
||||
t.Error("stats not enabled")
|
||||
}
|
||||
|
||||
// Verify policy enables user stats
|
||||
policy := parsed["policy"].(map[string]interface{})
|
||||
levels := policy["levels"].(map[string]interface{})
|
||||
level0 := levels["0"].(map[string]interface{})
|
||||
|
||||
if v, ok := level0["statsUserUplink"]; !ok || v != true {
|
||||
t.Error("statsUserUplink not enabled")
|
||||
}
|
||||
if v, ok := level0["statsUserDownlink"]; !ok || v != true {
|
||||
t.Error("statsUserDownlink not enabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_Shadowsocks_SingleUser(t *testing.T) {
|
||||
nc := panel.NodeConfig{
|
||||
Protocol: "shadowsocks",
|
||||
ServerPort: 8388,
|
||||
Cipher: "aes-128-gcm",
|
||||
}
|
||||
cfg := buildConfig(testKernelCfg, &nc, testUsers, "", "")
|
||||
data, _ := json.Marshal(cfg)
|
||||
|
||||
var parsed map[string]interface{}
|
||||
json.Unmarshal(data, &parsed)
|
||||
|
||||
inbounds := parsed["inbounds"].([]interface{})
|
||||
ib := inbounds[0].(map[string]interface{})
|
||||
settings := ib["settings"].(map[string]interface{})
|
||||
|
||||
// Single-user mode: password directly, no clients array
|
||||
if settings["method"] != "aes-128-gcm" {
|
||||
t.Errorf("expected method aes-128-gcm, got %v", settings["method"])
|
||||
}
|
||||
if settings["password"] != testUsers[0].UUID {
|
||||
t.Errorf("expected password %s, got %v", testUsers[0].UUID, settings["password"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildConfig_Shadowsocks_MultiUser(t *testing.T) {
|
||||
nc := panel.NodeConfig{
|
||||
Protocol: "shadowsocks",
|
||||
ServerPort: 8388,
|
||||
Cipher: "2022-blake3-aes-128-gcm",
|
||||
ServerKey: "server-key",
|
||||
}
|
||||
cfg := buildConfig(testKernelCfg, &nc, testUsers, "", "")
|
||||
data, _ := json.Marshal(cfg)
|
||||
|
||||
var parsed map[string]interface{}
|
||||
json.Unmarshal(data, &parsed)
|
||||
|
||||
inbounds := parsed["inbounds"].([]interface{})
|
||||
ib := inbounds[0].(map[string]interface{})
|
||||
settings := ib["settings"].(map[string]interface{})
|
||||
|
||||
if settings["password"] != "server-key" {
|
||||
t.Errorf("expected server key, got %v", settings["password"])
|
||||
}
|
||||
clients := settings["clients"].([]interface{})
|
||||
if len(clients) != 2 {
|
||||
t.Fatalf("expected 2 clients, got %d", len(clients))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
_ "unsafe"
|
||||
|
||||
xrayDispatcher "github.com/xtls/xray-core/app/dispatcher"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"github.com/cedar2025/xboard-node/internal/kernel"
|
||||
)
|
||||
|
||||
// Access xray's internal config creator registry so we can replace the
|
||||
// default dispatcher factory with ours. This runs AFTER xray's init()
|
||||
// functions because our package imports xray (dependency order guarantee).
|
||||
//
|
||||
//go:linkname typeCreatorRegistry github.com/xtls/xray-core/common.typeCreatorRegistry
|
||||
var typeCreatorRegistry map[reflect.Type]common.ConfigCreator
|
||||
|
||||
var origDispatcherFactory common.ConfigCreator
|
||||
|
||||
// globalLimitDispatcher is set when the factory creates a LimitDispatcher.
|
||||
// The Xray kernel reads it to configure limits and get connections.
|
||||
var globalLimitDispatcher atomic.Pointer[LimitDispatcher]
|
||||
|
||||
func init() {
|
||||
configType := reflect.TypeOf((*xrayDispatcher.Config)(nil))
|
||||
origDispatcherFactory = typeCreatorRegistry[configType]
|
||||
typeCreatorRegistry[configType] = limitDispatcherFactory
|
||||
}
|
||||
|
||||
func limitDispatcherFactory(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
orig, err := origDispatcherFactory(ctx, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inner, ok := orig.(routing.Dispatcher)
|
||||
if !ok {
|
||||
return orig, nil
|
||||
}
|
||||
ld := &LimitDispatcher{
|
||||
inner: orig,
|
||||
innerDisp: inner,
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
globalLimitDispatcher.Store(ld)
|
||||
slog.Debug("xray: limit dispatcher installed")
|
||||
return ld, nil
|
||||
}
|
||||
|
||||
// LimitDispatcher wraps xray's DefaultDispatcher to add per-user device
|
||||
// limit enforcement, speed limiting, and per-connection source IP tracking.
|
||||
// It hooks into Dispatch/DispatchLink which are called AFTER the protocol
|
||||
// handler has identified the user, so it works for ALL protocols.
|
||||
type LimitDispatcher struct {
|
||||
inner interface{} // original DefaultDispatcher (Feature + Dispatcher)
|
||||
innerDisp routing.Dispatcher // same object, typed as Dispatcher
|
||||
|
||||
mu sync.RWMutex
|
||||
conns map[string]*dispatchedConn // connID → conn
|
||||
userIPs map[string]map[string]int // email → sourceIP → count
|
||||
deviceLimits map[string]int // email → max devices
|
||||
speedLimits map[string]int // email → Mbps
|
||||
speedBuckets sync.Map // email → *rate.Limiter
|
||||
emailToUID map[string]int // email → panel user ID
|
||||
|
||||
connIDSeq atomic.Uint64
|
||||
}
|
||||
|
||||
type dispatchedConn struct {
|
||||
id string
|
||||
email string
|
||||
sourceIP string
|
||||
userID int
|
||||
upload atomic.Int64
|
||||
download atomic.Int64
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
// ─── routing.Dispatcher ──────────────────────────────────────────────────────
|
||||
|
||||
func (d *LimitDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
email, sourceIP, isTCP, err := d.identifyAndCheck(ctx, dest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
link, err := d.innerDisp.Dispatch(ctx, dest)
|
||||
if err != nil {
|
||||
if email != "" && isTCP {
|
||||
d.delConn(email, sourceIP)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if email != "" {
|
||||
d.wrapLink(ctx, link, email, sourceIP, isTCP)
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
email, sourceIP, isTCP, err := d.identifyAndCheck(ctx, dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if email != "" {
|
||||
d.wrapLink(ctx, link, email, sourceIP, isTCP)
|
||||
}
|
||||
return d.innerDisp.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
|
||||
// identifyAndCheck extracts user identity from the session context, enforces
|
||||
// device limits, and returns the user's email, source IP, and TCP flag.
|
||||
// Returns a non-nil error only when the connection should be rejected.
|
||||
func (d *LimitDispatcher) identifyAndCheck(ctx context.Context, dest net.Destination) (email, sourceIP string, isTCP bool, err error) {
|
||||
si := session.InboundFromContext(ctx)
|
||||
if si == nil || si.User == nil || len(si.User.Email) == 0 {
|
||||
return "", "", false, nil
|
||||
}
|
||||
email = si.User.Email
|
||||
sourceIP = si.Source.Address.IP().String()
|
||||
isTCP = dest.Network == net.Network_TCP
|
||||
|
||||
if d.checkDeviceLimit(email, sourceIP, isTCP) {
|
||||
slog.Info("xray: device limit exceeded", "email", email, "ip", sourceIP)
|
||||
return "", "", false, errors.New("device limit exceeded for " + email)
|
||||
}
|
||||
return email, sourceIP, isTCP, nil
|
||||
}
|
||||
|
||||
// wrapLink instruments a transport.Link with per-connection byte counting,
|
||||
// rate limiting, and lifecycle tracking. Must only be called when email != "".
|
||||
func (d *LimitDispatcher) wrapLink(ctx context.Context, link *transport.Link, email, sourceIP string, isTCP bool) {
|
||||
connID := "xd-" + strconv.FormatUint(d.connIDSeq.Add(1), 36)
|
||||
dc := &dispatchedConn{
|
||||
id: connID,
|
||||
email: email,
|
||||
sourceIP: sourceIP,
|
||||
userID: d.getUID(email),
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
d.conns[connID] = dc
|
||||
d.mu.Unlock()
|
||||
|
||||
onClose := func() {
|
||||
if dc.closed.CompareAndSwap(false, true) {
|
||||
if isTCP {
|
||||
d.delConn(email, sourceIP)
|
||||
}
|
||||
d.mu.Lock()
|
||||
delete(d.conns, connID)
|
||||
d.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
limiter := d.getBucket(email)
|
||||
|
||||
link.Reader = &statsCloseReader{
|
||||
Reader: link.Reader,
|
||||
counter: &dc.upload,
|
||||
limiter: limiter,
|
||||
ctx: ctx,
|
||||
}
|
||||
link.Writer = &statsCloseWriter{
|
||||
Writer: link.Writer,
|
||||
counter: &dc.download,
|
||||
limiter: limiter,
|
||||
ctx: ctx,
|
||||
onClose: onClose,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── features.Feature (delegated) ───────────────────────────────────────────
|
||||
|
||||
func (d *LimitDispatcher) Type() interface{} { return routing.DispatcherType() }
|
||||
|
||||
func (d *LimitDispatcher) Start() error {
|
||||
if s, ok := d.inner.(interface{ Start() error }); ok {
|
||||
return s.Start()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) Close() error {
|
||||
if c, ok := d.inner.(interface{ Close() error }); ok {
|
||||
return c.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─── Limit management (called by Xray kernel) ──────────────────────────────
|
||||
|
||||
func (d *LimitDispatcher) UpdateLimits(emailToUID map[string]int, deviceLimits, speedLimits map[string]int) {
|
||||
d.mu.Lock()
|
||||
d.emailToUID = emailToUID
|
||||
d.deviceLimits = deviceLimits
|
||||
d.speedLimits = speedLimits
|
||||
d.mu.Unlock()
|
||||
|
||||
d.speedBuckets.Range(func(key, _ interface{}) bool {
|
||||
if _, ok := speedLimits[key.(string)]; !ok {
|
||||
d.speedBuckets.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) ResetConns() {
|
||||
d.mu.Lock()
|
||||
d.conns = make(map[string]*dispatchedConn)
|
||||
d.userIPs = make(map[string]map[string]int)
|
||||
d.mu.Unlock()
|
||||
|
||||
d.speedBuckets.Range(func(key, _ interface{}) bool {
|
||||
d.speedBuckets.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) Snapshot() []kernel.Connection {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
|
||||
result := make([]kernel.Connection, 0, len(d.conns))
|
||||
for _, c := range d.conns {
|
||||
result = append(result, kernel.Connection{
|
||||
ID: c.id,
|
||||
UserID: c.userID,
|
||||
SourceIP: c.sourceIP,
|
||||
Upload: c.upload.Load(),
|
||||
Download: c.download.Load(),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) CloseConn(id string) bool {
|
||||
d.mu.RLock()
|
||||
c, ok := d.conns[id]
|
||||
d.mu.RUnlock()
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
c.closed.Store(true)
|
||||
d.delConn(c.email, c.sourceIP)
|
||||
d.mu.Lock()
|
||||
delete(d.conns, id)
|
||||
d.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
// ─── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
func (d *LimitDispatcher) checkDeviceLimit(email, sourceIP string, isTCP bool) bool {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
limit, hasLimit := d.deviceLimits[email]
|
||||
if !hasLimit || limit <= 0 {
|
||||
if isTCP {
|
||||
if d.userIPs[email] == nil {
|
||||
d.userIPs[email] = make(map[string]int)
|
||||
}
|
||||
d.userIPs[email][sourceIP]++
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
ips := d.userIPs[email]
|
||||
if ips == nil {
|
||||
ips = make(map[string]int)
|
||||
d.userIPs[email] = ips
|
||||
}
|
||||
|
||||
if ips[sourceIP] > 0 {
|
||||
if isTCP {
|
||||
ips[sourceIP]++
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if len(ips) < limit {
|
||||
if isTCP {
|
||||
ips[sourceIP]++
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Over limit — deterministic: allow lowest IPs lexicographically
|
||||
ipList := make([]string, 0, len(ips)+1)
|
||||
for ip := range ips {
|
||||
ipList = append(ipList, ip)
|
||||
}
|
||||
ipList = append(ipList, sourceIP)
|
||||
sort.Strings(ipList)
|
||||
|
||||
for i := 0; i < limit && i < len(ipList); i++ {
|
||||
if ipList[i] == sourceIP {
|
||||
if isTCP {
|
||||
ips[sourceIP]++
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) delConn(email, sourceIP string) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if ips, ok := d.userIPs[email]; ok {
|
||||
ips[sourceIP]--
|
||||
if ips[sourceIP] <= 0 {
|
||||
delete(ips, sourceIP)
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
delete(d.userIPs, email)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) getUID(email string) int {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.emailToUID[email]
|
||||
}
|
||||
|
||||
func (d *LimitDispatcher) getBucket(email string) *rate.Limiter {
|
||||
d.mu.RLock()
|
||||
mbps, ok := d.speedLimits[email]
|
||||
d.mu.RUnlock()
|
||||
if !ok || mbps <= 0 {
|
||||
return nil
|
||||
}
|
||||
bytesPerSec := int(mbps) * 1_000_000 / 8
|
||||
burst := bytesPerSec
|
||||
if burst < 64*1024 {
|
||||
burst = 64 * 1024
|
||||
}
|
||||
v, loaded := d.speedBuckets.LoadOrStore(email, rate.NewLimiter(rate.Limit(bytesPerSec), burst))
|
||||
lim := v.(*rate.Limiter)
|
||||
if loaded {
|
||||
// Update existing limiter in case speed limit changed.
|
||||
lim.SetLimit(rate.Limit(bytesPerSec))
|
||||
lim.SetBurst(burst)
|
||||
}
|
||||
return lim
|
||||
}
|
||||
|
||||
// ─── I/O wrappers ───────────────────────────────────────────────────────────
|
||||
|
||||
type statsCloseReader struct {
|
||||
buf.Reader
|
||||
counter *atomic.Int64
|
||||
limiter *rate.Limiter
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (r *statsCloseReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
mb, err := r.Reader.ReadMultiBuffer()
|
||||
if n := int64(mb.Len()); n > 0 {
|
||||
r.counter.Add(n)
|
||||
if r.limiter != nil {
|
||||
waitN := int(n)
|
||||
if burst := r.limiter.Burst(); waitN > burst {
|
||||
waitN = burst
|
||||
}
|
||||
_ = r.limiter.WaitN(r.ctx, waitN)
|
||||
}
|
||||
}
|
||||
return mb, err
|
||||
}
|
||||
|
||||
func (r *statsCloseReader) Close() error { return common.Close(r.Reader) }
|
||||
func (r *statsCloseReader) Interrupt() { common.Interrupt(r.Reader) }
|
||||
|
||||
type statsCloseWriter struct {
|
||||
buf.Writer
|
||||
counter *atomic.Int64
|
||||
limiter *rate.Limiter
|
||||
ctx context.Context
|
||||
onClose func()
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func (w *statsCloseWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
n := int64(mb.Len())
|
||||
if w.limiter != nil {
|
||||
waitN := int(n)
|
||||
if burst := w.limiter.Burst(); waitN > burst {
|
||||
waitN = burst
|
||||
}
|
||||
_ = w.limiter.WaitN(w.ctx, waitN)
|
||||
}
|
||||
w.counter.Add(n)
|
||||
return w.Writer.WriteMultiBuffer(mb)
|
||||
}
|
||||
|
||||
func (w *statsCloseWriter) Close() error {
|
||||
if w.closed.CompareAndSwap(false, true) {
|
||||
w.onClose()
|
||||
}
|
||||
return common.Close(w.Writer)
|
||||
}
|
||||
|
||||
func (w *statsCloseWriter) Interrupt() {
|
||||
if w.closed.CompareAndSwap(false, true) {
|
||||
w.onClose()
|
||||
}
|
||||
common.Interrupt(w.Writer)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/cedar2025/xboard-node/internal/panel"
|
||||
)
|
||||
|
||||
func TestLimitDispatcher_DeviceLimitCheck(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
|
||||
users := []panel.User{
|
||||
{ID: 1, UUID: "uuid-1", DeviceLimit: 2, SpeedLimit: 0},
|
||||
{ID: 2, UUID: "uuid-2", DeviceLimit: 0, SpeedLimit: 10},
|
||||
}
|
||||
|
||||
emailToUID := make(map[string]int)
|
||||
deviceLimits := make(map[string]int)
|
||||
speedLimits := make(map[string]int)
|
||||
for _, u := range users {
|
||||
email := userEmail(u.ID)
|
||||
emailToUID[email] = u.ID
|
||||
if u.DeviceLimit > 0 {
|
||||
deviceLimits[email] = u.DeviceLimit
|
||||
}
|
||||
if u.SpeedLimit > 0 {
|
||||
speedLimits[email] = u.SpeedLimit
|
||||
}
|
||||
}
|
||||
ld.UpdateLimits(emailToUID, deviceLimits, speedLimits)
|
||||
|
||||
email1 := userEmail(1)
|
||||
|
||||
// First IP should be allowed
|
||||
if ld.checkDeviceLimit(email1, "1.1.1.1", true) {
|
||||
t.Error("first IP should be allowed")
|
||||
}
|
||||
|
||||
// Second IP should be allowed (limit=2)
|
||||
if ld.checkDeviceLimit(email1, "2.2.2.2", true) {
|
||||
t.Error("second IP should be allowed")
|
||||
}
|
||||
|
||||
// Third unique IP should be rejected
|
||||
if !ld.checkDeviceLimit(email1, "3.3.3.3", true) {
|
||||
t.Error("third IP should be rejected (limit=2)")
|
||||
}
|
||||
|
||||
// Same IP as first should be allowed (already connected)
|
||||
if ld.checkDeviceLimit(email1, "1.1.1.1", true) {
|
||||
t.Error("same IP should always be allowed")
|
||||
}
|
||||
|
||||
// User 2 has no device limit — should always be allowed
|
||||
email2 := userEmail(2)
|
||||
for i := 0; i < 10; i++ {
|
||||
ip := "10.0.0." + string(rune('0'+i))
|
||||
if ld.checkDeviceLimit(email2, ip, true) {
|
||||
t.Errorf("user with no device limit should always be allowed (ip=%s)", ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitDispatcher_DelConn(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
|
||||
email := userEmail(1)
|
||||
deviceLimits := map[string]int{email: 2}
|
||||
ld.UpdateLimits(map[string]int{email: 1}, deviceLimits, nil)
|
||||
|
||||
// Add 2 IPs
|
||||
ld.checkDeviceLimit(email, "1.1.1.1", true)
|
||||
ld.checkDeviceLimit(email, "2.2.2.2", true)
|
||||
|
||||
// Third should be rejected
|
||||
if !ld.checkDeviceLimit(email, "3.3.3.3", true) {
|
||||
t.Error("third IP should be rejected")
|
||||
}
|
||||
|
||||
// Remove first IP
|
||||
ld.delConn(email, "1.1.1.1")
|
||||
|
||||
// Now third IP should be allowed
|
||||
if ld.checkDeviceLimit(email, "3.3.3.3", true) {
|
||||
t.Error("after deleting one IP, new IP should be allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitDispatcher_SpeedBucket(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
|
||||
email1 := userEmail(1)
|
||||
email2 := userEmail(2)
|
||||
|
||||
speedLimits := map[string]int{email1: 10} // 10 Mbps
|
||||
ld.UpdateLimits(map[string]int{email1: 1, email2: 2}, nil, speedLimits)
|
||||
|
||||
// User 1 has speed limit — should get a limiter
|
||||
limiter := ld.getBucket(email1)
|
||||
if limiter == nil {
|
||||
t.Error("user with speed limit should get a limiter")
|
||||
}
|
||||
|
||||
// Same user should get the same limiter (cached)
|
||||
limiter2 := ld.getBucket(email1)
|
||||
if limiter != limiter2 {
|
||||
t.Error("same user should get cached limiter")
|
||||
}
|
||||
|
||||
// User 2 has no speed limit — should get nil
|
||||
limiter3 := ld.getBucket(email2)
|
||||
if limiter3 != nil {
|
||||
t.Error("user without speed limit should get nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitDispatcher_Snapshot(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
|
||||
// Add some connections
|
||||
ld.conns["conn-1"] = &dispatchedConn{
|
||||
id: "conn-1", email: "user@1", sourceIP: "1.1.1.1", userID: 1,
|
||||
}
|
||||
ld.conns["conn-2"] = &dispatchedConn{
|
||||
id: "conn-2", email: "user@2", sourceIP: "2.2.2.2", userID: 2,
|
||||
}
|
||||
ld.conns["conn-1"].upload.Store(1000)
|
||||
ld.conns["conn-1"].download.Store(2000)
|
||||
|
||||
snapshot := ld.Snapshot()
|
||||
if len(snapshot) != 2 {
|
||||
t.Fatalf("expected 2 connections, got %d", len(snapshot))
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, c := range snapshot {
|
||||
if c.ID == "conn-1" {
|
||||
found = true
|
||||
if c.UserID != 1 || c.SourceIP != "1.1.1.1" || c.Upload != 1000 || c.Download != 2000 {
|
||||
t.Errorf("unexpected connection data: %+v", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("conn-1 not found in snapshot")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitDispatcher_CloseConn(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
|
||||
email := userEmail(1)
|
||||
ld.userIPs[email] = map[string]int{"1.1.1.1": 1}
|
||||
ld.conns["conn-1"] = &dispatchedConn{
|
||||
id: "conn-1", email: email, sourceIP: "1.1.1.1", userID: 1,
|
||||
}
|
||||
|
||||
ok := ld.CloseConn("conn-1")
|
||||
if !ok {
|
||||
t.Error("CloseConn should return true for existing connection")
|
||||
}
|
||||
|
||||
if len(ld.conns) != 0 {
|
||||
t.Error("connection should be removed after close")
|
||||
}
|
||||
|
||||
ok = ld.CloseConn("nonexistent")
|
||||
if ok {
|
||||
t.Error("CloseConn should return false for nonexistent connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitDispatcher_ResetConns(t *testing.T) {
|
||||
ld := &LimitDispatcher{
|
||||
conns: make(map[string]*dispatchedConn),
|
||||
userIPs: make(map[string]map[string]int),
|
||||
}
|
||||
ld.conns["c1"] = &dispatchedConn{id: "c1"}
|
||||
ld.userIPs["user@1"] = map[string]int{"1.1.1.1": 1}
|
||||
|
||||
ld.ResetConns()
|
||||
|
||||
if len(ld.conns) != 0 {
|
||||
t.Error("conns should be empty after reset")
|
||||
}
|
||||
if len(ld.userIPs) != 0 {
|
||||
t.Error("userIPs should be empty after reset")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
xrayCore "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
"github.com/xtls/xray-core/infra/conf/serial"
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
_ "github.com/xtls/xray-core/main/distro/all"
|
||||
|
||||
"github.com/cedar2025/xboard-node/internal/config"
|
||||
"github.com/cedar2025/xboard-node/internal/kernel"
|
||||
"github.com/cedar2025/xboard-node/internal/kernel/geodata"
|
||||
"github.com/cedar2025/xboard-node/internal/panel"
|
||||
)
|
||||
|
||||
// drainTimeout is how long stop() waits for in-flight connections to finish
|
||||
// naturally before hard-killing the xray instance.
|
||||
const drainTimeout = 5 * time.Second
|
||||
|
||||
// Xray implements kernel.Kernel by embedding xray-core as a Go library.
|
||||
//
|
||||
// Device limits and speed limits are enforced through a custom dispatcher
|
||||
// wrapper (LimitDispatcher) that hooks into session.InboundFromContext(ctx)
|
||||
// — the same approach used by V2bX and XrayR. This works for ALL protocols
|
||||
// because the dispatcher is called AFTER the protocol handler has identified
|
||||
// the user and recorded the source IP in the session context.
|
||||
type Xray struct {
|
||||
cfg config.KernelConfig
|
||||
|
||||
mu sync.Mutex
|
||||
instance *xrayCore.Instance
|
||||
users []panel.User
|
||||
protocol string
|
||||
|
||||
inboundTag string
|
||||
|
||||
// limitDispatcher is the per-instance LimitDispatcher created during
|
||||
// xrayCore.New(). Stored here (instead of using the global pointer)
|
||||
// so that multi-node mode with multiple Xray instances works correctly.
|
||||
limitDispatcher *LimitDispatcher
|
||||
|
||||
// lastKernelHash caches a hash of the kernel-affecting config + user
|
||||
// identities. Used by Reload to skip unnecessary full restarts.
|
||||
lastKernelHash string
|
||||
|
||||
// cumTraffic keeps running totals for the aggregate stats fallback.
|
||||
cumTraffic map[int][2]int64
|
||||
}
|
||||
|
||||
func New(cfg config.KernelConfig) *Xray {
|
||||
return &Xray{
|
||||
cfg: cfg,
|
||||
cumTraffic: make(map[int][2]int64),
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Xray) Name() string { return "xray" }
|
||||
|
||||
func (x *Xray) ApplyConfig(nodeConfig *panel.NodeConfig, users []panel.User, certFile, keyFile string) error {
|
||||
x.mu.Lock()
|
||||
defer x.mu.Unlock()
|
||||
|
||||
// Auto-download geo databases and set XRAY_LOCATION_ASSET when panel
|
||||
// routes reference geoip:/geosite: entries.
|
||||
if kernel.NeedsGeoIP(nodeConfig.Routes) || kernel.NeedsGeoSite(nodeConfig.Routes) {
|
||||
geoDataDir := x.cfg.GeoDataDir
|
||||
if err := geodata.Ensure(geoDataDir,
|
||||
kernel.NeedsGeoIP(nodeConfig.Routes),
|
||||
kernel.NeedsGeoSite(nodeConfig.Routes),
|
||||
"xray",
|
||||
); err != nil {
|
||||
slog.Warn("geo database unavailable; geoip/geosite rules may not match", "error", err)
|
||||
}
|
||||
os.Setenv("XRAY_LOCATION_ASSET", geoDataDir)
|
||||
}
|
||||
|
||||
cfgMap := buildConfig(x.cfg, nodeConfig, users, certFile, keyFile)
|
||||
data, err := json.Marshal(cfgMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal config: %w", err)
|
||||
}
|
||||
|
||||
slog.Debug("xray config generated", "len", len(data))
|
||||
|
||||
pbConfig, err := serial.LoadJSONConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse xray config: %w", err)
|
||||
}
|
||||
|
||||
x.stop()
|
||||
|
||||
// Hold the global creation mutex around xrayCore.New() + capture so that
|
||||
// concurrent Xray instances (multi-node) don't clobber each other's
|
||||
// LimitDispatcher reference.
|
||||
xrayCreationMu.Lock()
|
||||
instance, err := xrayCore.New(pbConfig)
|
||||
if err != nil {
|
||||
xrayCreationMu.Unlock()
|
||||
return fmt.Errorf("create xray instance: %w", err)
|
||||
}
|
||||
x.limitDispatcher = globalLimitDispatcher.Load()
|
||||
xrayCreationMu.Unlock()
|
||||
|
||||
if err := instance.Start(); err != nil {
|
||||
instance.Close()
|
||||
return fmt.Errorf("start xray: %w", err)
|
||||
}
|
||||
|
||||
x.instance = instance
|
||||
x.users = users
|
||||
x.protocol = nodeConfig.Protocol
|
||||
x.inboundTag = nodeConfig.Protocol + "-in"
|
||||
x.cumTraffic = make(map[int][2]int64)
|
||||
x.lastKernelHash = computeKernelHash(nodeConfig, users)
|
||||
|
||||
// Configure the limit dispatcher with user limits
|
||||
x.updateDispatcherLimits(users)
|
||||
|
||||
slog.Info("xray started (in-process)",
|
||||
"users", len(users),
|
||||
"protocol", nodeConfig.Protocol,
|
||||
"device_limits", "enabled (all protocols via dispatcher hook)",
|
||||
"speed_limits", "enabled (all protocols via dispatcher hook)",
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Xray) Reload(nodeConfig *panel.NodeConfig, users []panel.User, certFile, keyFile string) error {
|
||||
// Always update dispatcher limits (instant, no restart).
|
||||
x.updateDispatcherLimits(users)
|
||||
|
||||
// Skip full restart if kernel-affecting fields are unchanged.
|
||||
// This covers user-only limit changes where identities (ID, UUID) and
|
||||
// config (routes, protocol settings, port) haven't changed.
|
||||
newHash := computeKernelHash(nodeConfig, users)
|
||||
x.mu.Lock()
|
||||
same := x.lastKernelHash == newHash
|
||||
x.mu.Unlock()
|
||||
if same {
|
||||
x.mu.Lock()
|
||||
x.users = users
|
||||
x.mu.Unlock()
|
||||
slog.Info("xray: config/users unchanged, limits updated without restart")
|
||||
return nil
|
||||
}
|
||||
|
||||
return x.ApplyConfig(nodeConfig, users, certFile, keyFile)
|
||||
}
|
||||
|
||||
func (x *Xray) Stop() {
|
||||
x.mu.Lock()
|
||||
defer x.mu.Unlock()
|
||||
x.stop()
|
||||
}
|
||||
|
||||
func (x *Xray) stop() {
|
||||
if x.instance != nil {
|
||||
// Drain: wait for in-flight connections to finish naturally.
|
||||
if x.limitDispatcher != nil {
|
||||
deadline := time.Now().Add(drainTimeout)
|
||||
for time.Now().Before(deadline) {
|
||||
x.limitDispatcher.mu.RLock()
|
||||
n := len(x.limitDispatcher.conns)
|
||||
x.limitDispatcher.mu.RUnlock()
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
x.instance.Close()
|
||||
x.instance = nil
|
||||
}
|
||||
if x.limitDispatcher != nil {
|
||||
x.limitDispatcher.ResetConns()
|
||||
x.limitDispatcher = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Xray) IsRunning() bool {
|
||||
x.mu.Lock()
|
||||
defer x.mu.Unlock()
|
||||
return x.instance != nil
|
||||
}
|
||||
|
||||
// GetConnections returns per-connection data from the dispatcher.
|
||||
// Each connection has a real source IP and user ID, enabling device limit
|
||||
// enforcement by the upper-layer limiter.
|
||||
func (x *Xray) GetConnections(ctx context.Context) ([]kernel.Connection, error) {
|
||||
x.mu.Lock()
|
||||
defer x.mu.Unlock()
|
||||
|
||||
if x.instance == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Primary: use LimitDispatcher's per-connection tracking
|
||||
if x.limitDispatcher != nil {
|
||||
conns := x.limitDispatcher.Snapshot()
|
||||
if len(conns) > 0 {
|
||||
return conns, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: aggregate stats (for edge cases)
|
||||
return x.getAggregateStats()
|
||||
}
|
||||
|
||||
func (x *Xray) getAggregateStats() ([]kernel.Connection, error) {
|
||||
sm := x.instance.GetFeature(stats.ManagerType())
|
||||
if sm == nil {
|
||||
return nil, nil
|
||||
}
|
||||
statsManager, ok := sm.(stats.Manager)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var conns []kernel.Connection
|
||||
for _, u := range x.users {
|
||||
email := userEmail(u.ID)
|
||||
|
||||
var deltaUp, deltaDown int64
|
||||
if c := statsManager.GetCounter(fmt.Sprintf("user>>>%s>>>traffic>>>uplink", email)); c != nil {
|
||||
deltaUp = c.Set(0)
|
||||
}
|
||||
if c := statsManager.GetCounter(fmt.Sprintf("user>>>%s>>>traffic>>>downlink", email)); c != nil {
|
||||
deltaDown = c.Set(0)
|
||||
}
|
||||
|
||||
if deltaUp > 0 || deltaDown > 0 {
|
||||
cum := x.cumTraffic[u.ID]
|
||||
cum[0] += deltaUp
|
||||
cum[1] += deltaDown
|
||||
x.cumTraffic[u.ID] = cum
|
||||
}
|
||||
|
||||
cum := x.cumTraffic[u.ID]
|
||||
if cum[0] > 0 || cum[1] > 0 {
|
||||
conns = append(conns, kernel.Connection{
|
||||
ID: fmt.Sprintf("xray-%d", u.ID),
|
||||
UserID: u.ID,
|
||||
Upload: cum[0],
|
||||
Download: cum[1],
|
||||
})
|
||||
}
|
||||
}
|
||||
return conns, nil
|
||||
}
|
||||
|
||||
func (x *Xray) CloseConnection(_ context.Context, connID string) error {
|
||||
x.mu.Lock()
|
||||
ld := x.limitDispatcher
|
||||
x.mu.Unlock()
|
||||
if ld != nil {
|
||||
ld.CloseConn(connID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Xray) SetSpeedLimitFunc(_ func(string) *rate.Limiter) {}
|
||||
|
||||
var _ kernel.Kernel = (*Xray)(nil)
|
||||
|
||||
// updateDispatcherLimits configures the global LimitDispatcher with
|
||||
// per-user device limits and speed limits.
|
||||
func (x *Xray) updateDispatcherLimits(users []panel.User) {
|
||||
x.mu.Lock()
|
||||
ld := x.limitDispatcher
|
||||
x.mu.Unlock()
|
||||
if ld == nil {
|
||||
return
|
||||
}
|
||||
|
||||
emailToUID := make(map[string]int, len(users))
|
||||
deviceLimits := make(map[string]int)
|
||||
speedLimits := make(map[string]int)
|
||||
|
||||
for _, u := range users {
|
||||
email := userEmail(u.ID)
|
||||
emailToUID[email] = u.ID
|
||||
// SOCKS/HTTP protocols use the raw UUID as User.Email in xray's session,
|
||||
// while VMess/VLESS/Trojan use the "user@<id>" format. Map both so that
|
||||
// limits work for all protocols.
|
||||
emailToUID[u.UUID] = u.ID
|
||||
if u.DeviceLimit > 0 {
|
||||
deviceLimits[email] = u.DeviceLimit
|
||||
deviceLimits[u.UUID] = u.DeviceLimit
|
||||
}
|
||||
if u.SpeedLimit > 0 {
|
||||
speedLimits[email] = u.SpeedLimit
|
||||
speedLimits[u.UUID] = u.SpeedLimit
|
||||
}
|
||||
}
|
||||
|
||||
ld.UpdateLimits(emailToUID, deviceLimits, speedLimits)
|
||||
}
|
||||
|
||||
// xrayCreationMu serialises xrayCore.New() + globalLimitDispatcher capture
|
||||
// so that concurrent Xray instances in multi-node mode each capture their
|
||||
// own LimitDispatcher.
|
||||
var xrayCreationMu sync.Mutex
|
||||
|
||||
// computeKernelHash returns a hash of the config + user identities (ID, UUID)
|
||||
// that would require a kernel restart if changed. Limit-only changes are
|
||||
// excluded so they can be applied without restart.
|
||||
func computeKernelHash(nc *panel.NodeConfig, users []panel.User) string {
|
||||
h := sha256.New()
|
||||
configData, _ := json.Marshal(nc)
|
||||
h.Write(configData)
|
||||
sorted := make([]panel.User, len(users))
|
||||
copy(sorted, users)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i].ID < sorted[j].ID })
|
||||
for _, u := range sorted {
|
||||
fmt.Fprintf(h, "%d:%s,", u.ID, u.UUID)
|
||||
}
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
Reference in New Issue
Block a user