port_conflict_test.go 33 KB

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