port_conflict_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. package service
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "sync"
  6. "testing"
  7. "github.com/op/go-logging"
  8. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. )
  13. // the panel logger is a process-wide singleton. init it once per test
  14. // binary so a stray warning from gorm doesn't blow up on a nil logger.
  15. var portConflictLoggerOnce sync.Once
  16. // setupConflictDB wires a temp sqlite db so checkPortConflict can read
  17. // real candidates. closes the db before t.TempDir cleans up so windows
  18. // doesn't refuse to remove the file.
  19. func setupConflictDB(t *testing.T) {
  20. t.Helper()
  21. portConflictLoggerOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) })
  22. dbDir := t.TempDir()
  23. t.Setenv("XUI_DB_FOLDER", dbDir)
  24. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  25. t.Fatalf("InitDB: %v", err)
  26. }
  27. t.Cleanup(func() {
  28. if err := database.CloseDB(); err != nil {
  29. t.Logf("CloseDB warning: %v", err)
  30. }
  31. })
  32. }
  33. func seedInboundConflict(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string) {
  34. t.Helper()
  35. seedInboundConflictNode(t, tag, listen, port, protocol, streamSettings, settings, nil)
  36. }
  37. func seedInboundConflictNode(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string, nodeID *int) {
  38. t.Helper()
  39. in := &model.Inbound{
  40. Tag: tag,
  41. Enable: true,
  42. Listen: listen,
  43. Port: port,
  44. Protocol: protocol,
  45. StreamSettings: streamSettings,
  46. Settings: settings,
  47. NodeID: nodeID,
  48. }
  49. if err := database.GetDB().Create(in).Error; err != nil {
  50. t.Fatalf("seed inbound %s: %v", tag, err)
  51. }
  52. }
  53. func TestInboundTransports(t *testing.T) {
  54. cases := []struct {
  55. name string
  56. protocol model.Protocol
  57. streamSettings string
  58. settings string
  59. want transportBits
  60. }{
  61. {"vless default tcp", model.VLESS, `{"network":"tcp"}`, ``, transportTCP},
  62. {"vless ws (still tcp)", model.VLESS, `{"network":"ws"}`, ``, transportTCP},
  63. {"vless kcp is udp", model.VLESS, `{"network":"kcp"}`, ``, transportUDP},
  64. {"vless empty stream defaults to tcp", model.VLESS, ``, ``, transportTCP},
  65. {"vless garbage stream stays tcp", model.VLESS, `not json`, ``, transportTCP},
  66. {"vmess default tcp", model.VMESS, `{"network":"tcp"}`, ``, transportTCP},
  67. {"trojan grpc is tcp", model.Trojan, `{"network":"grpc"}`, ``, transportTCP},
  68. {"hysteria forced udp", model.Hysteria, `{"network":"tcp"}`, ``, 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. // hysteria 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.Hysteria,
  118. }
  119. exist, err := svc.checkPortConflict(hyst2, 0)
  120. if err != nil {
  121. t.Fatalf("checkPortConflict: %v", err)
  122. }
  123. if exist != nil {
  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 == nil {
  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.Hysteria, ``, ``)
  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 == nil {
  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 == nil {
  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.Hysteria,
  188. }
  189. if exist, err := svc.checkPortConflict(udpClash, 0); err != nil || exist == nil {
  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 != nil {
  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 != nil {
  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 == nil {
  236. t.Fatalf("any-addr on same port+transport must conflict with specific; exist=%v err=%v", exist, err)
  237. }
  238. }
  239. // even with a stale legacy tag owning "in-443", a new UDP-side
  240. // inbound gets a fully qualified canonical tag and does not collide.
  241. func TestGenerateInboundTag_DisambiguatesByTransportOnSamePort(t *testing.T) {
  242. setupConflictDB(t)
  243. seedInboundConflict(t, "in-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  244. svc := &InboundService{}
  245. udp := &model.Inbound{
  246. Listen: "0.0.0.0",
  247. Port: 443,
  248. Protocol: model.Hysteria,
  249. }
  250. got, err := svc.generateInboundTag(udp, 0)
  251. if err != nil {
  252. t.Fatalf("generateInboundTag: %v", err)
  253. }
  254. if got != "in-443-udp" {
  255. t.Fatalf("expected in-443-udp, got %q", got)
  256. }
  257. }
  258. // when the port is free, the canonical tag carries the transport so
  259. // tcp/8443 and udp/8443 get distinct tags out of the box.
  260. func TestGenerateInboundTag_KeepsBaseTagWhenFree(t *testing.T) {
  261. setupConflictDB(t)
  262. svc := &InboundService{}
  263. in := &model.Inbound{
  264. Listen: "0.0.0.0",
  265. Port: 8443,
  266. Protocol: model.VLESS,
  267. }
  268. got, err := svc.generateInboundTag(in, 0)
  269. if err != nil {
  270. t.Fatalf("generateInboundTag: %v", err)
  271. }
  272. if got != "in-8443-tcp" {
  273. t.Fatalf("expected in-8443-tcp, got %q", got)
  274. }
  275. }
  276. // updating an inbound on its own port must not flag its own tag as taken;
  277. // that's what ignoreId is for.
  278. func TestGenerateInboundTag_IgnoresSelfOnUpdate(t *testing.T) {
  279. setupConflictDB(t)
  280. seedInboundConflict(t, "in-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  281. var existing model.Inbound
  282. if err := database.GetDB().Where("tag = ?", "in-443-tcp").First(&existing).Error; err != nil {
  283. t.Fatalf("read seeded row: %v", err)
  284. }
  285. svc := &InboundService{}
  286. got, err := svc.generateInboundTag(&existing, existing.Id)
  287. if err != nil {
  288. t.Fatalf("generateInboundTag: %v", err)
  289. }
  290. if got != "in-443-tcp" {
  291. t.Fatalf("self-update must keep base tag, got %q", got)
  292. }
  293. }
  294. // the listen address never appears in the tag; the transport suffix still
  295. // keeps a udp inbound distinct from a tcp one on the same port.
  296. func TestGenerateInboundTag_ListenIgnoredTransportDisambiguates(t *testing.T) {
  297. setupConflictDB(t)
  298. seedInboundConflict(t, "in-443-tcp", "1.2.3.4", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  299. svc := &InboundService{}
  300. udp := &model.Inbound{
  301. Listen: "1.2.3.4",
  302. Port: 443,
  303. Protocol: model.Hysteria,
  304. }
  305. got, err := svc.generateInboundTag(udp, 0)
  306. if err != nil {
  307. t.Fatalf("generateInboundTag: %v", err)
  308. }
  309. if got != "in-443-udp" {
  310. t.Fatalf("expected in-443-udp, got %q", got)
  311. }
  312. }
  313. // inbounds bound to different nodes run on different physical machines,
  314. // so the same port + transport must be allowed across nodes. covers
  315. // local-vs-remote, remote-A-vs-remote-B, and the still-clashing
  316. // same-node case.
  317. func TestCheckPortConflict_NodeScope(t *testing.T) {
  318. setupConflictDB(t)
  319. seedInboundConflictNode(t, "local-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  320. seedInboundConflictNode(t, "node1-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, new(1))
  321. svc := &InboundService{}
  322. cases := []struct {
  323. name string
  324. nodeID *int
  325. want bool
  326. }{
  327. {"new local same port + tcp clashes with local", nil, true},
  328. {"new remote on different node from local is fine", new(2), false},
  329. {"new remote on existing node 1 clashes", new(1), true},
  330. }
  331. for _, c := range cases {
  332. t.Run(c.name, func(t *testing.T) {
  333. candidate := &model.Inbound{
  334. Listen: "0.0.0.0",
  335. Port: 443,
  336. Protocol: model.VLESS,
  337. StreamSettings: `{"network":"tcp"}`,
  338. NodeID: c.nodeID,
  339. }
  340. got, err := svc.checkPortConflict(candidate, 0)
  341. if err != nil {
  342. t.Fatalf("checkPortConflict: %v", err)
  343. }
  344. if (got != nil) != c.want {
  345. t.Fatalf("got conflict=%v, want %v", got != nil, c.want)
  346. }
  347. })
  348. }
  349. }
  350. // when the caller passes an explicit non-empty Tag that doesn't collide,
  351. // resolveInboundTag returns it verbatim. this is the cross-panel path:
  352. // the central panel picks a tag, pushes the inbound to a node, and the
  353. // node must keep that exact tag so the eventual traffic sync-back can
  354. // match the row by tag. previously the node regenerated and the two
  355. // panels diverged, causing a UNIQUE constraint failure on sync.
  356. func TestResolveInboundTag_RespectsCallerTagWhenFree(t *testing.T) {
  357. setupConflictDB(t)
  358. seedInboundConflictNode(t, "in-5000-tcp", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  359. seedInboundConflictNode(t, "in-5000-udp", "0.0.0.0", 5000, model.Hysteria, ``, ``, nil)
  360. svc := &InboundService{}
  361. pushed := &model.Inbound{
  362. Tag: "custom-pushed-tag",
  363. Listen: "0.0.0.0",
  364. Port: 5000,
  365. Protocol: model.VLESS,
  366. StreamSettings: `{"network":"tcp"}`,
  367. NodeID: new(1),
  368. }
  369. got, err := svc.resolveInboundTag(pushed, 0)
  370. if err != nil {
  371. t.Fatalf("resolveInboundTag: %v", err)
  372. }
  373. if got != "custom-pushed-tag" {
  374. t.Fatalf("caller tag must be preserved when free, got %q", got)
  375. }
  376. }
  377. // when the caller leaves Tag empty (the local UI path) resolveInboundTag
  378. // falls back to generateInboundTag, which emits the canonical
  379. // "in-<port>-<transport>" shape.
  380. func TestResolveInboundTag_GeneratesWhenTagEmpty(t *testing.T) {
  381. setupConflictDB(t)
  382. svc := &InboundService{}
  383. in := &model.Inbound{
  384. Listen: "0.0.0.0",
  385. Port: 8443,
  386. Protocol: model.VLESS,
  387. }
  388. got, err := svc.resolveInboundTag(in, 0)
  389. if err != nil {
  390. t.Fatalf("resolveInboundTag: %v", err)
  391. }
  392. if got != "in-8443-tcp" {
  393. t.Fatalf("expected generated in-8443-tcp, got %q", got)
  394. }
  395. }
  396. // when the caller's Tag collides (e.g. a node that was used standalone
  397. // happens to already own the tag the central panel picked),
  398. // resolveInboundTag falls back to generateInboundTag rather than
  399. // failing — the inbound still lands, just under a slightly different
  400. // tag that the central will pick up via the AddInbound response.
  401. func TestResolveInboundTag_RegeneratesOnCollision(t *testing.T) {
  402. setupConflictDB(t)
  403. seedInboundConflictNode(t, "in-5000-tcp", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  404. svc := &InboundService{}
  405. pushed := &model.Inbound{
  406. Tag: "in-5000-tcp",
  407. Listen: "0.0.0.0",
  408. Port: 5000,
  409. Protocol: model.Hysteria,
  410. StreamSettings: ``,
  411. Settings: ``,
  412. }
  413. got, err := svc.resolveInboundTag(pushed, 0)
  414. if err != nil {
  415. t.Fatalf("resolveInboundTag: %v", err)
  416. }
  417. if got == "in-5000-tcp" {
  418. t.Fatalf("colliding caller tag must be replaced, but resolver kept %q", got)
  419. }
  420. }
  421. // inbounds bound to a remote node get the canonical tag prefixed with
  422. // "n<id>-" so the same listen+port+transport can live on the central
  423. // panel and on the node simultaneously without bumping the global
  424. // UNIQUE(inbounds.tag) constraint.
  425. func TestGenerateInboundTag_NodePrefix(t *testing.T) {
  426. setupConflictDB(t)
  427. svc := &InboundService{}
  428. in := &model.Inbound{
  429. Listen: "0.0.0.0",
  430. Port: 443,
  431. Protocol: model.VLESS,
  432. NodeID: new(1),
  433. }
  434. got, err := svc.generateInboundTag(in, 0)
  435. if err != nil {
  436. t.Fatalf("generateInboundTag: %v", err)
  437. }
  438. if got != "n1-in-443-tcp" {
  439. t.Fatalf("expected n1-in-443-tcp, got %q", got)
  440. }
  441. }
  442. // a node-prefixed inbound shouldn't collide with a same-port local one:
  443. // the prefix scopes the tag to that specific node.
  444. func TestGenerateInboundTag_NodePrefixedDoesNotCollideWithLocal(t *testing.T) {
  445. setupConflictDB(t)
  446. seedInboundConflict(t, "in-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  447. svc := &InboundService{}
  448. in := &model.Inbound{
  449. Listen: "0.0.0.0",
  450. Port: 443,
  451. Protocol: model.VLESS,
  452. NodeID: new(1),
  453. }
  454. got, err := svc.generateInboundTag(in, 0)
  455. if err != nil {
  456. t.Fatalf("generateInboundTag: %v", err)
  457. }
  458. if got != "n1-in-443-tcp" {
  459. t.Fatalf("expected n1-in-443-tcp, got %q", got)
  460. }
  461. }
  462. // updating an inbound must not see itself as a conflict, that's what
  463. // ignoreId is for.
  464. func TestCheckPortConflict_IgnoreSelfOnUpdate(t *testing.T) {
  465. setupConflictDB(t)
  466. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  467. var existing model.Inbound
  468. if err := database.GetDB().Where("tag = ?", "vless-443").First(&existing).Error; err != nil {
  469. t.Fatalf("read seeded row: %v", err)
  470. }
  471. svc := &InboundService{}
  472. if exist, err := svc.checkPortConflict(&existing, existing.Id); err != nil || exist != nil {
  473. t.Fatalf("self-update must not be flagged as conflict; exist=%v err=%v", exist, err)
  474. }
  475. }
  476. // streamSettings.network=quic rides on UDP at L4, so a QUIC inbound must
  477. // conflict with a UDP-only neighbour (hysteria) on the same port but not
  478. // with a TCP-only one. covers the gap left by the original kcp-only check.
  479. func TestCheckPortConflict_QUICTreatedAsUDP(t *testing.T) {
  480. quic := &model.Inbound{
  481. Tag: "vless-quic-443",
  482. Listen: "0.0.0.0",
  483. Port: 443,
  484. Protocol: model.VLESS,
  485. StreamSettings: `{"network":"quic"}`,
  486. }
  487. t.Run("conflicts with hysteria/udp", func(t *testing.T) {
  488. setupConflictDB(t)
  489. seedInboundConflict(t, "hyst-443", "0.0.0.0", 443, model.Hysteria, ``, ``)
  490. svc := &InboundService{}
  491. if exist, err := svc.checkPortConflict(quic, 0); err != nil || exist == nil {
  492. t.Fatalf("quic on same port as hysteria must conflict; exist=%v err=%v", exist, err)
  493. }
  494. })
  495. t.Run("coexists with vless/tcp", func(t *testing.T) {
  496. setupConflictDB(t)
  497. seedInboundConflict(t, "vless-tcp-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  498. svc := &InboundService{}
  499. if exist, err := svc.checkPortConflict(quic, 0); err != nil || exist != nil {
  500. t.Fatalf("quic and tcp on same port must coexist; exist=%v err=%v", exist, err)
  501. }
  502. })
  503. }
  504. // tunnel (dokodemo-door) carries its L4 transport list in
  505. // settings.allowedNetwork, not settings.network. verify the predicate
  506. // picks the right field for each protocol.
  507. func TestCheckPortConflict_TunnelAllowedNetwork(t *testing.T) {
  508. setupConflictDB(t)
  509. seedInboundConflict(t, "tunnel-udp-443", "0.0.0.0", 443, model.Tunnel, ``, `{"allowedNetwork":"udp"}`)
  510. svc := &InboundService{}
  511. // tcp inbound on same port should coexist with udp-only tunnel.
  512. tcpNeighbour := &model.Inbound{
  513. Tag: "vless-443",
  514. Listen: "0.0.0.0",
  515. Port: 443,
  516. Protocol: model.VLESS,
  517. StreamSettings: `{"network":"tcp"}`,
  518. }
  519. if exist, err := svc.checkPortConflict(tcpNeighbour, 0); err != nil || exist != nil {
  520. t.Fatalf("tunnel/udp and vless/tcp on same port must coexist; exist=%v err=%v", exist, err)
  521. }
  522. // udp neighbour (hysteria) on same port must conflict.
  523. udpNeighbour := &model.Inbound{
  524. Tag: "hyst-443",
  525. Listen: "0.0.0.0",
  526. Port: 443,
  527. Protocol: model.Hysteria,
  528. }
  529. if exist, err := svc.checkPortConflict(udpNeighbour, 0); err != nil || exist == nil {
  530. t.Fatalf("tunnel/udp and hysteria on same port must conflict; exist=%v err=%v", exist, err)
  531. }
  532. }
  533. // the rich conflict detail surfaced to the user must name the offending
  534. // inbound (by remark when available) and the shared L4 transport(s).
  535. func TestCheckPortConflict_DetailMessage(t *testing.T) {
  536. setupConflictDB(t)
  537. seeded := &model.Inbound{
  538. Tag: "vless-443",
  539. Remark: "my-vless",
  540. Enable: true,
  541. Listen: "0.0.0.0",
  542. Port: 443,
  543. Protocol: model.VLESS,
  544. StreamSettings: `{"network":"tcp"}`,
  545. Settings: `{}`,
  546. }
  547. if err := database.GetDB().Create(seeded).Error; err != nil {
  548. t.Fatalf("seed inbound: %v", err)
  549. }
  550. svc := &InboundService{}
  551. candidate := &model.Inbound{
  552. Tag: "trojan-443",
  553. Listen: "0.0.0.0",
  554. Port: 443,
  555. Protocol: model.Trojan,
  556. StreamSettings: `{"network":"ws"}`,
  557. }
  558. got, err := svc.checkPortConflict(candidate, 0)
  559. if err != nil || got == nil {
  560. t.Fatalf("expected conflict, got=%v err=%v", got, err)
  561. }
  562. msg := got.String()
  563. if !strings.Contains(msg, "my-vless") {
  564. t.Fatalf("message should mention the conflicting inbound's remark; got %q", msg)
  565. }
  566. if !strings.Contains(msg, "tcp") {
  567. t.Fatalf("message should mention the shared L4 transport; got %q", msg)
  568. }
  569. if !strings.Contains(msg, "443") {
  570. t.Fatalf("message should mention the port; got %q", msg)
  571. }
  572. }
  573. // isAutoGeneratedTag must recognise the tags generateInboundTag emits (so an
  574. // edit that changes port/transport re-derives them) while leaving user-typed
  575. // or cross-panel tags untouched.
  576. func TestIsAutoGeneratedTag(t *testing.T) {
  577. tcp := transportTCP
  578. cases := []struct {
  579. name string
  580. tag string
  581. port int
  582. nodeID *int
  583. bits transportBits
  584. want bool
  585. }{
  586. {"canonical", "in-443-tcp", 443, nil, tcp, true},
  587. {"canonical udp", "in-443-udp", 443, nil, transportUDP, true},
  588. {"dedup suffix", "in-443-tcp-2", 443, nil, tcp, true},
  589. {"node prefixed", "n1-in-443-tcp", 443, new(1), tcp, true},
  590. {"legacy listen-scoped is now custom", "in-127.0.0.1:443-tcp", 443, nil, tcp, false},
  591. {"custom tag", "my-cool-tag", 443, nil, tcp, false},
  592. {"stale port", "in-443-tcp", 8443, nil, tcp, false},
  593. {"stale transport", "in-443-tcp", 443, nil, transportUDP, false},
  594. {"non-numeric suffix", "in-443-tcp-x", 443, nil, tcp, false},
  595. {"empty suffix", "in-443-tcp-", 443, nil, tcp, false},
  596. }
  597. for _, c := range cases {
  598. t.Run(c.name, func(t *testing.T) {
  599. if got := isAutoGeneratedTag(c.tag, c.port, c.nodeID, c.bits); got != c.want {
  600. t.Fatalf("isAutoGeneratedTag(%q) = %v, want %v", c.tag, got, c.want)
  601. }
  602. })
  603. }
  604. }
  605. // the internal Xray API inbound (tag "api", loopback TCP) isn't a DB row, so
  606. // checkPortConflict must still reject a local user inbound that reuses its
  607. // reserved port — otherwise Xray binds the port twice (#5304).
  608. func TestCheckPortConflict_ReservedAPIPortBlockedLocal(t *testing.T) {
  609. setupConflictDB(t)
  610. svc := &InboundService{}
  611. candidate := &model.Inbound{
  612. Tag: "user-62789",
  613. Listen: "0.0.0.0",
  614. Port: defaultXrayAPIPort,
  615. Protocol: model.VLESS,
  616. StreamSettings: `{"network":"tcp"}`,
  617. }
  618. got, err := svc.checkPortConflict(candidate, 0)
  619. if err != nil {
  620. t.Fatalf("checkPortConflict: %v", err)
  621. }
  622. if got == nil {
  623. t.Fatalf("local inbound on the reserved API port %d must conflict", defaultXrayAPIPort)
  624. }
  625. if msg := got.String(); !strings.Contains(msg, "api") {
  626. t.Fatalf("conflict message should name the api inbound; got %q", msg)
  627. }
  628. }
  629. // nodes run their own Xray with their own API port, so a node inbound on the
  630. // central panel's reserved API port must be allowed.
  631. func TestCheckPortConflict_ReservedAPIPortAllowedOnNode(t *testing.T) {
  632. setupConflictDB(t)
  633. svc := &InboundService{}
  634. candidate := &model.Inbound{
  635. Tag: "node-62789",
  636. Listen: "0.0.0.0",
  637. Port: defaultXrayAPIPort,
  638. Protocol: model.VLESS,
  639. StreamSettings: `{"network":"tcp"}`,
  640. NodeID: new(1),
  641. }
  642. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  643. t.Fatalf("node inbound on the reserved API port must be allowed; got=%v err=%v", got, err)
  644. }
  645. }
  646. // the API inbound is TCP-only, so a UDP-only inbound (e.g. hysteria) may share
  647. // its port — same tcp/udp coexistence the rest of the checks allow.
  648. func TestCheckPortConflict_ReservedAPIPortUDPCoexists(t *testing.T) {
  649. setupConflictDB(t)
  650. svc := &InboundService{}
  651. candidate := &model.Inbound{
  652. Tag: "hyst-62789",
  653. Listen: "0.0.0.0",
  654. Port: defaultXrayAPIPort,
  655. Protocol: model.Hysteria,
  656. }
  657. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  658. t.Fatalf("udp-only inbound must coexist with the tcp API inbound; got=%v err=%v", got, err)
  659. }
  660. }
  661. // amneziawgRoutedSettings builds a minimal but complete AmneziaWG settings
  662. // blob with one qualifying, enabled peer -- the shape that makes
  663. // injectAmneziawgnetSocks (and therefore checkAmneziawgnetSocksConflict)
  664. // create a relay inbound at all. The routeThroughXray field is kept in the
  665. // JSON (a stale value from a pre-cutover install) specifically to prove
  666. // it's now ignored -- see the "RouteThroughXrayOff" test below.
  667. const amneziawgRoutedSettings = `{"server":{"privateKey":"priv","publicKey":"pub","subnetIp":"10.8.1.0","subnetCidr":24,"routeThroughXray":true},"clients":[{"email":"a@x","enable":true,"publicKey":"pub-a","allowedIPs":["10.8.1.2/32"]}]}`
  668. // An enabled AmneziaWG inbound's automatic Xray SOCKS5 relay inbound
  669. // (injectAmneziawgnetSocks) is a synthetic loopback inbound, not a database
  670. // row, so checkPortConflict needs its own check to catch a collision --
  671. // exactly the same shape of problem as the reserved API port above.
  672. func TestCheckPortConflict_AmneziawgnetSocksRelayBlockedLocal(t *testing.T) {
  673. setupConflictDB(t)
  674. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  675. var awgInbound model.Inbound
  676. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  677. t.Fatalf("read seeded row: %v", err)
  678. }
  679. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  680. svc := &InboundService{}
  681. candidate := &model.Inbound{
  682. Tag: "vless-bridge",
  683. Listen: "0.0.0.0",
  684. Port: relayPort,
  685. Protocol: model.VLESS,
  686. }
  687. got, err := svc.checkPortConflict(candidate, 0)
  688. if err != nil {
  689. t.Fatalf("checkPortConflict: %v", err)
  690. }
  691. if got == nil {
  692. t.Fatalf("a local inbound on the AmneziaWG relay port %d must conflict", relayPort)
  693. }
  694. if msg := got.String(); !strings.Contains(msg, "awg-1") {
  695. t.Fatalf("conflict message should name the owning AmneziaWG inbound; got %q", msg)
  696. }
  697. }
  698. // Nodes run their own Xray, so a node inbound landing on the central panel's
  699. // AmneziaWG relay port must be allowed -- the relay inbound only ever binds
  700. // 127.0.0.1 on the local panel's own Xray.
  701. func TestCheckPortConflict_AmneziawgnetSocksRelayAllowedOnNode(t *testing.T) {
  702. setupConflictDB(t)
  703. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  704. var awgInbound model.Inbound
  705. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  706. t.Fatalf("read seeded row: %v", err)
  707. }
  708. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  709. svc := &InboundService{}
  710. candidate := &model.Inbound{
  711. Tag: "node-bridge",
  712. Listen: "0.0.0.0",
  713. Port: relayPort,
  714. Protocol: model.VLESS,
  715. NodeID: new(1),
  716. }
  717. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  718. t.Fatalf("a node inbound on the local AmneziaWG relay port must be allowed; got=%v err=%v", got, err)
  719. }
  720. }
  721. // A disabled AmneziaWG inbound never gets a relay inbound injected
  722. // (injectAmneziawgnetSocks skips !inbound.Enable), so its "reserved" port
  723. // must not block anything.
  724. func TestCheckPortConflict_AmneziawgnetSocksRelayIgnoredWhenDisabled(t *testing.T) {
  725. setupConflictDB(t)
  726. awg := &model.Inbound{Tag: "awg-1", Enable: false, Listen: "0.0.0.0", Port: 51820, Protocol: model.AmneziaWG, Settings: `{}`}
  727. if err := database.GetDB().Create(awg).Error; err != nil {
  728. t.Fatalf("seed disabled awg inbound: %v", err)
  729. }
  730. relayPort := amneziawgnet.SOCKSPortForInbound(awg.Id)
  731. svc := &InboundService{}
  732. candidate := &model.Inbound{
  733. Tag: "vless-bridge",
  734. Listen: "0.0.0.0",
  735. Port: relayPort,
  736. Protocol: model.VLESS,
  737. }
  738. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  739. t.Fatalf("a disabled AmneziaWG inbound's port must not be reserved; got=%v err=%v", got, err)
  740. }
  741. }
  742. // Unlike the retired kernel-module bridge, the embedded relay has no
  743. // RouteThroughXray-style opt-in -- every qualifying AmneziaWG inbound
  744. // reserves its relay port regardless of that (now-vestigial) field's value,
  745. // including a stale routeThroughXray:true left over from a pre-cutover
  746. // install (amneziawgRoutedSettings).
  747. func TestCheckPortConflict_AmneziawgnetSocksRelayReservedRegardlessOfLegacyRouteThroughXrayField(t *testing.T) {
  748. setupConflictDB(t)
  749. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{"server":{"privateKey":"priv","publicKey":"pub","subnetIp":"10.8.1.0","subnetCidr":24},"clients":[{"email":"a@x","enable":true,"publicKey":"pub-a","allowedIPs":["10.8.1.2/32"]}]}`)
  750. var awgInbound model.Inbound
  751. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  752. t.Fatalf("read seeded row: %v", err)
  753. }
  754. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  755. svc := &InboundService{}
  756. candidate := &model.Inbound{
  757. Tag: "vless-bridge",
  758. Listen: "0.0.0.0",
  759. Port: relayPort,
  760. Protocol: model.VLESS,
  761. }
  762. got, err := svc.checkPortConflict(candidate, 0)
  763. if err != nil {
  764. t.Fatalf("checkPortConflict: %v", err)
  765. }
  766. if got == nil {
  767. t.Fatalf("an enabled, qualifying AmneziaWG inbound must reserve its relay port even with RouteThroughXray left at its default")
  768. }
  769. }
  770. // A qualifying AmneziaWG inbound with no enabled/valid peer at all never
  771. // gets a relay inbound (amneziawg.InstanceFromInbound returns ok=false), so
  772. // its port isn't reserved.
  773. func TestCheckPortConflict_AmneziawgnetSocksRelayIgnoredWhenNoQualifyingPeer(t *testing.T) {
  774. setupConflictDB(t)
  775. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{}`)
  776. var awgInbound model.Inbound
  777. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  778. t.Fatalf("read seeded row: %v", err)
  779. }
  780. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  781. svc := &InboundService{}
  782. candidate := &model.Inbound{
  783. Tag: "vless-bridge",
  784. Listen: "0.0.0.0",
  785. Port: relayPort,
  786. Protocol: model.VLESS,
  787. }
  788. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  789. t.Fatalf("an AmneziaWG inbound with no qualifying peer must not reserve its relay port; got=%v err=%v", got, err)
  790. }
  791. }
  792. // An unrelated port never conflicts with the relay inbound.
  793. func TestCheckPortConflict_AmneziawgnetSocksRelayDifferentPortAllowed(t *testing.T) {
  794. setupConflictDB(t)
  795. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  796. svc := &InboundService{}
  797. candidate := &model.Inbound{
  798. Tag: "vless-elsewhere",
  799. Listen: "0.0.0.0",
  800. Port: 9999,
  801. Protocol: model.VLESS,
  802. }
  803. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  804. t.Fatalf("an unrelated port must not conflict with the AmneziaWG relay inbound; got=%v err=%v", got, err)
  805. }
  806. }
  807. // The reverse direction: saving an AmneziaWG inbound whose own derived relay
  808. // port happens to equal another inbound's real port must also be rejected,
  809. // not just the already-covered "someone else picks my relay port" case.
  810. func TestCheckPortConflict_AmneziawgnetSocksRelayReverseDirectionBlockedOnUpdate(t *testing.T) {
  811. setupConflictDB(t)
  812. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  813. var awgInbound model.Inbound
  814. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  815. t.Fatalf("read seeded row: %v", err)
  816. }
  817. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  818. seedInboundConflict(t, "vless-1", "0.0.0.0", relayPort, model.VLESS, ``, `{}`)
  819. svc := &InboundService{}
  820. candidate := &model.Inbound{
  821. Id: awgInbound.Id,
  822. Tag: "awg-1",
  823. Listen: "0.0.0.0",
  824. Port: 51820,
  825. Protocol: model.AmneziaWG,
  826. Settings: amneziawgRoutedSettings,
  827. }
  828. got, err := svc.checkPortConflict(candidate, awgInbound.Id)
  829. if err != nil {
  830. t.Fatalf("checkPortConflict: %v", err)
  831. }
  832. if got == nil {
  833. t.Fatalf("awg-1's own derived relay port %d collides with vless-1's real port; must be rejected", relayPort)
  834. }
  835. }