port_conflict.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // unlike the old port-only check, this one understands that tcp/443 and
  149. // udp/443 are independent sockets in linux and may coexist on the same
  150. // address.
  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. // the listen-overlap rule (specific addr conflicts with any-addr on the
  158. // same port, both directions) is preserved from the previous check.
  159. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  160. db := database.GetDB()
  161. var candidates []*model.Inbound
  162. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  163. if ignoreId > 0 {
  164. q = q.Where("id != ?", ignoreId)
  165. }
  166. if err := q.Find(&candidates).Error; err != nil {
  167. return nil, err
  168. }
  169. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  170. for _, c := range candidates {
  171. if !sameNode(c.NodeID, inbound.NodeID) {
  172. continue
  173. }
  174. if !listenOverlaps(c.Listen, inbound.Listen) {
  175. continue
  176. }
  177. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  178. shared := existingBits & newBits
  179. if shared == 0 {
  180. continue
  181. }
  182. return &portConflictDetail{
  183. InboundID: c.Id,
  184. Remark: c.Remark,
  185. Tag: c.Tag,
  186. Listen: c.Listen,
  187. Port: c.Port,
  188. Transports: shared,
  189. }, nil
  190. }
  191. return nil, nil
  192. }
  193. // sameNode reports whether two NodeID pointers refer to the same xray
  194. // process. nil/nil means both inbounds run on the local panel; non-nil
  195. // with equal value means they share the same remote node. any mix
  196. // (local vs remote, remote-A vs remote-B) is "different node" and
  197. // can't produce a real socket collision.
  198. func sameNode(a, b *int) bool {
  199. if a == nil && b == nil {
  200. return true
  201. }
  202. if a == nil || b == nil {
  203. return false
  204. }
  205. return *a == *b
  206. }
  207. // baseInboundTag is the historical "inbound-<port>" / "inbound-<listen>:<port>"
  208. // shape. kept exactly so existing routing rules that reference these tags
  209. // keep working after the upgrade.
  210. func baseInboundTag(listen string, port int) string {
  211. if isAnyListen(listen) {
  212. return fmt.Sprintf("inbound-%v", port)
  213. }
  214. return fmt.Sprintf("inbound-%v:%v", listen, port)
  215. }
  216. // transportTagSuffix turns a transport mask into a short, stable string
  217. // for tag disambiguation. only used when the base "inbound-<port>" is
  218. // already taken on a coexisting transport (e.g. tcp inbound already lives
  219. // on 443 and we're now adding a udp one).
  220. func transportTagSuffix(b transportBits) string {
  221. switch b {
  222. case transportTCP:
  223. return "tcp"
  224. case transportUDP:
  225. return "udp"
  226. case transportTCP | transportUDP:
  227. return "mixed"
  228. }
  229. return "any"
  230. }
  231. // generateInboundTag picks a tag for the inbound that doesn't collide with
  232. // any existing row. for the common single-inbound-per-port case the tag
  233. // stays exactly as before ("inbound-443"), so user routing rules don't
  234. // silently change shape on upgrade. only when a same-port neighbour
  235. // already owns the base tag (now possible because tcp/443 and udp/443 can
  236. // coexist after the transport-aware port check) does this append a
  237. // transport suffix like "inbound-443-udp".
  238. //
  239. // ignoreId is the inbound's own id during update so it doesn't see itself
  240. // as a collision; pass 0 on add.
  241. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  242. base := baseInboundTag(inbound.Listen, inbound.Port)
  243. exists, err := s.tagExists(base, ignoreId)
  244. if err != nil {
  245. return "", err
  246. }
  247. if !exists {
  248. return base, nil
  249. }
  250. suffix := transportTagSuffix(inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings))
  251. candidate := base + "-" + suffix
  252. exists, err = s.tagExists(candidate, ignoreId)
  253. if err != nil {
  254. return "", err
  255. }
  256. if !exists {
  257. return candidate, nil
  258. }
  259. // the transport-aware port check should have already blocked this
  260. // path, but guard anyway so a unique-constraint failure doesn't reach
  261. // the user as an opaque sqlite error.
  262. for i := 2; i < 100; i++ {
  263. c := fmt.Sprintf("%s-%d", candidate, i)
  264. exists, err = s.tagExists(c, ignoreId)
  265. if err != nil {
  266. return "", err
  267. }
  268. if !exists {
  269. return c, nil
  270. }
  271. }
  272. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  273. }
  274. // resolveInboundTag chooses a tag for an Add or Update. when the caller
  275. // supplied a non-empty Tag (e.g. the central panel pushed its picked
  276. // tag to a node during a multi-node sync) and that tag is free in the
  277. // local DB, it's used verbatim so the two panels stay in agreement —
  278. // otherwise the node would regenerate (often back to bare
  279. // "inbound-<port>") and the eventual traffic sync-back would try to
  280. // INSERT a row whose tag already exists, hitting the UNIQUE constraint
  281. // on inbounds.tag and rolling the node-side row right back out.
  282. // when Tag is empty (the common UI path) or collides, fall back to the
  283. // transport-aware generateInboundTag.
  284. //
  285. // ignoreId mirrors generateInboundTag: pass 0 on add, the inbound's
  286. // own id on update so a row doesn't see its own current tag as taken.
  287. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  288. if inbound.Tag != "" {
  289. taken, err := s.tagExists(inbound.Tag, ignoreId)
  290. if err != nil {
  291. return "", err
  292. }
  293. if !taken {
  294. return inbound.Tag, nil
  295. }
  296. }
  297. return s.generateInboundTag(inbound, ignoreId)
  298. }
  299. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  300. db := database.GetDB()
  301. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  302. if ignoreId > 0 {
  303. q = q.Where("id != ?", ignoreId)
  304. }
  305. var count int64
  306. if err := q.Count(&count).Error; err != nil {
  307. return false, err
  308. }
  309. return count > 0, nil
  310. }