Feature/tuic v5 (#6337)

* Feat(tuic): Implement native TUIC v5 protocol support via Rust sidecar daemon

- Add internal/tuic package for official tuic-server sidecar lifecycle management, configuration generation, and graceful process control
- Bridge decrypted TUIC QUIC traffic into loopback Xray SOCKS5 inbounds (63200+id) for traffic accounting, statistics, and routing rules
- Implement periodic reconciliation job (cadence @every 10s) and immediate runtime synchronization on inbound/client mutations
- Add TUIC inbound & multi-user client settings (UUID + Password authentication) in Web UI with SNI auto-fill and panel certificate loader
- Integrate tuic:// subscription links and Clash.Meta (Mihomo) proxy generation for TUIC
- Update install.sh to automatically download and install official tuic-server release for x86_64, aarch64, and armv7
- Add full localization for TUIC protocol across all 13 supported languages

* Feat(install): Support custom repository and branch in install and update scripts

* Ci(release): Enable publish-dev for feature branch and workflow dispatch

* Feat(sub): Add TUIC to subscription resolution and client QR config generator

- Add 'tuic' to getInboundsBySubId SQL allowlist to resolve TUIC inbounds in subscriptions and sub links
- Enhance buildTuicProxy in Clash subscription generator with robust host and credentials resolution
- Add tuicConfig.ts to generate standalone Clash/Mihomo YAML configuration
- Add dedicated TUIC Config tab in ClientQrModal with QR code and .yaml download button
- Add localization keys for TUIC config across all 13 supported languages

* Fix(tuic): Exclude TUIC from native Xray inbounds and strip udp_relay_mode from server config

- Exclude model.TUIC from native Xray inbounds in GetXrayConfig to prevent Xray startup failure
- Remove udp_relay_mode from tuic-server JSON configuration builder
- Update install.sh to install tuic-server binary to both xui_folder/bin and /usr/local/bin

* Fix(install): Fallback to dev-latest when releases/latest is not present on fork

* Feat(tuic): Add real-time online status and LastOnline tracking for TUIC clients

- Track client activity by mapping client UUID in tuic-server logs to email
- Integrate TUIC active clients into XrayTrafficJob to refresh local online clients
- Bump LastOnline timestamp in database and broadcast live online status over WebSocket

* Feat(tuic): Implement real-time traffic statistics and live speed reporting for TUIC

- Collect precise I/O traffic deltas for tuic-server child processes via /proc/<pid>/io
- Aggregate and attribute TUIC traffic deltas per client in tuic Manager
- Integrate TUIC traffic deltas into XrayTrafficJob to update database and broadcast live speed

* Feat(tuic): Finalize TUIC v5 integration with 1:1 traffic counting and orphan process cleanup
- Use exact 1:1 byte delta accounting from /proc/<pid>/io
- Add killStrayTuicProcesses to terminate orphan sidecars on panel startup
- Fully integrate TUIC with subscriptions, live speed meter, and all 13 locales

* Feat(frontend): Polish TUIC UI, support bulk operations, and update translations

- Align TUIC inbound certificate form with standard 3X-UI layout (Set Default Cert, Clear)
- Remove extra subtitle hint text from TUIC inbound form fields
- Support TUIC in client bulk attach/detach and bulk add modals
- Add TUIC badge color to client info modal, clients table, and host list
- Update password tooltip across all 13 locales to include TUIC
- Remove obsolete dead translation keys across all 13 locales

* Chore(ci): Finalize TUIC v5 bundling across release workflow, Docker, and scripts

* Feat(openapi): Update OpenAPI generator and schemas for TUIC types

* Fix(backend): Address core review findings for TUIC types, port checks, and xray bridge

* Refactor(traffic): Isolate proc reading with build tags and decouple TUIC metering into TuicJob

* Feat(client): Add TuicServer to InboundOption, fix config export and clean share links

* Fix(frontend): Register TUIC in multi-user helpers, tracked protocols, and tag derivation

* Chore(openapi): Re-generate OpenAPI specification and sync Zod schemas

* Chore(scripts): Add Alpine musl binaries, 386 and Windows packaging, and anchor pkill

* Fix(review): Remove stale import, correct binary names, switch to musl, and drop unreachable relay gate

* Feat(frontend): Show share link in Inbound Info and display UDP tag for TUIC

* Docs: Add TUIC v5 configuration guide and link specifications

* Docs(tuic): Correct Clash Meta configuration parameter to reduce-rtt

* Fix(tuic): Generate client credentials on copy, enforce ID/password validation, and add i386 to DockerInit

* Fix(tuic): drop unused relay, fix traffic accounting, and honor host endpoints

- Drop unused loopback SOCKS relay and eliminate port collision with AmneziaWG
- Correct inbound traffic calculation without double-counting
- Drop heuristic client traffic division while retaining online tracking
- Support externalProxy host fan-out and conditional parameters in share links
- Scope orphan process termination to managed config directory

* Fix(tuic): enforce client quotas, decouple Xray restart, and sync openapi schemas

- Regenerate OpenAPI, Zod schemas, and TypeScript types without route_through_xray
- Populate clientTraffics in TuicJob to enforce client quotas and first-use expiry
- Split process I/O delta into up and down in Process.CollectTraffic
- Remove SetNeedRestart from updateTuicInbound to prevent Xray session drops
- Use InstanceFromInbound for default ALPN and UDP relay mode in tuic:// share links
- Support allow_insecure on externalProxy host endpoints without parameter collision

* Fix(tuic): attribute client traffic only on single-user inbounds and sync link defaults

- Attribute I/O deltas to the client only when the inbound has exactly one configured client, avoiding false billing and disablings on multi-user inbounds
- Aggregate client traffic by email in TuicJob so clients on multiple inbounds don't lose deltas
- Match frontend genTuicLink defaults for alpn and udp_relay_mode with backend subscription links

* Fix(tuic): gate client traffic by total sidecar clients and require client email

* Fix(tuic): enforce inbound-only traffic limits and disable client totalGB

* fix(tuic): restore delayed start, remove client totalGB rejection, and document linux-only limits

* fix(tuic): anchor pkill, fix io baseline/split, escape yaml, and deduplicate start errors

* fix(tuic): prevent traffic double-counting, ensure info log level for delayed start, and broaden pkill matching

* fix(tuic): address review round 11 findings

- internal/sub/json_service: skip tuic protocol in json subscription to prevent direct routing leak
- internal/sub/clash_service: honor externalProxy/host row allowInsecure, sni, and alpn in buildTuicProxy
- internal/web/runtime: decouple tuic inbound add/delete from xray restart
- internal/tuic/config: restore user log-level options (warn, error) without forced info clamp
- frontend/src/lib/xray/inbound-link: fix duplicate remark suffix and apply externalProxy TLS overrides
- frontend/src/schemas/protocols/stream/external-proxy: propagate allowInsecure through host mapping
- tests: add coverage for json sub skip, clash proxy overrides, and link generation

* fix(tuic): meter inbound traffic through a UDP relay and bracket IPv6 binds

Review repairs on the TUIC v5 sidecar integration:

- Inbound traffic was read from the sidecar's /proc/<pid>/io rchar, but
  the kernel only counts read()/write() there and tuic-server moves its
  sockets with recvfrom/recvmmsg/sendmmsg/sendto, so an inbound's up/down
  stayed at 0 forever and inbound total limits never tripped (measured:
  12 MiB relayed, rchar delta 0). The panel now owns the inbound's public
  UDP port with a small relay and runs tuic-server behind it on a loopback
  port, counting up/down exactly on every OS. tuic-server therefore logs
  127.0.0.1 as every client's address; per-client attribution stays
  unsupported since QUIC is opaque.
- Instance.BindTo formatted an IPv6 listen address as ":::8443", which
  tuic-server rejects with "invalid socket address syntax", so an inbound
  listening on "::" or any IPv6 literal never started. It now uses
  net.JoinHostPort; IPv4 output is unchanged.
- The log level is passed to the sidecar as chosen. Online status,
  last-online and delayed start are read from its Info lines, so the Log
  Level field now says that Warn and Error switch them off for the
  inbound, and the docs say the same.
- Drop two frontend tests that only exercised a getter and a set lookup,
  and strip the trailing blank line that made gofumpt fail on two of the
  new Go test files.

* fix(tuic): harden tag updates, runtime routing, and relay stability

---------

Co-authored-by: poise52 <equipoise52@gmail.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
amae
2026-09-12 13:15:48 +05:00
committed by GitHub
parent 0a2cd789ba
commit 6d96accd63
100 changed files with 4139 additions and 52 deletions
+94
View File
@@ -0,0 +1,94 @@
package tuic
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/mhsanaei/3x-ui/v3/internal/config"
)
type ServerConfig struct {
Server string `json:"server"`
Users map[string]string `json:"users"`
Certificate string `json:"certificate"`
PrivateKey string `json:"private_key"`
CongestionControl string `json:"congestion_control"`
ALPN []string `json:"alpn"`
ZeroRTTHandshake bool `json:"zero_rtt_handshake"`
LogLevel string `json:"log_level"`
MaxIdleTime string `json:"max_idle_time,omitempty"`
AuthTimeout string `json:"auth_timeout,omitempty"`
MaxExternalPacketSize int `json:"max_external_packet_size,omitempty"`
}
// bind is where the sidecar itself listens: a loopback port behind the
// panel's relay, never the inbound's public address (see udpRelay).
func GenerateConfig(inst Instance, bind string) ([]byte, error) {
users := make(map[string]string, len(inst.Clients))
for _, c := range inst.Clients {
if c.UUID != "" && c.Password != "" {
users[c.UUID] = c.Password
}
}
authTimeoutStr := ""
if inst.AuthenticationTimeout > 0 {
authTimeoutStr = fmt.Sprintf("%ds", inst.AuthenticationTimeout)
}
maxIdleStr := ""
if inst.MaxIdleTime > 0 {
maxIdleStr = fmt.Sprintf("%ds", inst.MaxIdleTime)
}
logLevel := inst.LogLevel
if logLevel == "" {
logLevel = "info"
}
cfg := ServerConfig{
Server: bind,
Users: users,
Certificate: inst.Certificate,
PrivateKey: inst.PrivateKey,
CongestionControl: inst.CongestionControl,
ALPN: inst.ALPN,
ZeroRTTHandshake: inst.ZeroRTTHandshake,
LogLevel: logLevel,
AuthTimeout: authTimeoutStr,
MaxIdleTime: maxIdleStr,
MaxExternalPacketSize: inst.MaxUdpRelayPacketSize,
}
return json.MarshalIndent(cfg, "", " ")
}
func ConfigDir() string {
return filepath.Join(config.GetBinFolderPath(), "tuic")
}
func ConfigPathForID(id int) string {
return filepath.Join(ConfigDir(), fmt.Sprintf("tuic_%d.json", id))
}
func WriteConfigFile(id int, data []byte) (string, error) {
dir := ConfigDir()
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
path := ConfigPathForID(id)
if err := os.WriteFile(path, data, 0o600); err != nil {
return "", err
}
return path, nil
}
func RemoveConfigFile(id int) error {
path := ConfigPathForID(id)
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
+87
View File
@@ -0,0 +1,87 @@
package tuic
import (
"encoding/json"
"testing"
)
func TestGenerateConfig(t *testing.T) {
inst := Instance{
Id: 1,
Port: 8443,
Listen: "0.0.0.0",
Certificate: "/etc/ssl/cert.pem",
PrivateKey: "/etc/ssl/key.pem",
CongestionControl: "bbr",
ALPN: []string{"h3", "spdy/3.1"},
UDPRelayMode: "native",
ZeroRTTHandshake: true,
LogLevel: "info",
MaxIdleTime: 15,
AuthenticationTimeout: 3,
MaxUdpRelayPacketSize: 1500,
Clients: []TuicClientSettings{
{UUID: "uuid-1", Password: "pass-1", Email: "e1"},
{UUID: "uuid-2", Password: "pass-2", Email: "e2"},
},
}
data, err := GenerateConfig(inst, "127.0.0.1:4433")
if err != nil {
t.Fatalf("GenerateConfig error: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(data, &parsed); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if parsed["server"] != "127.0.0.1:4433" {
t.Fatalf("expected the sidecar bound to the relay's loopback port, got %v", parsed["server"])
}
if parsed["certificate"] != "/etc/ssl/cert.pem" || parsed["private_key"] != "/etc/ssl/key.pem" {
t.Fatalf("unexpected cert/key in json: %v", parsed)
}
users, ok := parsed["users"].(map[string]any)
if !ok {
t.Fatalf("expected users map, got %T", parsed["users"])
}
if users["uuid-1"] != "pass-1" || users["uuid-2"] != "pass-2" {
t.Fatalf("unexpected users in json: %v", users)
}
}
func TestGenerateConfigLogLevel(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"info", "info"},
{"warn", "warn"},
{"error", "error"},
{"", "info"},
{"debug", "debug"},
{"trace", "trace"},
}
for _, tc := range tests {
inst := Instance{
Id: 1,
Port: 8443,
Listen: "0.0.0.0",
LogLevel: tc.input,
}
data, err := GenerateConfig(inst, "127.0.0.1:4433")
if err != nil {
t.Fatalf("GenerateConfig error for %s: %v", tc.input, err)
}
var parsed map[string]any
if err := json.Unmarshal(data, &parsed); err != nil {
t.Fatalf("Unmarshal error for %s: %v", tc.input, err)
}
if parsed["log_level"] != tc.expected {
t.Fatalf("expected log_level %s for input %s, got %v", tc.expected, tc.input, parsed["log_level"])
}
}
}
+231
View File
@@ -0,0 +1,231 @@
package tuic
import (
"fmt"
"net"
"strconv"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
)
type managed struct {
proc *Process
relay *udpRelay
tag string
configPath string
structuralFP string
usersFP string
}
type Manager struct {
mu sync.Mutex
procs map[int]*managed
lastStartErr map[int]string
}
var (
managerInstance *Manager
managerOnce sync.Once
)
func GetManager() *Manager {
managerOnce.Do(func() {
managerInstance = &Manager{
procs: make(map[int]*managed),
lastStartErr: make(map[int]string),
}
if n := killStrayTuicProcesses(GetBinaryPath()); n > 0 {
logger.Warningf("tuic: terminated %d orphaned tuic-server process(es) from a previous run", n)
}
})
return managerInstance
}
func (m *Manager) HasRunning() bool {
m.mu.Lock()
defer m.mu.Unlock()
for _, mg := range m.procs {
if mg.proc != nil && mg.proc.IsRunning() {
return true
}
}
return false
}
func (m *Manager) Ensure(inst Instance) error {
m.mu.Lock()
defer m.mu.Unlock()
return m.ensureLocked(inst)
}
func (m *Manager) ensureLocked(inst Instance) error {
if len(inst.Clients) == 0 {
m.removeLocked(inst.Id)
return nil
}
structuralFP := inst.StructuralFingerprint()
usersFP := inst.UsersFingerprint()
uuidToEmail := make(map[string]string, len(inst.Clients))
for _, c := range inst.Clients {
if c.UUID != "" && c.Email != "" {
uuidToEmail[c.UUID] = c.Email
}
}
if existing, ok := m.procs[inst.Id]; ok && existing != nil {
if existing.proc != nil && existing.proc.IsRunning() &&
existing.structuralFP == structuralFP && existing.usersFP == usersFP {
existing.tag = inst.Tag
existing.proc.UpdateClients(uuidToEmail)
return nil
}
stopManaged(existing)
delete(m.procs, inst.Id)
}
proc, relay, configPath, err := m.startLocked(inst, uuidToEmail)
if err != nil {
if m.lastStartErr[inst.Id] != err.Error() {
m.lastStartErr[inst.Id] = err.Error()
logger.Warningf("tuic: failed to start tuic-server for inbound %d (%s): %v", inst.Id, inst.Tag, err)
}
return err
}
delete(m.lastStartErr, inst.Id)
m.procs[inst.Id] = &managed{
proc: proc,
relay: relay,
tag: inst.Tag,
configPath: configPath,
structuralFP: structuralFP,
usersFP: usersFP,
}
return nil
}
func (m *Manager) startLocked(inst Instance, uuidToEmail map[string]string) (*Process, *udpRelay, string, error) {
port, err := freeLoopbackUDPPort()
if err != nil {
return nil, nil, "", fmt.Errorf("tuic: pick sidecar port for %d: %w", inst.Id, err)
}
upstream := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port}
configBytes, err := GenerateConfig(inst, net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
if err != nil {
return nil, nil, "", fmt.Errorf("tuic: generate config for %d: %w", inst.Id, err)
}
configPath, err := WriteConfigFile(inst.Id, configBytes)
if err != nil {
return nil, nil, "", fmt.Errorf("tuic: write config for %d: %w", inst.Id, err)
}
relay, err := startUDPRelay(inst.BindTo(), upstream, relayFlowIdle)
if err != nil {
_ = RemoveConfigFile(inst.Id)
return nil, nil, "", fmt.Errorf("tuic: listen on %s for %d: %w", inst.BindTo(), inst.Id, err)
}
proc := newProcess(configPath, inst.Tag, uuidToEmail)
if err := proc.Start(); err != nil {
relay.Close()
_ = RemoveConfigFile(inst.Id)
return nil, nil, "", err
}
return proc, relay, configPath, nil
}
func stopManaged(mg *managed) {
if mg.proc != nil && mg.proc.IsRunning() {
_ = mg.proc.Stop()
}
mg.relay.Close()
}
func (m *Manager) GetActiveClients(window time.Duration) ([]string, []string) {
m.mu.Lock()
defer m.mu.Unlock()
var emails []string
var tags []string
for _, mg := range m.procs {
if mg.proc != nil && mg.proc.IsRunning() {
active := mg.proc.GetActiveEmails(window)
if len(active) > 0 {
emails = append(emails, active...)
tags = append(tags, mg.tag)
}
}
}
return emails, tags
}
type InboundTrafficDelta struct {
Tag string
Up int64
Down int64
}
func (m *Manager) CollectTraffic() []InboundTrafficDelta {
m.mu.Lock()
defer m.mu.Unlock()
var out []InboundTrafficDelta
for _, mg := range m.procs {
if mg.relay != nil && mg.proc != nil && mg.proc.IsRunning() {
deltaUp, deltaDown := mg.relay.CollectTraffic()
if deltaUp > 0 || deltaDown > 0 {
out = append(out, InboundTrafficDelta{
Tag: mg.tag,
Up: deltaUp,
Down: deltaDown,
})
}
}
}
return out
}
func (m *Manager) Remove(id int) {
m.mu.Lock()
defer m.mu.Unlock()
m.removeLocked(id)
}
func (m *Manager) removeLocked(id int) {
if existing, ok := m.procs[id]; ok && existing != nil {
stopManaged(existing)
_ = RemoveConfigFile(id)
delete(m.procs, id)
delete(m.lastStartErr, id)
}
}
func (m *Manager) Reconcile(desired []Instance) {
m.mu.Lock()
defer m.mu.Unlock()
desiredMap := make(map[int]Instance, len(desired))
for _, inst := range desired {
desiredMap[inst.Id] = inst
}
for id := range m.procs {
if _, ok := desiredMap[id]; !ok {
m.removeLocked(id)
}
}
for _, inst := range desired {
_ = m.ensureLocked(inst)
}
}
func (m *Manager) StopAll() {
m.mu.Lock()
defer m.mu.Unlock()
for id, mg := range m.procs {
stopManaged(mg)
_ = RemoveConfigFile(id)
}
m.procs = make(map[int]*managed)
}
+95
View File
@@ -0,0 +1,95 @@
package tuic
import (
"encoding/json"
"net"
"os"
"path/filepath"
"runtime"
"testing"
)
func TestEnsureFrontsSidecarWithRelayAndRemoveReleasesPort(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a shell script as the sidecar binary")
}
bin := t.TempDir()
t.Setenv("XUI_BIN_FOLDER", bin)
if err := os.WriteFile(filepath.Join(bin, GetBinaryName()), []byte("#!/bin/sh\nexec sleep 300\n"), 0o755); err != nil {
t.Fatal(err)
}
port, err := freeLoopbackUDPPort()
if err != nil {
t.Fatal(err)
}
inst := Instance{
Id: 7, Tag: "tuic-7", Listen: "127.0.0.1", Port: port,
Clients: []TuicClientSettings{{UUID: "u", Password: "p", Email: "e"}},
}
m := &Manager{procs: map[int]*managed{}, lastStartErr: map[int]string{}}
t.Cleanup(m.StopAll)
if err := m.Ensure(inst); err != nil {
t.Fatalf("Ensure: %v", err)
}
if c, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port}); err == nil {
_ = c.Close()
t.Fatal("the relay must own the inbound's public port while the sidecar runs")
}
raw, err := os.ReadFile(ConfigPathForID(7))
if err != nil {
t.Fatal(err)
}
var cfg struct {
Server string `json:"server"`
}
if err := json.Unmarshal(raw, &cfg); err != nil {
t.Fatal(err)
}
host, sidecarPort, err := net.SplitHostPort(cfg.Server)
if err != nil || host != "127.0.0.1" || sidecarPort == "" || cfg.Server == inst.BindTo() {
t.Fatalf("sidecar bound to %q, want a loopback port other than the public %q", cfg.Server, inst.BindTo())
}
m.Remove(7)
c, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
if err != nil {
t.Fatalf("public port still held after Remove: %v", err)
}
_ = c.Close()
}
func TestEnsureUpdatesTagWithoutRestart(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a shell script as the sidecar binary")
}
bin := t.TempDir()
t.Setenv("XUI_BIN_FOLDER", bin)
if err := os.WriteFile(filepath.Join(bin, GetBinaryName()), []byte("#!/bin/sh\nexec sleep 300\n"), 0o755); err != nil {
t.Fatal(err)
}
port, err := freeLoopbackUDPPort()
if err != nil {
t.Fatal(err)
}
inst := Instance{
Id: 8, Tag: "old-tag", Listen: "127.0.0.1", Port: port,
Clients: []TuicClientSettings{{UUID: "u", Password: "p", Email: "e"}},
}
m := &Manager{procs: map[int]*managed{}, lastStartErr: map[int]string{}}
t.Cleanup(m.StopAll)
if err := m.Ensure(inst); err != nil {
t.Fatalf("Ensure: %v", err)
}
inst.Tag = "new-tag"
if err := m.Ensure(inst); err != nil {
t.Fatalf("Ensure updated tag: %v", err)
}
m.mu.Lock()
gotTag := m.procs[8].tag
m.mu.Unlock()
if gotTag != "new-tag" {
t.Fatalf("manager tag = %q, want %q", gotTag, "new-tag")
}
}
+87
View File
@@ -0,0 +1,87 @@
//go:build linux
package tuic
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
func killStrayTuicProcesses(binaryPath string) int {
base := filepath.Base(binaryPath)
if base == "" || base == "." || base == string(filepath.Separator) {
return 0
}
configDir := filepath.Clean(ConfigDir())
self := os.Getpid()
entries, err := os.ReadDir("/proc")
if err != nil {
return 0
}
killed := 0
for _, e := range entries {
pid, err := strconv.Atoi(e.Name())
if err != nil || pid == self {
continue
}
if procExeBase(pid) != base && cmdlineArgv0Base(pid) != base {
continue
}
if !isManagedTuicCmdline(pid, configDir) {
continue
}
if err := syscall.Kill(pid, syscall.SIGTERM); err == nil {
killed++
time.Sleep(50 * time.Millisecond)
if err := syscall.Kill(pid, 0); err == nil {
_ = syscall.Kill(pid, syscall.SIGKILL)
}
}
}
return killed
}
func isManagedTuicCmdline(pid int, configDir string) bool {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
if err != nil || len(data) == 0 {
return false
}
args := strings.Split(string(data), "\x00")
for i, arg := range args {
if arg == "-c" && i+1 < len(args) {
cfg := filepath.Clean(args[i+1])
if strings.HasPrefix(cfg, configDir) {
return true
}
}
}
return false
}
func procExeBase(pid int) string {
exe, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
if err != nil {
return ""
}
return filepath.Base(exe)
}
func cmdlineArgv0Base(pid int) string {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
if err != nil || len(data) == 0 {
return ""
}
first := data
for i, b := range data {
if b == 0 {
first = data[:i]
break
}
}
return filepath.Base(string(first))
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !linux
package tuic
func killStrayTuicProcesses(_ string) int { return 0 }
+292
View File
@@ -0,0 +1,292 @@
package tuic
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
)
func GetBinaryName() string {
name := fmt.Sprintf("tuic-server-%s-%s", runtime.GOOS, runtime.GOARCH)
if runtime.GOOS == "windows" {
name += ".exe"
}
return name
}
func GetBinaryPath() string {
custom := filepath.Join(config.GetBinFolderPath(), GetBinaryName())
if _, err := os.Stat(custom); err == nil {
return custom
}
binTuic := filepath.Join(config.GetBinFolderPath(), "tuic-server")
if runtime.GOOS == "windows" {
binTuic += ".exe"
}
if _, err := os.Stat(binTuic); err == nil {
return binTuic
}
for _, p := range []string{"/usr/local/bin/tuic-server", "/usr/bin/tuic-server"} {
if _, err := os.Stat(p); err == nil {
return p
}
}
if path, err := exec.LookPath("tuic-server"); err == nil {
return path
}
return binTuic
}
var (
gracefulStopTimeout = 5 * time.Second
forceStopTimeout = 2 * time.Second
)
type procLogWriter struct {
mu sync.Mutex
label string
buf string
lastLine string
uuidToEmail map[string]string
lastActive map[string]int64
}
func (w *procLogWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
w.buf += string(p)
for {
i := strings.IndexByte(w.buf, '\n')
if i < 0 {
break
}
line := w.buf[:i]
w.buf = w.buf[i+1:]
w.emitLocked(line)
}
return len(p), nil
}
func (w *procLogWriter) Flush() {
w.mu.Lock()
defer w.mu.Unlock()
if w.buf != "" {
line := w.buf
w.buf = ""
w.emitLocked(line)
}
}
func (w *procLogWriter) emitLocked(line string) {
trimmed := strings.TrimSpace(strings.TrimRight(line, "\r"))
if trimmed == "" {
return
}
w.lastLine = trimmed
logger.Infof("tuic: tuic-server %s | %s", w.label, trimmed)
now := time.Now().UnixMilli()
lowerLine := strings.ToLower(line)
for uuid, email := range w.uuidToEmail {
if strings.Contains(lowerLine, uuid) {
if w.lastActive == nil {
w.lastActive = make(map[string]int64)
}
w.lastActive[email] = now
}
}
}
func (w *procLogWriter) LastLine() string {
w.mu.Lock()
defer w.mu.Unlock()
return w.lastLine
}
type Process struct {
mu sync.RWMutex
cmd *exec.Cmd
done chan struct{}
configPath string
logWriter *procLogWriter
exitErr error
intentionalStop atomic.Bool
}
func newProcess(configPath, label string, uuidToEmail map[string]string) *Process {
return &Process{
configPath: configPath,
logWriter: &procLogWriter{
label: label,
uuidToEmail: uuidToEmail,
lastActive: make(map[string]int64),
},
}
}
func (p *Process) GetActiveEmails(window time.Duration) []string {
if p == nil || p.logWriter == nil {
return nil
}
p.logWriter.mu.Lock()
defer p.logWriter.mu.Unlock()
cutoff := time.Now().Add(-window).UnixMilli()
var active []string
for email, last := range p.logWriter.lastActive {
if last >= cutoff {
active = append(active, email)
}
}
return active
}
func (p *Process) UpdateClients(uuidToEmail map[string]string) {
if p == nil || p.logWriter == nil {
return
}
p.logWriter.mu.Lock()
defer p.logWriter.mu.Unlock()
p.logWriter.uuidToEmail = uuidToEmail
}
func (p *Process) IsRunning() bool {
p.mu.RLock()
cmd, done := p.cmd, p.done
p.mu.RUnlock()
if cmd == nil || cmd.Process == nil {
return false
}
if done != nil {
select {
case <-done:
return false
default:
}
}
return true
}
func (p *Process) GetResult() string {
if line := p.logWriter.LastLine(); line != "" {
return line
}
p.mu.RLock()
exitErr := p.exitErr
p.mu.RUnlock()
if exitErr != nil {
return exitErr.Error()
}
return ""
}
func (p *Process) Start() error {
if p.IsRunning() {
return errors.New("tuic-server is already running")
}
cmd := exec.CommandContext(context.Background(), GetBinaryPath(), "-c", p.configPath)
cmd.Stdout = p.logWriter
cmd.Stderr = p.logWriter
done := make(chan struct{})
p.mu.Lock()
p.cmd = cmd
p.done = done
p.exitErr = nil
p.mu.Unlock()
p.intentionalStop.Store(false)
if err := cmd.Start(); err != nil {
close(done)
p.mu.Lock()
p.cmd = nil
p.mu.Unlock()
return err
}
attachChildLifetime(cmd)
go p.wait(cmd, done)
return nil
}
func (p *Process) wait(cmd *exec.Cmd, done chan struct{}) {
defer close(done)
err := cmd.Wait()
p.logWriter.Flush()
if err == nil || p.intentionalStop.Load() {
return
}
if runtime.GOOS == "windows" {
if strings.Contains(strings.ToLower(err.Error()), "exit status 1") {
p.setExitErr(err)
return
}
}
logger.Errorf("tuic: tuic-server process exited: %v", err)
p.setExitErr(err)
}
func (p *Process) setExitErr(err error) {
p.mu.Lock()
p.exitErr = err
p.mu.Unlock()
}
func (p *Process) Stop() error {
if !p.IsRunning() {
return errors.New("tuic-server is not running")
}
p.intentionalStop.Store(true)
p.mu.RLock()
cmd, done := p.cmd, p.done
p.mu.RUnlock()
if cmd == nil || cmd.Process == nil {
return errors.New("tuic-server is not running")
}
if runtime.GOOS == "windows" {
if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
return err
}
return waitForExit(done, forceStopTimeout)
}
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
if errors.Is(err, os.ErrProcessDone) {
return waitForExit(done, forceStopTimeout)
}
return err
}
if err := waitForExit(done, gracefulStopTimeout); err == nil {
return nil
}
logger.Warning("tuic: tuic-server did not stop after SIGTERM, killing process")
if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
return err
}
return waitForExit(done, forceStopTimeout)
}
func waitForExit(done <-chan struct{}, timeout time.Duration) error {
if done == nil {
return nil
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
return nil
case <-timer.C:
return fmt.Errorf("timed out waiting for tuic-server process to stop after %s", timeout)
}
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package tuic
import "os/exec"
func attachChildLifetime(_ *exec.Cmd) {}
+67
View File
@@ -0,0 +1,67 @@
//go:build windows
package tuic
import (
"os/exec"
"sync"
"unsafe"
"golang.org/x/sys/windows"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
)
var (
killOnExitJobOnce sync.Once
killOnExitJob windows.Handle
killOnExitJobErr error
)
func ensureKillOnExitJob() (windows.Handle, error) {
killOnExitJobOnce.Do(func() {
h, err := windows.CreateJobObject(nil, nil)
if err != nil {
killOnExitJobErr = err
return
}
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{
BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{
LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
},
}
_, err = windows.SetInformationJobObject(
h,
windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)),
uint32(unsafe.Sizeof(info)),
)
if err != nil {
_ = windows.CloseHandle(h)
killOnExitJobErr = err
return
}
killOnExitJob = h
})
return killOnExitJob, killOnExitJobErr
}
func attachChildLifetime(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
job, err := ensureKillOnExitJob()
if err != nil {
logger.Warningf("tuic: kill-on-exit job unavailable: %v", err)
return
}
h, err := windows.OpenProcess(windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, uint32(cmd.Process.Pid))
if err != nil {
logger.Warningf("tuic: OpenProcess for job attach failed: %v", err)
return
}
defer func() { _ = windows.CloseHandle(h) }()
if err := windows.AssignProcessToJobObject(job, h); err != nil {
logger.Warningf("tuic: AssignProcessToJobObject failed: %v", err)
}
}
+196
View File
@@ -0,0 +1,196 @@
package tuic
import (
"errors"
"net"
"sync"
"sync/atomic"
"time"
)
// A QUIC flow the sidecar has not touched for this long is forgotten; QUIC's
// own max_idle_time (15s by default) closes the session well before that.
const relayFlowIdle = 2 * time.Minute
const (
relaySocketBuffer = 4 << 20
maxRelayFlows = 4096
)
// udpRelay owns an inbound's public UDP port and forwards each client's
// datagrams to the sidecar on loopback, which is the only place the panel can
// count the inbound's bytes: upstream tuic-server exposes no stats API and
// its socket syscalls never reach /proc/<pid>/io. Per-client attribution stays
// impossible because QUIC payloads are opaque.
type udpRelay struct {
public *net.UDPConn
upstream *net.UDPAddr
idle time.Duration
up atomic.Int64
down atomic.Int64
mu sync.Mutex
flows map[string]*relayFlow
done chan struct{}
closeOnce sync.Once
wg sync.WaitGroup
}
type relayFlow struct {
conn *net.UDPConn
client *net.UDPAddr
lastSeen atomic.Int64
}
func startUDPRelay(bind string, upstream *net.UDPAddr, idle time.Duration) (*udpRelay, error) {
addr, err := net.ResolveUDPAddr("udp", bind)
if err != nil {
return nil, err
}
public, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, err
}
_ = public.SetReadBuffer(relaySocketBuffer)
_ = public.SetWriteBuffer(relaySocketBuffer)
r := &udpRelay{
public: public,
upstream: upstream,
idle: idle,
flows: make(map[string]*relayFlow),
done: make(chan struct{}),
}
r.wg.Add(2)
go r.serve()
go r.sweep()
return r, nil
}
func freeLoopbackUDPPort() (int, error) {
c, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
return 0, err
}
defer c.Close()
return c.LocalAddr().(*net.UDPAddr).Port, nil
}
func (r *udpRelay) LocalAddr() net.Addr {
return r.public.LocalAddr()
}
// CollectTraffic returns the client-to-sidecar and sidecar-to-client bytes
// relayed since the previous call.
func (r *udpRelay) CollectTraffic() (up, down int64) {
return r.up.Swap(0), r.down.Swap(0)
}
func (r *udpRelay) Close() {
if r == nil {
return
}
r.closeOnce.Do(func() {
close(r.done)
_ = r.public.Close()
r.mu.Lock()
for key, f := range r.flows {
_ = f.conn.Close()
delete(r.flows, key)
}
r.mu.Unlock()
r.wg.Wait()
})
}
func (r *udpRelay) serve() {
defer r.wg.Done()
buf := make([]byte, 65535)
for {
n, client, err := r.public.ReadFromUDP(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
continue
}
flow, err := r.flowFor(client)
if err != nil {
continue
}
if _, err := flow.conn.Write(buf[:n]); err == nil {
r.up.Add(int64(n))
}
}
}
func (r *udpRelay) flowFor(client *net.UDPAddr) (*relayFlow, error) {
key := client.String()
now := time.Now().UnixMilli()
r.mu.Lock()
defer r.mu.Unlock()
select {
case <-r.done:
return nil, net.ErrClosed
default:
}
if f, ok := r.flows[key]; ok {
f.lastSeen.Store(now)
return f, nil
}
if len(r.flows) >= maxRelayFlows {
return nil, errors.New("tuic: max relay flows reached")
}
conn, err := net.DialUDP("udp", nil, r.upstream)
if err != nil {
return nil, err
}
_ = conn.SetReadBuffer(relaySocketBuffer)
_ = conn.SetWriteBuffer(relaySocketBuffer)
f := &relayFlow{conn: conn, client: client}
f.lastSeen.Store(now)
r.flows[key] = f
r.wg.Add(1)
go r.pump(f)
return f, nil
}
func (r *udpRelay) pump(f *relayFlow) {
defer r.wg.Done()
buf := make([]byte, 65535)
for {
n, err := f.conn.Read(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
// ICMP unreachable while the sidecar restarts: drop it, keep the flow.
time.Sleep(20 * time.Millisecond)
continue
}
if _, err := r.public.WriteToUDP(buf[:n], f.client); err == nil {
r.down.Add(int64(n))
}
f.lastSeen.Store(time.Now().UnixMilli())
}
}
func (r *udpRelay) sweep() {
defer r.wg.Done()
ticker := time.NewTicker(r.idle / 2)
defer ticker.Stop()
for {
select {
case <-r.done:
return
case <-ticker.C:
cutoff := time.Now().Add(-r.idle).UnixMilli()
r.mu.Lock()
for key, f := range r.flows {
if f.lastSeen.Load() < cutoff {
_ = f.conn.Close()
delete(r.flows, key)
}
}
r.mu.Unlock()
}
}
}
+127
View File
@@ -0,0 +1,127 @@
package tuic
import (
"bytes"
"net"
"testing"
"time"
)
// doublingEcho answers every datagram with the payload repeated twice, so a
// relay that mislabels directions or clients cannot pass by accident.
func doublingEcho(t *testing.T) *net.UDPAddr {
t.Helper()
echo, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = echo.Close() })
go func() {
buf := make([]byte, 65535)
for {
n, from, err := echo.ReadFromUDP(buf)
if err != nil {
return
}
_, _ = echo.WriteToUDP(append(append([]byte{}, buf[:n]...), buf[:n]...), from)
}
}()
return echo.LocalAddr().(*net.UDPAddr)
}
func roundTrip(t *testing.T, relay *udpRelay, payload []byte) int {
t.Helper()
c, err := net.DialUDP("udp", nil, relay.LocalAddr().(*net.UDPAddr))
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := c.Write(payload); err != nil {
t.Fatal(err)
}
_ = c.SetReadDeadline(time.Now().Add(3 * time.Second))
buf := make([]byte, 65535)
n, err := c.Read(buf)
if err != nil {
t.Fatalf("no reply through the relay: %v", err)
}
return n
}
func collectUntil(t *testing.T, relay *udpRelay, wantUp, wantDown int64) (int64, int64) {
t.Helper()
var up, down int64
deadline := time.Now().Add(2 * time.Second)
for {
u, d := relay.CollectTraffic()
up, down = up+u, down+d
if (up >= wantUp && down >= wantDown) || time.Now().After(deadline) {
return up, down
}
time.Sleep(10 * time.Millisecond)
}
}
func TestUDPRelayMetersBothDirectionsPerClient(t *testing.T) {
relay, err := startUDPRelay("127.0.0.1:0", doublingEcho(t), relayFlowIdle)
if err != nil {
t.Fatal(err)
}
t.Cleanup(relay.Close)
if got := roundTrip(t, relay, bytes.Repeat([]byte("a"), 100)); got != 200 {
t.Fatalf("client A reply = %d bytes, want 200", got)
}
if got := roundTrip(t, relay, bytes.Repeat([]byte("b"), 50)); got != 100 {
t.Fatalf("client B reply = %d bytes, want 100", got)
}
if up, down := collectUntil(t, relay, 150, 300); up != 150 || down != 300 {
t.Fatalf("delta = (%d up, %d down), want (150, 300)", up, down)
}
if up, down := relay.CollectTraffic(); up != 0 || down != 0 {
t.Fatalf("second collect = (%d, %d), want (0, 0): deltas must reset", up, down)
}
}
func TestUDPRelayExpiresIdleFlows(t *testing.T) {
relay, err := startUDPRelay("127.0.0.1:0", doublingEcho(t), 50*time.Millisecond)
if err != nil {
t.Fatal(err)
}
t.Cleanup(relay.Close)
roundTrip(t, relay, []byte("hello"))
deadline := time.Now().Add(2 * time.Second)
for {
relay.mu.Lock()
n := len(relay.flows)
relay.mu.Unlock()
if n == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("%d flow(s) still open after the idle window", n)
}
time.Sleep(10 * time.Millisecond)
}
if got := roundTrip(t, relay, []byte("again")); got != 10 {
t.Fatalf("reply after expiry = %d bytes, want 10", got)
}
}
func TestUDPRelayRefusesFlowsAfterClose(t *testing.T) {
relay, err := startUDPRelay("127.0.0.1:0", doublingEcho(t), relayFlowIdle)
if err != nil {
t.Fatal(err)
}
relay.Close()
if _, err := relay.flowFor(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 9}); err == nil {
t.Fatal("flowFor after Close must refuse: its pump would outlive the relay and hang Close's WaitGroup")
}
relay.mu.Lock()
n := len(relay.flows)
relay.mu.Unlock()
if n != 0 {
t.Fatalf("%d flow(s) registered after Close", n)
}
}
+249
View File
@@ -0,0 +1,249 @@
package tuic
import (
"encoding/json"
"fmt"
"net"
"slices"
"strconv"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
type TuicServerSettings struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"private_key"`
CongestionControl string `json:"congestion_control"`
ALPN []string `json:"alpn"`
UDPRelayMode string `json:"udp_relay_mode"`
ZeroRTTHandshake bool `json:"zero_rtt_handshake"`
LogLevel string `json:"log_level"`
MaxIdleTime int `json:"max_idle_time"`
AuthenticationTimeout int `json:"authentication_timeout"`
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
SNI string `json:"sni,omitempty"`
}
type TuicClientSettings struct {
UUID string `json:"uuid"`
Password string `json:"password"`
Email string `json:"email"`
}
type Instance struct {
Id int
Tag string
Listen string
Port int
Certificate string
PrivateKey string
CongestionControl string
ALPN []string
UDPRelayMode string
ZeroRTTHandshake bool
LogLevel string
MaxIdleTime int
AuthenticationTimeout int
MaxUdpRelayPacketSize int
SNI string
Clients []TuicClientSettings
}
func (inst Instance) BindTo() string {
listen := inst.Listen
if listen == "" {
listen = "0.0.0.0"
}
return net.JoinHostPort(listen, strconv.Itoa(inst.Port))
}
func (inst Instance) StructuralFingerprint() string {
parts := []string{
inst.BindTo(),
inst.Certificate,
inst.PrivateKey,
inst.CongestionControl,
strings.Join(inst.ALPN, ","),
inst.UDPRelayMode,
strconv.FormatBool(inst.ZeroRTTHandshake),
inst.LogLevel,
strconv.Itoa(inst.MaxIdleTime),
strconv.Itoa(inst.AuthenticationTimeout),
strconv.Itoa(inst.MaxUdpRelayPacketSize),
inst.SNI,
}
return strings.Join(parts, "|")
}
func (inst Instance) UsersFingerprint() string {
pairs := make([]string, 0, len(inst.Clients))
for _, c := range inst.Clients {
pairs = append(pairs, fmt.Sprintf("%s=%s:%s", c.Email, c.UUID, c.Password))
}
slices.Sort(pairs)
return strings.Join(pairs, "|")
}
func (inst Instance) FullFingerprint() string {
return inst.StructuralFingerprint() + "#" + inst.UsersFingerprint()
}
func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
if ib == nil || ib.Protocol != model.TUIC {
return Instance{}, false
}
var parsed struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"private_key"`
CongestionControl string `json:"congestion_control"`
ALPN []string `json:"alpn"`
UDPRelayMode string `json:"udp_relay_mode"`
ZeroRTTHandshake *bool `json:"zero_rtt_handshake"`
LogLevel string `json:"log_level"`
MaxIdleTime int `json:"max_idle_time"`
AuthenticationTimeout int `json:"authentication_timeout"`
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
SNI string `json:"sni"`
Server *struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"private_key"`
CongestionControl string `json:"congestion_control"`
ALPN []string `json:"alpn"`
UDPRelayMode string `json:"udp_relay_mode"`
ZeroRTTHandshake *bool `json:"zero_rtt_handshake"`
LogLevel string `json:"log_level"`
MaxIdleTime int `json:"max_idle_time"`
AuthenticationTimeout int `json:"authentication_timeout"`
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
SNI string `json:"sni"`
} `json:"server"`
Clients []struct {
UUID string `json:"uuid"`
ID string `json:"id"`
Password string `json:"password"`
Email string `json:"email"`
Enable *bool `json:"enable"`
TotalGB int64 `json:"totalGB"`
ExpiryTime int64 `json:"expiryTime"`
} `json:"clients"`
}
if ib.Settings != "" {
if err := json.Unmarshal([]byte(ib.Settings), &parsed); err != nil {
return Instance{}, false
}
}
cert := parsed.Certificate
key := parsed.PrivateKey
cc := parsed.CongestionControl
alpn := parsed.ALPN
udpRelayMode := parsed.UDPRelayMode
zeroRtt := true
if parsed.ZeroRTTHandshake != nil {
zeroRtt = *parsed.ZeroRTTHandshake
}
logLevel := parsed.LogLevel
maxIdle := parsed.MaxIdleTime
authTimeout := parsed.AuthenticationTimeout
maxPacketSize := parsed.MaxUdpRelayPacketSize
sni := parsed.SNI
if parsed.Server != nil {
if parsed.Server.Certificate != "" {
cert = parsed.Server.Certificate
}
if parsed.Server.PrivateKey != "" {
key = parsed.Server.PrivateKey
}
if parsed.Server.CongestionControl != "" {
cc = parsed.Server.CongestionControl
}
if len(parsed.Server.ALPN) > 0 {
alpn = parsed.Server.ALPN
}
if parsed.Server.UDPRelayMode != "" {
udpRelayMode = parsed.Server.UDPRelayMode
}
if parsed.Server.ZeroRTTHandshake != nil {
zeroRtt = *parsed.Server.ZeroRTTHandshake
}
if parsed.Server.LogLevel != "" {
logLevel = parsed.Server.LogLevel
}
if parsed.Server.MaxIdleTime > 0 {
maxIdle = parsed.Server.MaxIdleTime
}
if parsed.Server.AuthenticationTimeout > 0 {
authTimeout = parsed.Server.AuthenticationTimeout
}
if parsed.Server.MaxUdpRelayPacketSize > 0 {
maxPacketSize = parsed.Server.MaxUdpRelayPacketSize
}
if parsed.Server.SNI != "" {
sni = parsed.Server.SNI
}
}
if cc == "" {
cc = "bbr"
}
if len(alpn) == 0 {
alpn = []string{"h3", "spdy/3.1"}
}
if udpRelayMode == "" {
udpRelayMode = "native"
}
if logLevel == "" {
logLevel = "info"
}
if maxIdle <= 0 {
maxIdle = 15
}
if authTimeout <= 0 {
authTimeout = 3
}
if maxPacketSize <= 0 {
maxPacketSize = 1500
}
clients := make([]TuicClientSettings, 0, len(parsed.Clients))
for _, c := range parsed.Clients {
if c.Enable != nil && !*c.Enable {
continue
}
uuidVal := strings.ToLower(strings.TrimSpace(c.UUID))
if uuidVal == "" {
uuidVal = strings.ToLower(strings.TrimSpace(c.ID))
}
if uuidVal == "" || c.Password == "" {
continue
}
clients = append(clients, TuicClientSettings{
UUID: uuidVal,
Password: c.Password,
Email: c.Email,
})
}
return Instance{
Id: ib.Id,
Tag: ib.Tag,
Listen: ib.Listen,
Port: ib.Port,
Certificate: cert,
PrivateKey: key,
CongestionControl: cc,
ALPN: alpn,
UDPRelayMode: udpRelayMode,
ZeroRTTHandshake: zeroRtt,
LogLevel: logLevel,
MaxIdleTime: maxIdle,
AuthenticationTimeout: authTimeout,
MaxUdpRelayPacketSize: maxPacketSize,
SNI: sni,
Clients: clients,
}, true
}
+124
View File
@@ -0,0 +1,124 @@
package tuic
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestInstanceFromInbound(t *testing.T) {
t.Run("valid settings", func(t *testing.T) {
ib := &model.Inbound{
Id: 10,
Tag: "tuic-in-1",
Port: 8443,
Listen: "0.0.0.0",
Protocol: model.TUIC,
Settings: `{"certificate":"/etc/cert.pem","private_key":"/etc/key.pem","congestion_control":"bbr","alpn":["h3"],"clients":[{"uuid":"11111111-2222-3333-4444-555555555555","password":"pass1","email":"user1@test","enable":true}]}`,
}
inst, ok := InstanceFromInbound(ib)
if !ok {
t.Fatal("expected ok to be true")
}
if inst.Id != 10 || inst.Port != 8443 || inst.Tag != "tuic-in-1" {
t.Fatalf("unexpected inst header fields: %+v", inst)
}
if inst.Certificate != "/etc/cert.pem" || inst.PrivateKey != "/etc/key.pem" {
t.Fatalf("unexpected cert/key: %s / %s", inst.Certificate, inst.PrivateKey)
}
if len(inst.Clients) != 1 {
t.Fatalf("expected 1 client, got %d", len(inst.Clients))
}
if inst.Clients[0].UUID != "11111111-2222-3333-4444-555555555555" || inst.Clients[0].Password != "pass1" {
t.Fatalf("unexpected client: %+v", inst.Clients[0])
}
})
t.Run("normalizes uuid to lowercase and trims space", func(t *testing.T) {
ib := &model.Inbound{
Id: 12,
Protocol: model.TUIC,
Settings: `{"clients":[{"uuid":" A1B2C3D4-E5F6-7A8B-9C0D-1E2F3A4B5C6D ","password":"p"}]}`,
}
inst, ok := InstanceFromInbound(ib)
if !ok || len(inst.Clients) != 1 {
t.Fatal("expected ok and 1 client")
}
if inst.Clients[0].UUID != "a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d" {
t.Fatalf("expected lowercase trimmed UUID, got %q", inst.Clients[0].UUID)
}
})
t.Run("nil or wrong protocol", func(t *testing.T) {
if _, ok := InstanceFromInbound(nil); ok {
t.Fatal("expected false for nil")
}
if _, ok := InstanceFromInbound(&model.Inbound{Protocol: model.VLESS}); ok {
t.Fatal("expected false for vless")
}
})
t.Run("no enabled clients", func(t *testing.T) {
ib := &model.Inbound{
Id: 11,
Protocol: model.TUIC,
Settings: `{"clients":[{"uuid":"1111","password":"p","enable":false}]}`,
}
inst, ok := InstanceFromInbound(ib)
if !ok {
t.Fatal("expected ok for inbound")
}
if len(inst.Clients) != 0 {
t.Fatalf("expected 0 enabled clients, got %d", len(inst.Clients))
}
})
}
func TestFingerprints(t *testing.T) {
inst1 := Instance{
Id: 1,
Port: 8443,
Certificate: "/path/cert",
PrivateKey: "/path/key",
CongestionControl: "bbr",
Clients: []TuicClientSettings{
{UUID: "u1", Password: "p1", Email: "e1"},
{UUID: "u2", Password: "p2", Email: "e2"},
},
}
inst2 := Instance{
Id: 1,
Port: 8443,
Certificate: "/path/cert",
PrivateKey: "/path/key",
CongestionControl: "bbr",
Clients: []TuicClientSettings{
{UUID: "u2", Password: "p2", Email: "e2"},
{UUID: "u1", Password: "p1", Email: "e1"},
},
}
if inst1.UsersFingerprint() != inst2.UsersFingerprint() {
t.Fatalf("users fingerprint must be stable under reordering: %s vs %s", inst1.UsersFingerprint(), inst2.UsersFingerprint())
}
}
func TestBindTo(t *testing.T) {
tests := []struct {
listen string
want string
}{
{"", "0.0.0.0:8443"},
{"127.0.0.1", "127.0.0.1:8443"},
{"::", "[::]:8443"},
{"2001:db8::1", "[2001:db8::1]:8443"},
}
for _, tc := range tests {
t.Run(tc.listen, func(t *testing.T) {
got := Instance{Listen: tc.listen, Port: 8443}.BindTo()
if got != tc.want {
t.Fatalf("BindTo(%q) = %q, want %q", tc.listen, got, tc.want)
}
})
}
}