port_conflict.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/database"
  7. "github.com/mhsanaei/3x-ui/v3/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/util/common"
  9. )
  10. // transportBits is a bitmask of L4 transports an inbound listens on.
  11. // 0.0.0.0:443/tcp and 0.0.0.0:443/udp are independent sockets in linux,
  12. // so the conflict check needs more than just the port number.
  13. type transportBits uint8
  14. const (
  15. transportTCP transportBits = 1 << iota
  16. transportUDP
  17. )
  18. // inboundTransports returns the L4 transports the given inbound listens on.
  19. // always returns at least one bit (falls back to tcp on parse errors), so
  20. // no parse failure can silently let a real socket collision through.
  21. //
  22. // the rules:
  23. // - hysteria, wireguard: udp regardless of streamSettings
  24. // - streamSettings.network=kcp or quic: udp (both ride on udp at L4)
  25. // - shadowsocks: settings.network ("tcp" / "udp" / "tcp,udp"), overrides
  26. // the streamSettings-derived bit when present
  27. // - tunnel (xray dokodemo-door): same shape via settings.allowedNetwork
  28. // (3x-ui's wrapper renames the field)
  29. // - mixed (socks/http combo): tcp + udp when settings.udp is true
  30. // - everything else: tcp
  31. func inboundTransports(protocol model.Protocol, streamSettings, settings string) transportBits {
  32. // protocols that ignore streamSettings entirely.
  33. switch protocol {
  34. case model.Hysteria, model.WireGuard:
  35. return transportUDP
  36. }
  37. var bits transportBits
  38. // peek at streamSettings.network to spot udp-based transports.
  39. // parse errors are non-fatal: missing or weird streamSettings just
  40. // keeps the default tcp bit below.
  41. network := ""
  42. if streamSettings != "" {
  43. var ss map[string]any
  44. if json.Unmarshal([]byte(streamSettings), &ss) == nil {
  45. if n, _ := ss["network"].(string); n != "" {
  46. network = n
  47. }
  48. }
  49. }
  50. switch network {
  51. case "kcp", "quic":
  52. bits |= transportUDP
  53. default:
  54. bits |= transportTCP
  55. }
  56. // a few protocols carry their L4 choice in settings instead of (or in
  57. // addition to) streamSettings: SS / Tunnel via a CSV field that wins
  58. // outright, Mixed via an additive udp boolean.
  59. if settings != "" {
  60. var st map[string]any
  61. if json.Unmarshal([]byte(settings), &st) == nil {
  62. switch protocol {
  63. case model.Shadowsocks, model.Tunnel:
  64. // shadowsocks exposes settings.network, tunnel exposes
  65. // settings.allowedNetwork (3x-ui's wrapper around xray's
  66. // dokodemo-door). both carry "tcp" / "udp" / "tcp,udp"
  67. // and, when present, win outright over the streamSettings-
  68. // derived default; absent/empty keeps the inferred bit (tcp).
  69. key := "network"
  70. if protocol == model.Tunnel {
  71. key = "allowedNetwork"
  72. }
  73. if n, ok := st[key].(string); ok && n != "" {
  74. bits = 0
  75. for part := range strings.SplitSeq(n, ",") {
  76. switch strings.TrimSpace(part) {
  77. case "tcp":
  78. bits |= transportTCP
  79. case "udp":
  80. bits |= transportUDP
  81. }
  82. }
  83. }
  84. case model.Mixed:
  85. // socks/http "mixed" inbound: settings.udp=true means it
  86. // also relays udp on the same port (socks5 udp associate).
  87. if udpOn, _ := st["udp"].(bool); udpOn {
  88. bits |= transportUDP
  89. }
  90. }
  91. }
  92. }
  93. // safety net: never return zero, even if every parse failed.
  94. if bits == 0 {
  95. bits = transportTCP
  96. }
  97. return bits
  98. }
  99. // listenOverlaps reports whether two listen addresses can collide on the
  100. // same port. preserves the rule from the original checkPortExist:
  101. // any-address (empty / 0.0.0.0 / :: / ::0) overlaps with everything,
  102. // otherwise only identical specific addresses overlap.
  103. func listenOverlaps(a, b string) bool {
  104. if isAnyListen(a) || isAnyListen(b) {
  105. return true
  106. }
  107. return a == b
  108. }
  109. func isAnyListen(s string) bool {
  110. return s == "" || s == "0.0.0.0" || s == "::" || s == "::0"
  111. }
  112. // portConflictDetail describes the existing inbound that an add/update
  113. // would collide with. it carries enough context for the API layer to
  114. // render a user-actionable error ("port 443 (tcp) already used by
  115. // inbound 'my-vless' (#7) on *") instead of the historical opaque
  116. // "Port exists". Transports holds only the bits the two inbounds
  117. // actually share, not the existing inbound's full transport mask.
  118. type portConflictDetail struct {
  119. InboundID int
  120. Remark string
  121. Tag string
  122. Listen string
  123. Port int
  124. Transports transportBits
  125. }
  126. // String renders the detail as a single-line, user-facing summary.
  127. func (d *portConflictDetail) String() string {
  128. name := d.Remark
  129. if name == "" {
  130. name = d.Tag
  131. }
  132. if name == "" {
  133. name = fmt.Sprintf("#%d", d.InboundID)
  134. } else {
  135. name = fmt.Sprintf("'%s' (#%d)", name, d.InboundID)
  136. }
  137. listen := d.Listen
  138. if isAnyListen(listen) {
  139. listen = "*"
  140. }
  141. return fmt.Sprintf("port %d (%s) already used by inbound %s on %s",
  142. d.Port, transportTagSuffix(d.Transports), name, listen)
  143. }
  144. // checkPortConflict reports the existing inbound (if any) that adding
  145. // or updating an inbound on (listen, port) would clash with. nil result
  146. // means no conflict.
  147. //
  148. // the check understands that tcp/443 and udp/443 are independent
  149. // sockets in linux and may coexist on the same address (see
  150. // inboundTransports for the per-protocol L4 mapping).
  151. //
  152. // node scope: inbounds with different NodeID run on different physical
  153. // machines (local panel xray vs a remote node, or two remote nodes),
  154. // so their sockets can't collide. only candidates with the same NodeID
  155. // participate in the listen/transport overlap check.
  156. //
  157. // listen overlap: a specific listen address conflicts with any-address
  158. // on the same port (both directions), otherwise only identical specific
  159. // addresses overlap.
  160. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  161. db := database.GetDB()
  162. var candidates []*model.Inbound
  163. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  164. if ignoreId > 0 {
  165. q = q.Where("id != ?", ignoreId)
  166. }
  167. if err := q.Find(&candidates).Error; err != nil {
  168. return nil, err
  169. }
  170. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  171. for _, c := range candidates {
  172. if !sameNode(c.NodeID, inbound.NodeID) {
  173. continue
  174. }
  175. if !listenOverlaps(c.Listen, inbound.Listen) {
  176. continue
  177. }
  178. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  179. shared := existingBits & newBits
  180. if shared == 0 {
  181. continue
  182. }
  183. return &portConflictDetail{
  184. InboundID: c.Id,
  185. Remark: c.Remark,
  186. Tag: c.Tag,
  187. Listen: c.Listen,
  188. Port: c.Port,
  189. Transports: shared,
  190. }, nil
  191. }
  192. return nil, nil
  193. }
  194. // sameNode reports whether two NodeID pointers refer to the same xray
  195. // process. nil/nil means both inbounds run on the local panel; non-nil
  196. // with equal value means they share the same remote node. any mix
  197. // (local vs remote, remote-A vs remote-B) is "different node" and
  198. // can't produce a real socket collision.
  199. func sameNode(a, b *int) bool {
  200. if a == nil && b == nil {
  201. return true
  202. }
  203. if a == nil || b == nil {
  204. return false
  205. }
  206. return *a == *b
  207. }
  208. // baseInboundTag is the "in-<port>" / "in-<listen>:<port>" core used
  209. // by composeInboundTag and as a probe shape in setRemoteTrafficLocked
  210. // for node-side xray imports that pre-date the canonical naming.
  211. func baseInboundTag(listen string, port int) string {
  212. if isAnyListen(listen) {
  213. return fmt.Sprintf("in-%v", port)
  214. }
  215. return fmt.Sprintf("in-%v:%v", listen, port)
  216. }
  217. func transportTagSuffix(b transportBits) string {
  218. switch b {
  219. case transportTCP:
  220. return "tcp"
  221. case transportUDP:
  222. return "udp"
  223. case transportTCP | transportUDP:
  224. return "tcpudp"
  225. }
  226. return "any"
  227. }
  228. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  229. // can live on the central panel and on a node without bumping the global
  230. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  231. func nodeTagPrefix(nodeID *int) string {
  232. if nodeID == nil {
  233. return ""
  234. }
  235. return fmt.Sprintf("n%d-", *nodeID)
  236. }
  237. // protocolShortName collapses the full protocol identifier into a 2–4
  238. // char tag-friendly token (shadowsocks → ss, wireguard → wg, …). Falls
  239. // back to the raw identifier for anything not in the table so future
  240. // protocols don't need a code change just to get a tag.
  241. func protocolShortName(p model.Protocol) string {
  242. switch p {
  243. case model.VMESS:
  244. return "vm"
  245. case model.VLESS:
  246. return "vl"
  247. case model.Trojan:
  248. return "tr"
  249. case model.Shadowsocks:
  250. return "ss"
  251. case model.Mixed:
  252. return "mx"
  253. case model.WireGuard:
  254. return "wg"
  255. case model.Hysteria:
  256. return "hy"
  257. case model.Tunnel:
  258. return "tn"
  259. case model.HTTP:
  260. return "http"
  261. }
  262. if p == "" {
  263. return "any"
  264. }
  265. return string(p)
  266. }
  267. // composeInboundTag returns the canonical
  268. // "[n<id>-]inbound-[<listen>:]<port>-<protocol>-<network>" shape used
  269. // for every newly created inbound. The protocol + network segments
  270. // disambiguate tcp/443 and udp/443 sharing a listener; the node prefix
  271. // lets the same port live on local + node.
  272. func composeInboundTag(listen string, port int, protocol model.Protocol, nodeID *int, bits transportBits) string {
  273. return nodeTagPrefix(nodeID) + baseInboundTag(listen, port) + "-" + protocolShortName(protocol) + "-" + transportTagSuffix(bits)
  274. }
  275. // generateInboundTag returns a free tag in the canonical shape. ignoreId
  276. // is the inbound's own id on update so it doesn't see itself as taken;
  277. // pass 0 on add. Numeric suffix fallback is defensive — the port check
  278. // should have already blocked an exact-collision insert.
  279. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  280. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  281. candidate := composeInboundTag(inbound.Listen, inbound.Port, inbound.Protocol, inbound.NodeID, bits)
  282. exists, err := s.tagExists(candidate, ignoreId)
  283. if err != nil {
  284. return "", err
  285. }
  286. if !exists {
  287. return candidate, nil
  288. }
  289. for i := 2; i < 100; i++ {
  290. c := fmt.Sprintf("%s-%d", candidate, i)
  291. exists, err = s.tagExists(c, ignoreId)
  292. if err != nil {
  293. return "", err
  294. }
  295. if !exists {
  296. return c, nil
  297. }
  298. }
  299. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  300. }
  301. // resolveInboundTag chooses a tag for an Add or Update. when the caller
  302. // supplied a non-empty Tag (e.g. the central panel pushed its picked
  303. // tag to a node during a multi-node sync) and that tag is free in the
  304. // local DB, it's used verbatim so the two panels stay in agreement —
  305. // otherwise the node would regenerate (often back to bare
  306. // "inbound-<port>") and the eventual traffic sync-back would try to
  307. // INSERT a row whose tag already exists, hitting the UNIQUE constraint
  308. // on inbounds.tag and rolling the node-side row right back out.
  309. // when Tag is empty (the common UI path) or collides, fall back to the
  310. // transport-aware generateInboundTag.
  311. //
  312. // ignoreId mirrors generateInboundTag: pass 0 on add, the inbound's
  313. // own id on update so a row doesn't see its own current tag as taken.
  314. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  315. if inbound.Tag != "" {
  316. taken, err := s.tagExists(inbound.Tag, ignoreId)
  317. if err != nil {
  318. return "", err
  319. }
  320. if !taken {
  321. return inbound.Tag, nil
  322. }
  323. }
  324. return s.generateInboundTag(inbound, ignoreId)
  325. }
  326. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  327. db := database.GetDB()
  328. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  329. if ignoreId > 0 {
  330. q = q.Where("id != ?", ignoreId)
  331. }
  332. var count int64
  333. if err := q.Count(&count).Error; err != nil {
  334. return false, err
  335. }
  336. return count > 0, nil
  337. }