port_conflict_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. package service
  2. import (
  3. "path/filepath"
  4. "sync"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/database"
  7. "github.com/mhsanaei/3x-ui/v3/database/model"
  8. xuilogger "github.com/mhsanaei/3x-ui/v3/logger"
  9. "github.com/op/go-logging"
  10. )
  11. // the panel logger is a process-wide singleton. init it once per test
  12. // binary so a stray warning from gorm doesn't blow up on a nil logger.
  13. var portConflictLoggerOnce sync.Once
  14. // setupConflictDB wires a temp sqlite db so checkPortConflict can read
  15. // real candidates. closes the db before t.TempDir cleans up so windows
  16. // doesn't refuse to remove the file.
  17. func setupConflictDB(t *testing.T) {
  18. t.Helper()
  19. portConflictLoggerOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) })
  20. dbDir := t.TempDir()
  21. t.Setenv("XUI_DB_FOLDER", dbDir)
  22. if err := database.InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil {
  23. t.Fatalf("InitDB: %v", err)
  24. }
  25. t.Cleanup(func() {
  26. if err := database.CloseDB(); err != nil {
  27. t.Logf("CloseDB warning: %v", err)
  28. }
  29. })
  30. }
  31. func seedInboundConflict(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string) {
  32. t.Helper()
  33. seedInboundConflictNode(t, tag, listen, port, protocol, streamSettings, settings, nil)
  34. }
  35. func seedInboundConflictNode(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string, nodeID *int) {
  36. t.Helper()
  37. in := &model.Inbound{
  38. Tag: tag,
  39. Enable: true,
  40. Listen: listen,
  41. Port: port,
  42. Protocol: protocol,
  43. StreamSettings: streamSettings,
  44. Settings: settings,
  45. NodeID: nodeID,
  46. }
  47. if err := database.GetDB().Create(in).Error; err != nil {
  48. t.Fatalf("seed inbound %s: %v", tag, err)
  49. }
  50. }
  51. func intPtr(v int) *int { return &v }
  52. func TestInboundTransports(t *testing.T) {
  53. cases := []struct {
  54. name string
  55. protocol model.Protocol
  56. streamSettings string
  57. settings string
  58. want transportBits
  59. }{
  60. {"vless default tcp", model.VLESS, `{"network":"tcp"}`, ``, transportTCP},
  61. {"vless ws (still tcp)", model.VLESS, `{"network":"ws"}`, ``, transportTCP},
  62. {"vless kcp is udp", model.VLESS, `{"network":"kcp"}`, ``, transportUDP},
  63. {"vless empty stream defaults to tcp", model.VLESS, ``, ``, transportTCP},
  64. {"vless garbage stream stays tcp", model.VLESS, `not json`, ``, transportTCP},
  65. {"vmess default tcp", model.VMESS, `{"network":"tcp"}`, ``, transportTCP},
  66. {"trojan grpc is tcp", model.Trojan, `{"network":"grpc"}`, ``, transportTCP},
  67. {"hysteria forced udp", model.Hysteria, `{"network":"tcp"}`, ``, transportUDP},
  68. {"hysteria2 forced udp", model.Hysteria2, ``, ``, transportUDP},
  69. {"wireguard forced udp", model.WireGuard, ``, ``, transportUDP},
  70. {"shadowsocks tcp,udp", model.Shadowsocks, ``, `{"network":"tcp,udp"}`, transportTCP | transportUDP},
  71. {"shadowsocks udp only", model.Shadowsocks, ``, `{"network":"udp"}`, transportUDP},
  72. {"shadowsocks tcp only", model.Shadowsocks, ``, `{"network":"tcp"}`, transportTCP},
  73. {"shadowsocks empty network falls back to streamSettings", model.Shadowsocks, `{"network":"tcp"}`, `{}`, transportTCP},
  74. {"mixed udp on", model.Mixed, `{"network":"tcp"}`, `{"udp":true}`, transportTCP | transportUDP},
  75. {"mixed udp off", model.Mixed, `{"network":"tcp"}`, `{"udp":false}`, transportTCP},
  76. {"mixed udp missing", model.Mixed, `{"network":"tcp"}`, `{}`, transportTCP},
  77. }
  78. for _, c := range cases {
  79. t.Run(c.name, func(t *testing.T) {
  80. got := inboundTransports(c.protocol, c.streamSettings, c.settings)
  81. if got != c.want {
  82. t.Fatalf("got bits %#b, want %#b", got, c.want)
  83. }
  84. })
  85. }
  86. }
  87. func TestListenOverlaps(t *testing.T) {
  88. cases := []struct {
  89. a, b string
  90. want bool
  91. }{
  92. {"", "", true},
  93. {"0.0.0.0", "", true},
  94. {"0.0.0.0", "1.2.3.4", true},
  95. {"::", "1.2.3.4", true},
  96. {"::0", "fe80::1", true},
  97. {"1.2.3.4", "1.2.3.4", true},
  98. {"1.2.3.4", "5.6.7.8", false},
  99. {"1.2.3.4", "::1", false},
  100. }
  101. for _, c := range cases {
  102. if got := listenOverlaps(c.a, c.b); got != c.want {
  103. t.Errorf("listenOverlaps(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
  104. }
  105. }
  106. }
  107. // the actual case from #4103: tcp/443 vless reality and udp/443
  108. // hysteria2 must be allowed to coexist on the same port.
  109. func TestCheckPortConflict_TCPandUDPCoexistOnSamePort(t *testing.T) {
  110. setupConflictDB(t)
  111. seedInboundConflict(t, "vless-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  112. svc := &InboundService{}
  113. hyst2 := &model.Inbound{
  114. Tag: "hyst2-443-udp",
  115. Listen: "0.0.0.0",
  116. Port: 443,
  117. Protocol: model.Hysteria2,
  118. }
  119. exist, err := svc.checkPortConflict(hyst2, 0)
  120. if err != nil {
  121. t.Fatalf("checkPortConflict: %v", err)
  122. }
  123. if exist {
  124. t.Fatalf("vless/tcp and hysteria2/udp on the same port must be allowed to coexist")
  125. }
  126. }
  127. // two tcp inbounds on the same port still conflict.
  128. func TestCheckPortConflict_TCPCollidesWithTCP(t *testing.T) {
  129. setupConflictDB(t)
  130. seedInboundConflict(t, "vless-443-a", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  131. svc := &InboundService{}
  132. other := &model.Inbound{
  133. Tag: "vless-443-b",
  134. Listen: "0.0.0.0",
  135. Port: 443,
  136. Protocol: model.Trojan,
  137. StreamSettings: `{"network":"ws"}`,
  138. }
  139. exist, err := svc.checkPortConflict(other, 0)
  140. if err != nil {
  141. t.Fatalf("checkPortConflict: %v", err)
  142. }
  143. if !exist {
  144. t.Fatalf("two tcp inbounds on the same port must still conflict")
  145. }
  146. }
  147. // two udp inbounds (e.g. hysteria2 vs wireguard) on the same port also
  148. // conflict, since they fight for the same socket.
  149. func TestCheckPortConflict_UDPCollidesWithUDP(t *testing.T) {
  150. setupConflictDB(t)
  151. seedInboundConflict(t, "hyst2-443", "0.0.0.0", 443, model.Hysteria2, ``, ``)
  152. svc := &InboundService{}
  153. wg := &model.Inbound{
  154. Tag: "wg-443",
  155. Listen: "0.0.0.0",
  156. Port: 443,
  157. Protocol: model.WireGuard,
  158. }
  159. exist, err := svc.checkPortConflict(wg, 0)
  160. if err != nil {
  161. t.Fatalf("checkPortConflict: %v", err)
  162. }
  163. if !exist {
  164. t.Fatalf("two udp inbounds on the same port must conflict")
  165. }
  166. }
  167. // shadowsocks listening on tcp+udp eats the whole port for both
  168. // transports, so neither a tcp nor a udp neighbour is allowed.
  169. func TestCheckPortConflict_ShadowsocksDualListenBlocksBoth(t *testing.T) {
  170. setupConflictDB(t)
  171. seedInboundConflict(t, "ss-443-dual", "0.0.0.0", 443, model.Shadowsocks, ``, `{"network":"tcp,udp"}`)
  172. svc := &InboundService{}
  173. tcpClash := &model.Inbound{
  174. Tag: "vless-443",
  175. Listen: "0.0.0.0",
  176. Port: 443,
  177. Protocol: model.VLESS,
  178. StreamSettings: `{"network":"tcp"}`,
  179. }
  180. if exist, err := svc.checkPortConflict(tcpClash, 0); err != nil || !exist {
  181. t.Fatalf("tcp inbound should clash with shadowsocks tcp,udp; exist=%v err=%v", exist, err)
  182. }
  183. udpClash := &model.Inbound{
  184. Tag: "hyst2-443",
  185. Listen: "0.0.0.0",
  186. Port: 443,
  187. Protocol: model.Hysteria2,
  188. }
  189. if exist, err := svc.checkPortConflict(udpClash, 0); err != nil || !exist {
  190. t.Fatalf("udp inbound should clash with shadowsocks tcp,udp; exist=%v err=%v", exist, err)
  191. }
  192. }
  193. // different ports never conflict regardless of transport.
  194. func TestCheckPortConflict_DifferentPortNeverConflicts(t *testing.T) {
  195. setupConflictDB(t)
  196. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  197. svc := &InboundService{}
  198. other := &model.Inbound{
  199. Tag: "vless-444",
  200. Listen: "0.0.0.0",
  201. Port: 444,
  202. Protocol: model.VLESS,
  203. StreamSettings: `{"network":"tcp"}`,
  204. }
  205. if exist, err := svc.checkPortConflict(other, 0); err != nil || exist {
  206. t.Fatalf("different port must not conflict; exist=%v err=%v", exist, err)
  207. }
  208. }
  209. // specific listen addresses on the same port don't clash with each other,
  210. // but do clash with any-address on the same port (preserved from the old
  211. // check).
  212. func TestCheckPortConflict_ListenOverlapPreserved(t *testing.T) {
  213. setupConflictDB(t)
  214. seedInboundConflict(t, "vless-1.2.3.4", "1.2.3.4", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  215. svc := &InboundService{}
  216. // different specific address, same port + transport: no conflict.
  217. other := &model.Inbound{
  218. Tag: "vless-5.6.7.8",
  219. Listen: "5.6.7.8",
  220. Port: 443,
  221. Protocol: model.VLESS,
  222. StreamSettings: `{"network":"tcp"}`,
  223. }
  224. if exist, err := svc.checkPortConflict(other, 0); err != nil || exist {
  225. t.Fatalf("different specific listen must not conflict; exist=%v err=%v", exist, err)
  226. }
  227. // any-address vs specific on same transport: conflict (any-addr wins).
  228. anyAddr := &model.Inbound{
  229. Tag: "vless-any",
  230. Listen: "0.0.0.0",
  231. Port: 443,
  232. Protocol: model.VLESS,
  233. StreamSettings: `{"network":"tcp"}`,
  234. }
  235. if exist, err := svc.checkPortConflict(anyAddr, 0); err != nil || !exist {
  236. t.Fatalf("any-addr on same port+transport must conflict with specific; exist=%v err=%v", exist, err)
  237. }
  238. }
  239. // when the base "inbound-<port>" tag is already taken on a coexisting
  240. // transport, generateInboundTag must disambiguate with a transport
  241. // suffix so the unique-tag DB constraint stays satisfied.
  242. func TestGenerateInboundTag_DisambiguatesByTransportOnSamePort(t *testing.T) {
  243. setupConflictDB(t)
  244. // existing tcp inbound owns "inbound-443".
  245. seedInboundConflict(t, "inbound-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  246. svc := &InboundService{}
  247. udp := &model.Inbound{
  248. Listen: "0.0.0.0",
  249. Port: 443,
  250. Protocol: model.Hysteria2,
  251. }
  252. got, err := svc.generateInboundTag(udp, 0)
  253. if err != nil {
  254. t.Fatalf("generateInboundTag: %v", err)
  255. }
  256. if got != "inbound-443-udp" {
  257. t.Fatalf("expected disambiguated tag inbound-443-udp, got %q", got)
  258. }
  259. }
  260. // when the port is free, the historical "inbound-<port>" shape is kept
  261. // so existing routing rules don't change shape on upgrade.
  262. func TestGenerateInboundTag_KeepsBaseTagWhenFree(t *testing.T) {
  263. setupConflictDB(t)
  264. svc := &InboundService{}
  265. in := &model.Inbound{
  266. Listen: "0.0.0.0",
  267. Port: 8443,
  268. Protocol: model.VLESS,
  269. }
  270. got, err := svc.generateInboundTag(in, 0)
  271. if err != nil {
  272. t.Fatalf("generateInboundTag: %v", err)
  273. }
  274. if got != "inbound-8443" {
  275. t.Fatalf("expected inbound-8443, got %q", got)
  276. }
  277. }
  278. // updating an inbound on its own port must not flag its own tag as
  279. // taken, that's what ignoreId is for.
  280. func TestGenerateInboundTag_IgnoresSelfOnUpdate(t *testing.T) {
  281. setupConflictDB(t)
  282. seedInboundConflict(t, "inbound-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  283. var existing model.Inbound
  284. if err := database.GetDB().Where("tag = ?", "inbound-443").First(&existing).Error; err != nil {
  285. t.Fatalf("read seeded row: %v", err)
  286. }
  287. svc := &InboundService{}
  288. got, err := svc.generateInboundTag(&existing, existing.Id)
  289. if err != nil {
  290. t.Fatalf("generateInboundTag: %v", err)
  291. }
  292. if got != "inbound-443" {
  293. t.Fatalf("self-update must keep base tag, got %q", got)
  294. }
  295. }
  296. // specific listen address gets the listen-prefixed shape and same
  297. // disambiguation rules.
  298. func TestGenerateInboundTag_SpecificListenSameDisambiguation(t *testing.T) {
  299. setupConflictDB(t)
  300. seedInboundConflict(t, "inbound-1.2.3.4:443", "1.2.3.4", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  301. svc := &InboundService{}
  302. udp := &model.Inbound{
  303. Listen: "1.2.3.4",
  304. Port: 443,
  305. Protocol: model.Hysteria2,
  306. }
  307. got, err := svc.generateInboundTag(udp, 0)
  308. if err != nil {
  309. t.Fatalf("generateInboundTag: %v", err)
  310. }
  311. if got != "inbound-1.2.3.4:443-udp" {
  312. t.Fatalf("expected inbound-1.2.3.4:443-udp, got %q", got)
  313. }
  314. }
  315. // inbounds bound to different nodes run on different physical machines,
  316. // so the same port + transport must be allowed across nodes. covers
  317. // local-vs-remote, remote-A-vs-remote-B, and the still-clashing
  318. // same-node case.
  319. func TestCheckPortConflict_NodeScope(t *testing.T) {
  320. setupConflictDB(t)
  321. seedInboundConflictNode(t, "local-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  322. seedInboundConflictNode(t, "node1-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, intPtr(1))
  323. svc := &InboundService{}
  324. cases := []struct {
  325. name string
  326. nodeID *int
  327. want bool
  328. }{
  329. {"new local same port + tcp clashes with local", nil, true},
  330. {"new remote on different node from local is fine", intPtr(2), false},
  331. {"new remote on existing node 1 clashes", intPtr(1), true},
  332. }
  333. for _, c := range cases {
  334. t.Run(c.name, func(t *testing.T) {
  335. candidate := &model.Inbound{
  336. Listen: "0.0.0.0",
  337. Port: 443,
  338. Protocol: model.VLESS,
  339. StreamSettings: `{"network":"tcp"}`,
  340. NodeID: c.nodeID,
  341. }
  342. got, err := svc.checkPortConflict(candidate, 0)
  343. if err != nil {
  344. t.Fatalf("checkPortConflict: %v", err)
  345. }
  346. if got != c.want {
  347. t.Fatalf("got conflict=%v, want %v", got, c.want)
  348. }
  349. })
  350. }
  351. }
  352. // when the caller passes an explicit non-empty Tag that doesn't collide,
  353. // resolveInboundTag returns it verbatim. this is the cross-panel path:
  354. // the central panel picks a tag, pushes the inbound to a node, and the
  355. // node must keep that exact tag so the eventual traffic sync-back can
  356. // match the row by tag. previously the node regenerated and the two
  357. // panels diverged, causing a UNIQUE constraint failure on sync.
  358. func TestResolveInboundTag_RespectsCallerTagWhenFree(t *testing.T) {
  359. setupConflictDB(t)
  360. seedInboundConflictNode(t, "inbound-5000", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  361. seedInboundConflictNode(t, "inbound-5000-udp", "0.0.0.0", 5000, model.Hysteria2, ``, ``, nil)
  362. svc := &InboundService{}
  363. pushed := &model.Inbound{
  364. Tag: "inbound-5000-tcp",
  365. Listen: "0.0.0.0",
  366. Port: 5000,
  367. Protocol: model.VLESS,
  368. StreamSettings: `{"network":"tcp"}`,
  369. NodeID: intPtr(1),
  370. }
  371. got, err := svc.resolveInboundTag(pushed, 0)
  372. if err != nil {
  373. t.Fatalf("resolveInboundTag: %v", err)
  374. }
  375. if got != "inbound-5000-tcp" {
  376. t.Fatalf("caller tag must be preserved when free, got %q", got)
  377. }
  378. }
  379. // when the caller leaves Tag empty (the local UI path) resolveInboundTag
  380. // falls back to generateInboundTag, which keeps the historical
  381. // "inbound-<port>" shape so existing routing rules don't change.
  382. func TestResolveInboundTag_GeneratesWhenTagEmpty(t *testing.T) {
  383. setupConflictDB(t)
  384. svc := &InboundService{}
  385. in := &model.Inbound{
  386. Listen: "0.0.0.0",
  387. Port: 8443,
  388. Protocol: model.VLESS,
  389. }
  390. got, err := svc.resolveInboundTag(in, 0)
  391. if err != nil {
  392. t.Fatalf("resolveInboundTag: %v", err)
  393. }
  394. if got != "inbound-8443" {
  395. t.Fatalf("expected generated inbound-8443, got %q", got)
  396. }
  397. }
  398. // when the caller's Tag collides (e.g. a node that was used standalone
  399. // happens to already own the tag the central panel picked),
  400. // resolveInboundTag falls back to generateInboundTag rather than
  401. // failing — the inbound still lands, just under a slightly different
  402. // tag that the central will pick up via the AddInbound response.
  403. func TestResolveInboundTag_RegeneratesOnCollision(t *testing.T) {
  404. setupConflictDB(t)
  405. seedInboundConflictNode(t, "inbound-5000-tcp", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  406. svc := &InboundService{}
  407. pushed := &model.Inbound{
  408. Tag: "inbound-5000-tcp",
  409. Listen: "0.0.0.0",
  410. Port: 5000,
  411. Protocol: model.Hysteria2,
  412. StreamSettings: ``,
  413. Settings: ``,
  414. }
  415. got, err := svc.resolveInboundTag(pushed, 0)
  416. if err != nil {
  417. t.Fatalf("resolveInboundTag: %v", err)
  418. }
  419. if got == "inbound-5000-tcp" {
  420. t.Fatalf("colliding caller tag must be replaced, but resolver kept %q", got)
  421. }
  422. }
  423. // updating an inbound must not see itself as a conflict, that's what
  424. // ignoreId is for.
  425. func TestCheckPortConflict_IgnoreSelfOnUpdate(t *testing.T) {
  426. setupConflictDB(t)
  427. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  428. var existing model.Inbound
  429. if err := database.GetDB().Where("tag = ?", "vless-443").First(&existing).Error; err != nil {
  430. t.Fatalf("read seeded row: %v", err)
  431. }
  432. svc := &InboundService{}
  433. if exist, err := svc.checkPortConflict(&existing, existing.Id); err != nil || exist {
  434. t.Fatalf("self-update must not be flagged as conflict; exist=%v err=%v", exist, err)
  435. }
  436. }