1
0

port_conflict_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package service
  2. import (
  3. "path/filepath"
  4. "sync"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v2/database"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. xuilogger "github.com/mhsanaei/3x-ui/v2/logger"
  9. "github.com/op/go-logging"
  10. )
  11. // the panel logger is a process-wide singleton. init it once per test
  12. // binary so a stray warning from gorm doesn't blow up on a nil logger.
  13. var portConflictLoggerOnce sync.Once
  14. // setupConflictDB wires a temp sqlite db so checkPortConflict can read
  15. // real candidates. closes the db before t.TempDir cleans up so windows
  16. // doesn't refuse to remove the file.
  17. func setupConflictDB(t *testing.T) {
  18. t.Helper()
  19. portConflictLoggerOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) })
  20. dbDir := t.TempDir()
  21. t.Setenv("XUI_DB_FOLDER", dbDir)
  22. if err := database.InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil {
  23. t.Fatalf("InitDB: %v", err)
  24. }
  25. t.Cleanup(func() {
  26. if err := database.CloseDB(); err != nil {
  27. t.Logf("CloseDB warning: %v", err)
  28. }
  29. })
  30. }
  31. func seedInboundConflict(t *testing.T, tag, listen string, port int, protocol model.Protocol, streamSettings, settings string) {
  32. t.Helper()
  33. 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. }
  42. if err := database.GetDB().Create(in).Error; err != nil {
  43. t.Fatalf("seed inbound %s: %v", tag, err)
  44. }
  45. }
  46. func TestInboundTransports(t *testing.T) {
  47. cases := []struct {
  48. name string
  49. protocol model.Protocol
  50. streamSettings string
  51. settings string
  52. want transportBits
  53. }{
  54. {"vless default tcp", model.VLESS, `{"network":"tcp"}`, ``, transportTCP},
  55. {"vless ws (still tcp)", model.VLESS, `{"network":"ws"}`, ``, transportTCP},
  56. {"vless kcp is udp", model.VLESS, `{"network":"kcp"}`, ``, transportUDP},
  57. {"vless empty stream defaults to tcp", model.VLESS, ``, ``, transportTCP},
  58. {"vless garbage stream stays tcp", model.VLESS, `not json`, ``, transportTCP},
  59. {"vmess default tcp", model.VMESS, `{"network":"tcp"}`, ``, transportTCP},
  60. {"trojan grpc is tcp", model.Trojan, `{"network":"grpc"}`, ``, transportTCP},
  61. {"hysteria forced udp", model.Hysteria, `{"network":"tcp"}`, ``, transportUDP},
  62. {"hysteria2 forced udp", model.Hysteria2, ``, ``, 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(c.a, 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. // hysteria2 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.Hysteria2,
  112. }
  113. exist, err := svc.checkPortConflict(hyst2, 0)
  114. if err != nil {
  115. t.Fatalf("checkPortConflict: %v", err)
  116. }
  117. if exist {
  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 {
  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.Hysteria2, ``, ``)
  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 {
  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 {
  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.Hysteria2,
  182. }
  183. if exist, err := svc.checkPortConflict(udpClash, 0); err != nil || !exist {
  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 {
  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 {
  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 {
  230. t.Fatalf("any-addr on same port+transport must conflict with specific; exist=%v err=%v", exist, err)
  231. }
  232. }
  233. // when the base "inbound-<port>" tag is already taken on a coexisting
  234. // transport, generateInboundTag must disambiguate with a transport
  235. // suffix so the unique-tag DB constraint stays satisfied.
  236. func TestGenerateInboundTag_DisambiguatesByTransportOnSamePort(t *testing.T) {
  237. setupConflictDB(t)
  238. // existing tcp inbound owns "inbound-443".
  239. seedInboundConflict(t, "inbound-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.Hysteria2,
  245. }
  246. got, err := svc.generateInboundTag(udp, 0)
  247. if err != nil {
  248. t.Fatalf("generateInboundTag: %v", err)
  249. }
  250. if got != "inbound-443-udp" {
  251. t.Fatalf("expected disambiguated tag inbound-443-udp, got %q", got)
  252. }
  253. }
  254. // when the port is free, the historical "inbound-<port>" shape is kept
  255. // so existing routing rules don't change shape on upgrade.
  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 != "inbound-8443" {
  269. t.Fatalf("expected inbound-8443, got %q", got)
  270. }
  271. }
  272. // updating an inbound on its own port must not flag its own tag as
  273. // taken, that's what ignoreId is for.
  274. func TestGenerateInboundTag_IgnoresSelfOnUpdate(t *testing.T) {
  275. setupConflictDB(t)
  276. seedInboundConflict(t, "inbound-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  277. var existing model.Inbound
  278. if err := database.GetDB().Where("tag = ?", "inbound-443").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 != "inbound-443" {
  287. t.Fatalf("self-update must keep base tag, got %q", got)
  288. }
  289. }
  290. // specific listen address gets the listen-prefixed shape and same
  291. // disambiguation rules.
  292. func TestGenerateInboundTag_SpecificListenSameDisambiguation(t *testing.T) {
  293. setupConflictDB(t)
  294. seedInboundConflict(t, "inbound-1.2.3.4:443", "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.Hysteria2,
  300. }
  301. got, err := svc.generateInboundTag(udp, 0)
  302. if err != nil {
  303. t.Fatalf("generateInboundTag: %v", err)
  304. }
  305. if got != "inbound-1.2.3.4:443-udp" {
  306. t.Fatalf("expected inbound-1.2.3.4:443-udp, got %q", got)
  307. }
  308. }
  309. // updating an inbound must not see itself as a conflict, that's what
  310. // ignoreId is for.
  311. func TestCheckPortConflict_IgnoreSelfOnUpdate(t *testing.T) {
  312. setupConflictDB(t)
  313. seedInboundConflict(t, "vless-443", "0.0.0.0", 443, model.VLESS, `{"network":"tcp"}`, `{}`)
  314. var existing model.Inbound
  315. if err := database.GetDB().Where("tag = ?", "vless-443").First(&existing).Error; err != nil {
  316. t.Fatalf("read seeded row: %v", err)
  317. }
  318. svc := &InboundService{}
  319. if exist, err := svc.checkPortConflict(&existing, existing.Id); err != nil || exist {
  320. t.Fatalf("self-update must not be flagged as conflict; exist=%v err=%v", exist, err)
  321. }
  322. }