port_conflict_test.go 34 KB

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