port_conflict_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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/dbtest"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. )
  14. // the panel logger is a process-wide singleton. init it once per test
  15. // binary so a stray warning from gorm doesn't blow up on a nil logger.
  16. var portConflictLoggerOnce sync.Once
  17. // setupConflictDB wires a temp sqlite db so checkPortConflict can read
  18. // real candidates. closes the db before t.TempDir cleans up so windows
  19. // doesn't refuse to remove the file.
  20. func setupConflictDB(t *testing.T) {
  21. t.Helper()
  22. portConflictLoggerOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) })
  23. dbDir := t.TempDir()
  24. t.Setenv("XUI_DB_FOLDER", dbDir)
  25. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  26. }
  27. func seedInboundConflict(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string) {
  28. t.Helper()
  29. seedInboundConflictNode(t, tag, listen, port, protocol, streamSettings, settings, nil)
  30. }
  31. func seedInboundConflictNode(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string, nodeID *int) {
  32. t.Helper()
  33. in := &model.Inbound{
  34. Tag: tag,
  35. Enable: true,
  36. Listen: listen,
  37. Port: port,
  38. Protocol: protocol,
  39. StreamSettings: streamSettings,
  40. Settings: settings,
  41. NodeID: nodeID,
  42. }
  43. if err := database.GetDB().Create(in).Error; err != nil {
  44. t.Fatalf("seed inbound %s: %v", tag, err)
  45. }
  46. }
  47. func TestInboundTransports(t *testing.T) {
  48. cases := []struct {
  49. name string
  50. protocol model.Protocol
  51. streamSettings string
  52. settings string
  53. want transportBits
  54. }{
  55. {"vless default tcp", model.VLESS, `{"network":"tcp"}`, ``, transportTCP},
  56. {"vless ws (still tcp)", model.VLESS, `{"network":"ws"}`, ``, transportTCP},
  57. {"vless kcp is udp", model.VLESS, `{"network":"kcp"}`, ``, transportUDP},
  58. {"vless empty stream defaults to tcp", model.VLESS, ``, ``, transportTCP},
  59. {"vless garbage stream stays tcp", model.VLESS, `not json`, ``, transportTCP},
  60. {"vmess default tcp", model.VMESS, `{"network":"tcp"}`, ``, transportTCP},
  61. {"trojan grpc is tcp", model.Trojan, `{"network":"grpc"}`, ``, transportTCP},
  62. {"hysteria forced udp", model.Hysteria, `{"network":"tcp"}`, ``, transportUDP},
  63. {"wireguard forced udp", model.WireGuard, ``, ``, transportUDP},
  64. {"shadowsocks tcp,udp", model.Shadowsocks, ``, `{"network":"tcp,udp"}`, transportTCP | transportUDP},
  65. {"shadowsocks udp only", model.Shadowsocks, ``, `{"network":"udp"}`, transportUDP},
  66. {"shadowsocks tcp only", model.Shadowsocks, ``, `{"network":"tcp"}`, transportTCP},
  67. {"shadowsocks empty network falls back to streamSettings", model.Shadowsocks, `{"network":"tcp"}`, `{}`, transportTCP},
  68. {"mixed udp on", model.Mixed, `{"network":"tcp"}`, `{"udp":true}`, transportTCP | transportUDP},
  69. {"mixed udp off", model.Mixed, `{"network":"tcp"}`, `{"udp":false}`, transportTCP},
  70. {"mixed udp missing", model.Mixed, `{"network":"tcp"}`, `{}`, transportTCP},
  71. }
  72. for _, c := range cases {
  73. t.Run(c.name, func(t *testing.T) {
  74. got := inboundTransports(c.protocol, c.streamSettings, c.settings)
  75. if got != c.want {
  76. t.Fatalf("got bits %#b, want %#b", got, c.want)
  77. }
  78. })
  79. }
  80. }
  81. func TestListenOverlaps(t *testing.T) {
  82. cases := []struct {
  83. a, b string
  84. want bool
  85. }{
  86. {"", "", true},
  87. {"0.0.0.0", "", true},
  88. {"0.0.0.0", "1.2.3.4", true},
  89. {"::", "1.2.3.4", true},
  90. {"::0", "fe80::1", true},
  91. {"1.2.3.4", "1.2.3.4", true},
  92. {"1.2.3.4", "5.6.7.8", false},
  93. {"1.2.3.4", "::1", false},
  94. }
  95. for _, c := range cases {
  96. if got := listenOverlaps(bindAddr{listen: c.a}, bindAddr{listen: c.b}); got != c.want {
  97. t.Errorf("listenOverlaps(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
  98. }
  99. }
  100. }
  101. // the actual case from #4103: tcp/443 vless reality and udp/443
  102. // hysteria must be allowed to coexist on the same port.
  103. func TestCheckPortConflict_TCPandUDPCoexistOnSamePort(t *testing.T) {
  104. setupConflictDB(t)
  105. seedInboundConflict(t, "vless-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  106. svc := &InboundService{}
  107. hyst2 := &model.Inbound{
  108. Tag: "hyst2-443-udp",
  109. Listen: "0.0.0.0",
  110. Port: 443,
  111. Protocol: model.Hysteria,
  112. }
  113. exist, err := svc.checkPortConflict(hyst2, 0)
  114. if err != nil {
  115. t.Fatalf("checkPortConflict: %v", err)
  116. }
  117. if exist != nil {
  118. t.Fatalf("vless/tcp and hysteria2/udp on the same port must be allowed to coexist")
  119. }
  120. }
  121. // two tcp inbounds on the same port still conflict.
  122. func TestCheckPortConflict_TCPCollidesWithTCP(t *testing.T) {
  123. setupConflictDB(t)
  124. seedInboundConflict(t, "vless-443-a", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  125. svc := &InboundService{}
  126. other := &model.Inbound{
  127. Tag: "vless-443-b",
  128. Listen: "0.0.0.0",
  129. Port: 443,
  130. Protocol: model.Trojan,
  131. StreamSettings: `{"network":"ws"}`,
  132. }
  133. exist, err := svc.checkPortConflict(other, 0)
  134. if err != nil {
  135. t.Fatalf("checkPortConflict: %v", err)
  136. }
  137. if exist == nil {
  138. t.Fatalf("two tcp inbounds on the same port must still conflict")
  139. }
  140. }
  141. // two udp inbounds (e.g. hysteria2 vs wireguard) on the same port also
  142. // conflict, since they fight for the same socket.
  143. func TestCheckPortConflict_UDPCollidesWithUDP(t *testing.T) {
  144. setupConflictDB(t)
  145. seedInboundConflict(t, "hyst2-443", "0.0.0.0", 443, model.Hysteria, ``, ``)
  146. svc := &InboundService{}
  147. wg := &model.Inbound{
  148. Tag: "wg-443",
  149. Listen: "0.0.0.0",
  150. Port: 443,
  151. Protocol: model.WireGuard,
  152. }
  153. exist, err := svc.checkPortConflict(wg, 0)
  154. if err != nil {
  155. t.Fatalf("checkPortConflict: %v", err)
  156. }
  157. if exist == nil {
  158. t.Fatalf("two udp inbounds on the same port must conflict")
  159. }
  160. }
  161. // shadowsocks listening on tcp+udp eats the whole port for both
  162. // transports, so neither a tcp nor a udp neighbour is allowed.
  163. func TestCheckPortConflict_ShadowsocksDualListenBlocksBoth(t *testing.T) {
  164. setupConflictDB(t)
  165. seedInboundConflict(t, "ss-443-dual", "0.0.0.0", 443, model.Shadowsocks, ``, `{"network":"tcp,udp"}`)
  166. svc := &InboundService{}
  167. tcpClash := &model.Inbound{
  168. Tag: "vless-443",
  169. Listen: "0.0.0.0",
  170. Port: 443,
  171. Protocol: model.VLESS,
  172. StreamSettings: `{"network":"tcp"}`,
  173. }
  174. if exist, err := svc.checkPortConflict(tcpClash, 0); err != nil || exist == nil {
  175. t.Fatalf("tcp inbound should clash with shadowsocks tcp,udp; exist=%v err=%v", exist, err)
  176. }
  177. udpClash := &model.Inbound{
  178. Tag: "hyst2-443",
  179. Listen: "0.0.0.0",
  180. Port: 443,
  181. Protocol: model.Hysteria,
  182. }
  183. if exist, err := svc.checkPortConflict(udpClash, 0); err != nil || exist == nil {
  184. t.Fatalf("udp inbound should clash with shadowsocks tcp,udp; exist=%v err=%v", exist, err)
  185. }
  186. }
  187. // different ports never conflict regardless of transport.
  188. func TestCheckPortConflict_DifferentPortNeverConflicts(t *testing.T) {
  189. setupConflictDB(t)
  190. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  191. svc := &InboundService{}
  192. other := &model.Inbound{
  193. Tag: "vless-444",
  194. Listen: "0.0.0.0",
  195. Port: 444,
  196. Protocol: model.VLESS,
  197. StreamSettings: `{"network":"tcp"}`,
  198. }
  199. if exist, err := svc.checkPortConflict(other, 0); err != nil || exist != nil {
  200. t.Fatalf("different port must not conflict; exist=%v err=%v", exist, err)
  201. }
  202. }
  203. // specific listen addresses on the same port don't clash with each other,
  204. // but do clash with any-address on the same port (preserved from the old
  205. // check).
  206. func TestCheckPortConflict_ListenOverlapPreserved(t *testing.T) {
  207. setupConflictDB(t)
  208. seedInboundConflict(t, "vless-1.2.3.4", "1.2.3.4", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  209. svc := &InboundService{}
  210. // different specific address, same port + transport: no conflict.
  211. other := &model.Inbound{
  212. Tag: "vless-5.6.7.8",
  213. Listen: "5.6.7.8",
  214. Port: 443,
  215. Protocol: model.VLESS,
  216. StreamSettings: `{"network":"tcp"}`,
  217. }
  218. if exist, err := svc.checkPortConflict(other, 0); err != nil || exist != nil {
  219. t.Fatalf("different specific listen must not conflict; exist=%v err=%v", exist, err)
  220. }
  221. // any-address vs specific on same transport: conflict (any-addr wins).
  222. anyAddr := &model.Inbound{
  223. Tag: "vless-any",
  224. Listen: "0.0.0.0",
  225. Port: 443,
  226. Protocol: model.VLESS,
  227. StreamSettings: `{"network":"tcp"}`,
  228. }
  229. if exist, err := svc.checkPortConflict(anyAddr, 0); err != nil || exist == nil {
  230. t.Fatalf("any-addr on same port+transport must conflict with specific; exist=%v err=%v", exist, err)
  231. }
  232. }
  233. // even with a stale legacy tag owning "in-443", a new UDP-side
  234. // inbound gets a fully qualified canonical tag and does not collide.
  235. func TestGenerateInboundTag_DisambiguatesByTransportOnSamePort(t *testing.T) {
  236. setupConflictDB(t)
  237. seedInboundConflict(t, "in-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  238. svc := &InboundService{}
  239. udp := &model.Inbound{
  240. Listen: "0.0.0.0",
  241. Port: 443,
  242. Protocol: model.Hysteria,
  243. }
  244. got, err := svc.generateInboundTag(udp, 0)
  245. if err != nil {
  246. t.Fatalf("generateInboundTag: %v", err)
  247. }
  248. if got != "in-443-udp" {
  249. t.Fatalf("expected in-443-udp, got %q", got)
  250. }
  251. }
  252. // when the port is free, the canonical tag carries the transport so
  253. // tcp/8443 and udp/8443 get distinct tags out of the box.
  254. func TestGenerateInboundTag_KeepsBaseTagWhenFree(t *testing.T) {
  255. setupConflictDB(t)
  256. svc := &InboundService{}
  257. in := &model.Inbound{
  258. Listen: "0.0.0.0",
  259. Port: 8443,
  260. Protocol: model.VLESS,
  261. }
  262. got, err := svc.generateInboundTag(in, 0)
  263. if err != nil {
  264. t.Fatalf("generateInboundTag: %v", err)
  265. }
  266. if got != "in-8443-tcp" {
  267. t.Fatalf("expected in-8443-tcp, got %q", got)
  268. }
  269. }
  270. // updating an inbound on its own port must not flag its own tag as taken;
  271. // that's what ignoreId is for.
  272. func TestGenerateInboundTag_IgnoresSelfOnUpdate(t *testing.T) {
  273. setupConflictDB(t)
  274. seedInboundConflict(t, "in-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  275. var existing model.Inbound
  276. if err := database.GetDB().Where("tag = ?", "in-443-tcp").First(&existing).Error; err != nil {
  277. t.Fatalf("read seeded row: %v", err)
  278. }
  279. svc := &InboundService{}
  280. got, err := svc.generateInboundTag(&existing, existing.Id)
  281. if err != nil {
  282. t.Fatalf("generateInboundTag: %v", err)
  283. }
  284. if got != "in-443-tcp" {
  285. t.Fatalf("self-update must keep base tag, got %q", got)
  286. }
  287. }
  288. // the listen address never appears in the tag; the transport suffix still
  289. // keeps a udp inbound distinct from a tcp one on the same port.
  290. func TestGenerateInboundTag_ListenIgnoredTransportDisambiguates(t *testing.T) {
  291. setupConflictDB(t)
  292. seedInboundConflict(t, "in-443-tcp", "1.2.3.4", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  293. svc := &InboundService{}
  294. udp := &model.Inbound{
  295. Listen: "1.2.3.4",
  296. Port: 443,
  297. Protocol: model.Hysteria,
  298. }
  299. got, err := svc.generateInboundTag(udp, 0)
  300. if err != nil {
  301. t.Fatalf("generateInboundTag: %v", err)
  302. }
  303. if got != "in-443-udp" {
  304. t.Fatalf("expected in-443-udp, got %q", got)
  305. }
  306. }
  307. // inbounds bound to different nodes run on different physical machines,
  308. // so the same port + transport must be allowed across nodes. covers
  309. // local-vs-remote, remote-A-vs-remote-B, and the still-clashing
  310. // same-node case.
  311. func TestCheckPortConflict_NodeScope(t *testing.T) {
  312. setupConflictDB(t)
  313. seedInboundConflictNode(t, "local-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  314. seedInboundConflictNode(t, "node1-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`, new(1))
  315. svc := &InboundService{}
  316. cases := []struct {
  317. name string
  318. nodeID *int
  319. want bool
  320. }{
  321. {"new local same port + tcp clashes with local", nil, true},
  322. {"new remote on different node from local is fine", new(2), false},
  323. {"new remote on existing node 1 clashes", new(1), true},
  324. }
  325. for _, c := range cases {
  326. t.Run(c.name, func(t *testing.T) {
  327. candidate := &model.Inbound{
  328. Listen: "0.0.0.0",
  329. Port: 443,
  330. Protocol: model.VLESS,
  331. StreamSettings: `{"network":"tcp"}`,
  332. NodeID: c.nodeID,
  333. }
  334. got, err := svc.checkPortConflict(candidate, 0)
  335. if err != nil {
  336. t.Fatalf("checkPortConflict: %v", err)
  337. }
  338. if (got != nil) != c.want {
  339. t.Fatalf("got conflict=%v, want %v", got != nil, c.want)
  340. }
  341. })
  342. }
  343. }
  344. // when the caller passes an explicit non-empty Tag that doesn't collide,
  345. // resolveInboundTag returns it verbatim. this is the cross-panel path:
  346. // the central panel picks a tag, pushes the inbound to a node, and the
  347. // node must keep that exact tag so the eventual traffic sync-back can
  348. // match the row by tag. previously the node regenerated and the two
  349. // panels diverged, causing a UNIQUE constraint failure on sync.
  350. func TestResolveInboundTag_RespectsCallerTagWhenFree(t *testing.T) {
  351. setupConflictDB(t)
  352. seedInboundConflictNode(t, "in-5000-tcp", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  353. seedInboundConflictNode(t, "in-5000-udp", "0.0.0.0", 5000, model.Hysteria, ``, ``, nil)
  354. svc := &InboundService{}
  355. pushed := &model.Inbound{
  356. Tag: "custom-pushed-tag",
  357. Listen: "0.0.0.0",
  358. Port: 5000,
  359. Protocol: model.VLESS,
  360. StreamSettings: `{"network":"tcp"}`,
  361. NodeID: new(1),
  362. }
  363. got, err := svc.resolveInboundTag(pushed, 0)
  364. if err != nil {
  365. t.Fatalf("resolveInboundTag: %v", err)
  366. }
  367. if got != "custom-pushed-tag" {
  368. t.Fatalf("caller tag must be preserved when free, got %q", got)
  369. }
  370. }
  371. // when the caller leaves Tag empty (the local UI path) resolveInboundTag
  372. // falls back to generateInboundTag, which emits the canonical
  373. // "in-<port>-<transport>" shape.
  374. func TestResolveInboundTag_GeneratesWhenTagEmpty(t *testing.T) {
  375. setupConflictDB(t)
  376. svc := &InboundService{}
  377. in := &model.Inbound{
  378. Listen: "0.0.0.0",
  379. Port: 8443,
  380. Protocol: model.VLESS,
  381. }
  382. got, err := svc.resolveInboundTag(in, 0)
  383. if err != nil {
  384. t.Fatalf("resolveInboundTag: %v", err)
  385. }
  386. if got != "in-8443-tcp" {
  387. t.Fatalf("expected generated in-8443-tcp, got %q", got)
  388. }
  389. }
  390. // when the caller's Tag collides (e.g. a node that was used standalone
  391. // happens to already own the tag the central panel picked),
  392. // resolveInboundTag falls back to generateInboundTag rather than
  393. // failing — the inbound still lands, just under a slightly different
  394. // tag that the central will pick up via the AddInbound response.
  395. func TestResolveInboundTag_RegeneratesOnCollision(t *testing.T) {
  396. setupConflictDB(t)
  397. seedInboundConflictNode(t, "in-5000-tcp", "0.0.0.0", 5000, model.VLESS, `{"network":"tcp"}`, `{}`, nil)
  398. svc := &InboundService{}
  399. pushed := &model.Inbound{
  400. Tag: "in-5000-tcp",
  401. Listen: "0.0.0.0",
  402. Port: 5000,
  403. Protocol: model.Hysteria,
  404. StreamSettings: ``,
  405. Settings: ``,
  406. }
  407. got, err := svc.resolveInboundTag(pushed, 0)
  408. if err != nil {
  409. t.Fatalf("resolveInboundTag: %v", err)
  410. }
  411. if got == "in-5000-tcp" {
  412. t.Fatalf("colliding caller tag must be replaced, but resolver kept %q", got)
  413. }
  414. }
  415. // inbounds bound to a remote node get the canonical tag prefixed with
  416. // "n<id>-" so the same listen+port+transport can live on the central
  417. // panel and on the node simultaneously without bumping the global
  418. // UNIQUE(inbounds.tag) constraint.
  419. func TestGenerateInboundTag_NodePrefix(t *testing.T) {
  420. setupConflictDB(t)
  421. svc := &InboundService{}
  422. in := &model.Inbound{
  423. Listen: "0.0.0.0",
  424. Port: 443,
  425. Protocol: model.VLESS,
  426. NodeID: new(1),
  427. }
  428. got, err := svc.generateInboundTag(in, 0)
  429. if err != nil {
  430. t.Fatalf("generateInboundTag: %v", err)
  431. }
  432. if got != "n1-in-443-tcp" {
  433. t.Fatalf("expected n1-in-443-tcp, got %q", got)
  434. }
  435. }
  436. // a node-prefixed inbound shouldn't collide with a same-port local one:
  437. // the prefix scopes the tag to that specific node.
  438. func TestGenerateInboundTag_NodePrefixedDoesNotCollideWithLocal(t *testing.T) {
  439. setupConflictDB(t)
  440. seedInboundConflict(t, "in-443-tcp", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  441. svc := &InboundService{}
  442. in := &model.Inbound{
  443. Listen: "0.0.0.0",
  444. Port: 443,
  445. Protocol: model.VLESS,
  446. NodeID: new(1),
  447. }
  448. got, err := svc.generateInboundTag(in, 0)
  449. if err != nil {
  450. t.Fatalf("generateInboundTag: %v", err)
  451. }
  452. if got != "n1-in-443-tcp" {
  453. t.Fatalf("expected n1-in-443-tcp, got %q", got)
  454. }
  455. }
  456. // updating an inbound must not see itself as a conflict, that's what
  457. // ignoreId is for.
  458. func TestCheckPortConflict_IgnoreSelfOnUpdate(t *testing.T) {
  459. setupConflictDB(t)
  460. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  461. var existing model.Inbound
  462. if err := database.GetDB().Where("tag = ?", "vless-443").First(&existing).Error; err != nil {
  463. t.Fatalf("read seeded row: %v", err)
  464. }
  465. svc := &InboundService{}
  466. if exist, err := svc.checkPortConflict(&existing, existing.Id); err != nil || exist != nil {
  467. t.Fatalf("self-update must not be flagged as conflict; exist=%v err=%v", exist, err)
  468. }
  469. }
  470. // streamSettings.network=quic rides on UDP at L4, so a QUIC inbound must
  471. // conflict with a UDP-only neighbour (hysteria) on the same port but not
  472. // with a TCP-only one. covers the gap left by the original kcp-only check.
  473. func TestCheckPortConflict_QUICTreatedAsUDP(t *testing.T) {
  474. quic := &model.Inbound{
  475. Tag: "vless-quic-443",
  476. Listen: "0.0.0.0",
  477. Port: 443,
  478. Protocol: model.VLESS,
  479. StreamSettings: `{"network":"quic"}`,
  480. }
  481. t.Run("conflicts with hysteria/udp", func(t *testing.T) {
  482. setupConflictDB(t)
  483. seedInboundConflict(t, "hyst-443", "0.0.0.0", 443, model.Hysteria, ``, ``)
  484. svc := &InboundService{}
  485. if exist, err := svc.checkPortConflict(quic, 0); err != nil || exist == nil {
  486. t.Fatalf("quic on same port as hysteria must conflict; exist=%v err=%v", exist, err)
  487. }
  488. })
  489. t.Run("coexists with vless/tcp", func(t *testing.T) {
  490. setupConflictDB(t)
  491. seedInboundConflict(t, "vless-tcp-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  492. svc := &InboundService{}
  493. if exist, err := svc.checkPortConflict(quic, 0); err != nil || exist != nil {
  494. t.Fatalf("quic and tcp on same port must coexist; exist=%v err=%v", exist, err)
  495. }
  496. })
  497. }
  498. // tunnel (dokodemo-door) carries its L4 transport list in
  499. // settings.allowedNetwork, not settings.network. verify the predicate
  500. // picks the right field for each protocol.
  501. func TestCheckPortConflict_TunnelAllowedNetwork(t *testing.T) {
  502. setupConflictDB(t)
  503. seedInboundConflict(t, "tunnel-udp-443", "0.0.0.0", 443, model.Tunnel, ``, `{"allowedNetwork":"udp"}`)
  504. svc := &InboundService{}
  505. // tcp inbound on same port should coexist with udp-only tunnel.
  506. tcpNeighbour := &model.Inbound{
  507. Tag: "vless-443",
  508. Listen: "0.0.0.0",
  509. Port: 443,
  510. Protocol: model.VLESS,
  511. StreamSettings: `{"network":"tcp"}`,
  512. }
  513. if exist, err := svc.checkPortConflict(tcpNeighbour, 0); err != nil || exist != nil {
  514. t.Fatalf("tunnel/udp and vless/tcp on same port must coexist; exist=%v err=%v", exist, err)
  515. }
  516. // udp neighbour (hysteria) on same port must conflict.
  517. udpNeighbour := &model.Inbound{
  518. Tag: "hyst-443",
  519. Listen: "0.0.0.0",
  520. Port: 443,
  521. Protocol: model.Hysteria,
  522. }
  523. if exist, err := svc.checkPortConflict(udpNeighbour, 0); err != nil || exist == nil {
  524. t.Fatalf("tunnel/udp and hysteria on same port must conflict; exist=%v err=%v", exist, err)
  525. }
  526. }
  527. // the rich conflict detail surfaced to the user must name the offending
  528. // inbound (by remark when available) and the shared L4 transport(s).
  529. func TestCheckPortConflict_DetailMessage(t *testing.T) {
  530. setupConflictDB(t)
  531. seeded := &model.Inbound{
  532. Tag: "vless-443",
  533. Remark: "my-vless",
  534. Enable: true,
  535. Listen: "0.0.0.0",
  536. Port: 443,
  537. Protocol: model.VLESS,
  538. StreamSettings: `{"network":"tcp"}`,
  539. Settings: `{}`,
  540. }
  541. if err := database.GetDB().Create(seeded).Error; err != nil {
  542. t.Fatalf("seed inbound: %v", err)
  543. }
  544. svc := &InboundService{}
  545. candidate := &model.Inbound{
  546. Tag: "trojan-443",
  547. Listen: "0.0.0.0",
  548. Port: 443,
  549. Protocol: model.Trojan,
  550. StreamSettings: `{"network":"ws"}`,
  551. }
  552. got, err := svc.checkPortConflict(candidate, 0)
  553. if err != nil || got == nil {
  554. t.Fatalf("expected conflict, got=%v err=%v", got, err)
  555. }
  556. msg := got.String()
  557. if !strings.Contains(msg, "my-vless") {
  558. t.Fatalf("message should mention the conflicting inbound's remark; got %q", msg)
  559. }
  560. if !strings.Contains(msg, "tcp") {
  561. t.Fatalf("message should mention the shared L4 transport; got %q", msg)
  562. }
  563. if !strings.Contains(msg, "443") {
  564. t.Fatalf("message should mention the port; got %q", msg)
  565. }
  566. }
  567. // isAutoGeneratedTag must recognise the tags generateInboundTag emits (so an
  568. // edit that changes port/transport re-derives them) while leaving user-typed
  569. // or cross-panel tags untouched.
  570. func TestIsAutoGeneratedTag(t *testing.T) {
  571. tcp := transportTCP
  572. cases := []struct {
  573. name string
  574. tag string
  575. port int
  576. nodeID *int
  577. bits transportBits
  578. want bool
  579. }{
  580. {"canonical", "in-443-tcp", 443, nil, tcp, true},
  581. {"canonical udp", "in-443-udp", 443, nil, transportUDP, true},
  582. {"dedup suffix", "in-443-tcp-2", 443, nil, tcp, true},
  583. {"node prefixed", "n1-in-443-tcp", 443, new(1), tcp, true},
  584. {"legacy listen-scoped is now custom", "in-127.0.0.1:443-tcp", 443, nil, tcp, false},
  585. {"custom tag", "my-cool-tag", 443, nil, tcp, false},
  586. {"stale port", "in-443-tcp", 8443, nil, tcp, false},
  587. {"stale transport", "in-443-tcp", 443, nil, transportUDP, false},
  588. {"non-numeric suffix", "in-443-tcp-x", 443, nil, tcp, false},
  589. {"empty suffix", "in-443-tcp-", 443, nil, tcp, false},
  590. }
  591. for _, c := range cases {
  592. t.Run(c.name, func(t *testing.T) {
  593. if got := isAutoGeneratedTag(c.tag, c.port, c.nodeID, c.bits); got != c.want {
  594. t.Fatalf("isAutoGeneratedTag(%q) = %v, want %v", c.tag, got, c.want)
  595. }
  596. })
  597. }
  598. }
  599. // the internal Xray API inbound (tag "api", loopback TCP) isn't a DB row, so
  600. // checkPortConflict must still reject a local user inbound that reuses its
  601. // reserved port — otherwise Xray binds the port twice (#5304).
  602. func TestCheckPortConflict_ReservedAPIPortBlockedLocal(t *testing.T) {
  603. setupConflictDB(t)
  604. svc := &InboundService{}
  605. candidate := &model.Inbound{
  606. Tag: "user-62789",
  607. Listen: "0.0.0.0",
  608. Port: defaultXrayAPIPort,
  609. Protocol: model.VLESS,
  610. StreamSettings: `{"network":"tcp"}`,
  611. }
  612. got, err := svc.checkPortConflict(candidate, 0)
  613. if err != nil {
  614. t.Fatalf("checkPortConflict: %v", err)
  615. }
  616. if got == nil {
  617. t.Fatalf("local inbound on the reserved API port %d must conflict", defaultXrayAPIPort)
  618. }
  619. if msg := got.String(); !strings.Contains(msg, "api") {
  620. t.Fatalf("conflict message should name the api inbound; got %q", msg)
  621. }
  622. }
  623. // nodes run their own Xray with their own API port, so a node inbound on the
  624. // central panel's reserved API port must be allowed.
  625. func TestCheckPortConflict_ReservedAPIPortAllowedOnNode(t *testing.T) {
  626. setupConflictDB(t)
  627. svc := &InboundService{}
  628. candidate := &model.Inbound{
  629. Tag: "node-62789",
  630. Listen: "0.0.0.0",
  631. Port: defaultXrayAPIPort,
  632. Protocol: model.VLESS,
  633. StreamSettings: `{"network":"tcp"}`,
  634. NodeID: new(1),
  635. }
  636. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  637. t.Fatalf("node inbound on the reserved API port must be allowed; got=%v err=%v", got, err)
  638. }
  639. }
  640. // the API inbound is TCP-only, so a UDP-only inbound (e.g. hysteria) may share
  641. // its port — same tcp/udp coexistence the rest of the checks allow.
  642. func TestCheckPortConflict_ReservedAPIPortUDPCoexists(t *testing.T) {
  643. setupConflictDB(t)
  644. svc := &InboundService{}
  645. candidate := &model.Inbound{
  646. Tag: "hyst-62789",
  647. Listen: "0.0.0.0",
  648. Port: defaultXrayAPIPort,
  649. Protocol: model.Hysteria,
  650. }
  651. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  652. t.Fatalf("udp-only inbound must coexist with the tcp API inbound; got=%v err=%v", got, err)
  653. }
  654. }
  655. // amneziawgRoutedSettings builds a minimal but complete AmneziaWG settings
  656. // blob with one qualifying, enabled peer -- the shape that makes
  657. // injectAmneziawgnetSocks (and therefore checkAmneziawgnetSocksConflict)
  658. // create a relay inbound at all. The routeThroughXray field is kept in the
  659. // JSON (a stale value from a pre-cutover install) specifically to prove
  660. // it's now ignored -- see the "RouteThroughXrayOff" test below.
  661. 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"]}]}`
  662. // A local TCP inbound on EgressBasePort must conflict with the AmneziaWG
  663. // egress SOCKS server (which is not in the database).
  664. func TestCheckPortConflict_EgressPortBlockedLocal(t *testing.T) {
  665. setupConflictDB(t)
  666. svc := &InboundService{}
  667. candidate := &model.Inbound{
  668. Tag: "vless-bridge",
  669. Listen: "0.0.0.0",
  670. Port: int(amneziawgnet.EgressBasePort),
  671. Protocol: model.VLESS,
  672. }
  673. got, err := svc.checkPortConflict(candidate, 0)
  674. if err != nil {
  675. t.Fatalf("checkPortConflict: %v", err)
  676. }
  677. if got == nil {
  678. t.Fatalf("a local inbound on the egress port %d must conflict", amneziawgnet.EgressBasePort)
  679. }
  680. }
  681. func TestCheckPortConflict_AmneziawgnetSocksRelayBlockedLocal(t *testing.T) {
  682. setupConflictDB(t)
  683. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  684. var awgInbound model.Inbound
  685. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  686. t.Fatalf("read seeded row: %v", err)
  687. }
  688. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  689. svc := &InboundService{}
  690. candidate := &model.Inbound{
  691. Tag: "vless-bridge",
  692. Listen: "0.0.0.0",
  693. Port: relayPort,
  694. Protocol: model.VLESS,
  695. }
  696. got, err := svc.checkPortConflict(candidate, 0)
  697. if err != nil {
  698. t.Fatalf("checkPortConflict: %v", err)
  699. }
  700. if got == nil {
  701. t.Fatalf("a local inbound on the AmneziaWG relay port %d must conflict", relayPort)
  702. }
  703. if msg := got.String(); !strings.Contains(msg, "awg-1") {
  704. t.Fatalf("conflict message should name the owning AmneziaWG inbound; got %q", msg)
  705. }
  706. }
  707. // Nodes run their own Xray, so a node inbound landing on the central panel's
  708. // AmneziaWG relay port must be allowed -- the relay inbound only ever binds
  709. // 127.0.0.1 on the local panel's own Xray.
  710. func TestCheckPortConflict_AmneziawgnetSocksRelayAllowedOnNode(t *testing.T) {
  711. setupConflictDB(t)
  712. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  713. var awgInbound model.Inbound
  714. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  715. t.Fatalf("read seeded row: %v", err)
  716. }
  717. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  718. svc := &InboundService{}
  719. candidate := &model.Inbound{
  720. Tag: "node-bridge",
  721. Listen: "0.0.0.0",
  722. Port: relayPort,
  723. Protocol: model.VLESS,
  724. NodeID: new(1),
  725. }
  726. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  727. t.Fatalf("a node inbound on the local AmneziaWG relay port must be allowed; got=%v err=%v", got, err)
  728. }
  729. }
  730. // Unlike the retired kernel-module bridge, the embedded relay has no
  731. // RouteThroughXray-style opt-in -- every qualifying AmneziaWG inbound
  732. // reserves its relay port regardless of that (now-vestigial) field's value,
  733. // including a stale routeThroughXray:true left over from a pre-cutover
  734. // install (amneziawgRoutedSettings).
  735. func TestCheckPortConflict_AmneziawgnetSocksRelayReservedRegardlessOfLegacyRouteThroughXrayField(t *testing.T) {
  736. setupConflictDB(t)
  737. 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"]}]}`)
  738. var awgInbound model.Inbound
  739. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  740. t.Fatalf("read seeded row: %v", err)
  741. }
  742. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  743. svc := &InboundService{}
  744. candidate := &model.Inbound{
  745. Tag: "vless-bridge",
  746. Listen: "0.0.0.0",
  747. Port: relayPort,
  748. Protocol: model.VLESS,
  749. }
  750. got, err := svc.checkPortConflict(candidate, 0)
  751. if err != nil {
  752. t.Fatalf("checkPortConflict: %v", err)
  753. }
  754. if got == nil {
  755. t.Fatalf("an enabled, qualifying AmneziaWG inbound must reserve its relay port even with RouteThroughXray left at its default")
  756. }
  757. }
  758. // A local AmneziaWG inbound owns its relay port from the row, not from its first
  759. // peer: the relay appears when a client is added, and that path runs no port check.
  760. func TestCheckPortConflict_AmneziawgnetSocksRelayReservedBeforeTheFirstPeer(t *testing.T) {
  761. setupConflictDB(t)
  762. // The shape normalizeAmneziaWGSettings writes for a fresh AmneziaWG inbound.
  763. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``,
  764. `{"server":{"privateKey":"priv","publicKey":"pub","subnetIp":"10.8.1.0","subnetCidr":24},"clients":[]}`)
  765. var awgInbound model.Inbound
  766. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  767. t.Fatalf("read seeded row: %v", err)
  768. }
  769. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  770. svc := &InboundService{}
  771. candidate := &model.Inbound{
  772. Tag: "vless-bridge",
  773. Listen: "0.0.0.0",
  774. Port: relayPort,
  775. Protocol: model.VLESS,
  776. }
  777. got, err := svc.checkPortConflict(candidate, 0)
  778. if err != nil {
  779. t.Fatalf("checkPortConflict: %v", err)
  780. }
  781. if got == nil {
  782. t.Fatalf("an AmneziaWG inbound with no peer yet still owns relay port %d; the save must be refused", relayPort)
  783. }
  784. if !strings.Contains(got.String(), "awg-1") {
  785. t.Fatalf("the conflict must name the inbound owning the port, got %q", got.String())
  786. }
  787. }
  788. // An unrelated port never conflicts with the relay inbound.
  789. func TestCheckPortConflict_AmneziawgnetSocksRelayDifferentPortAllowed(t *testing.T) {
  790. setupConflictDB(t)
  791. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  792. svc := &InboundService{}
  793. candidate := &model.Inbound{
  794. Tag: "vless-elsewhere",
  795. Listen: "0.0.0.0",
  796. Port: 9999,
  797. Protocol: model.VLESS,
  798. }
  799. if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
  800. t.Fatalf("an unrelated port must not conflict with the AmneziaWG relay inbound; got=%v err=%v", got, err)
  801. }
  802. }
  803. // The reverse direction: saving an AmneziaWG inbound whose own derived relay
  804. // port happens to equal another inbound's real port must also be rejected,
  805. // not just the already-covered "someone else picks my relay port" case.
  806. func TestCheckPortConflict_AmneziawgnetSocksRelayReverseDirectionBlockedOnUpdate(t *testing.T) {
  807. setupConflictDB(t)
  808. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
  809. var awgInbound model.Inbound
  810. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  811. t.Fatalf("read seeded row: %v", err)
  812. }
  813. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  814. seedInboundConflict(t, "vless-1", "0.0.0.0", relayPort, model.VLESS, ``, `{}`)
  815. svc := &InboundService{}
  816. candidate := &model.Inbound{
  817. Id: awgInbound.Id,
  818. Tag: "awg-1",
  819. Listen: "0.0.0.0",
  820. Port: 51820,
  821. Protocol: model.AmneziaWG,
  822. Settings: amneziawgRoutedSettings,
  823. }
  824. got, err := svc.checkPortConflict(candidate, awgInbound.Id)
  825. if err != nil {
  826. t.Fatalf("checkPortConflict: %v", err)
  827. }
  828. if got == nil {
  829. t.Fatalf("awg-1's own derived relay port %d collides with vless-1's real port; must be rejected", relayPort)
  830. }
  831. }
  832. // xray binds "::" dual-stack unless sockopt.v6only is set, so only then may an
  833. // IPv4 address share its port; the flag is read from the saved streamSettings.
  834. func TestCheckPortConflict_V6OnlyWildcardLeavesIPv4AddressFree(t *testing.T) {
  835. for _, tc := range []struct {
  836. name string
  837. stream string
  838. want bool
  839. }{
  840. {"dual-stack", `{"network":"tcp"}`, true},
  841. {"v6only", `{"network":"tcp","sockopt":{"v6only":true}}`, false},
  842. } {
  843. t.Run(tc.name, func(t *testing.T) {
  844. setupConflictDB(t)
  845. seedInboundConflict(t, "vless-v6", "::", 443, model.VLESS, tc.stream, `{}`)
  846. v4 := &model.Inbound{Tag: "vless-v4", Listen: "10.5.0.200", Port: 443, Protocol: model.VLESS, StreamSettings: `{"network":"tcp"}`}
  847. exist, err := (&InboundService{}).checkPortConflict(v4, 0)
  848. if err != nil {
  849. t.Fatalf("checkPortConflict: %v", err)
  850. }
  851. if got := exist != nil; got != tc.want {
  852. t.Fatalf("conflict = %v, want %v", got, tc.want)
  853. }
  854. })
  855. }
  856. }