port_conflict.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 historical "inbound-<port>" / "inbound-<listen>:<port>"
  209. // shape. kept exactly so existing routing rules that reference these tags
  210. // keep working after the upgrade.
  211. func baseInboundTag(listen string, port int) string {
  212. if isAnyListen(listen) {
  213. return fmt.Sprintf("inbound-%v", port)
  214. }
  215. return fmt.Sprintf("inbound-%v:%v", listen, port)
  216. }
  217. // transportTagSuffix turns a transport mask into a short, stable string.
  218. // used both for generateInboundTag's disambiguation ("inbound-443-udp"
  219. // when the base "inbound-443" is taken on a coexisting transport) and
  220. // for the L4 hint in portConflictDetail's user-facing error message.
  221. func transportTagSuffix(b transportBits) string {
  222. switch b {
  223. case transportTCP:
  224. return "tcp"
  225. case transportUDP:
  226. return "udp"
  227. case transportTCP | transportUDP:
  228. return "mixed"
  229. }
  230. return "any"
  231. }
  232. // generateInboundTag picks a tag for the inbound that doesn't collide with
  233. // any existing row. for the common single-inbound-per-port case the tag
  234. // stays exactly as before ("inbound-443"), so user routing rules don't
  235. // silently change shape on upgrade. only when a same-port neighbour
  236. // already owns the base tag (now possible because tcp/443 and udp/443 can
  237. // coexist after the transport-aware port check) does this append a
  238. // transport suffix like "inbound-443-udp".
  239. //
  240. // ignoreId is the inbound's own id during update so it doesn't see itself
  241. // as a collision; pass 0 on add.
  242. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  243. base := baseInboundTag(inbound.Listen, inbound.Port)
  244. exists, err := s.tagExists(base, ignoreId)
  245. if err != nil {
  246. return "", err
  247. }
  248. if !exists {
  249. return base, nil
  250. }
  251. suffix := transportTagSuffix(inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings))
  252. candidate := base + "-" + suffix
  253. exists, err = s.tagExists(candidate, ignoreId)
  254. if err != nil {
  255. return "", err
  256. }
  257. if !exists {
  258. return candidate, nil
  259. }
  260. // the transport-aware port check should have already blocked this
  261. // path, but guard anyway so a unique-constraint failure doesn't reach
  262. // the user as an opaque sqlite error.
  263. for i := 2; i < 100; i++ {
  264. c := fmt.Sprintf("%s-%d", candidate, i)
  265. exists, err = s.tagExists(c, ignoreId)
  266. if err != nil {
  267. return "", err
  268. }
  269. if !exists {
  270. return c, nil
  271. }
  272. }
  273. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  274. }
  275. // resolveInboundTag chooses a tag for an Add or Update. when the caller
  276. // supplied a non-empty Tag (e.g. the central panel pushed its picked
  277. // tag to a node during a multi-node sync) and that tag is free in the
  278. // local DB, it's used verbatim so the two panels stay in agreement —
  279. // otherwise the node would regenerate (often back to bare
  280. // "inbound-<port>") and the eventual traffic sync-back would try to
  281. // INSERT a row whose tag already exists, hitting the UNIQUE constraint
  282. // on inbounds.tag and rolling the node-side row right back out.
  283. // when Tag is empty (the common UI path) or collides, fall back to the
  284. // transport-aware generateInboundTag.
  285. //
  286. // ignoreId mirrors generateInboundTag: pass 0 on add, the inbound's
  287. // own id on update so a row doesn't see its own current tag as taken.
  288. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  289. if inbound.Tag != "" {
  290. taken, err := s.tagExists(inbound.Tag, ignoreId)
  291. if err != nil {
  292. return "", err
  293. }
  294. if !taken {
  295. return inbound.Tag, nil
  296. }
  297. }
  298. return s.generateInboundTag(inbound, ignoreId)
  299. }
  300. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  301. db := database.GetDB()
  302. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  303. if ignoreId > 0 {
  304. q = q.Where("id != ?", ignoreId)
  305. }
  306. var count int64
  307. if err := q.Count(&count).Error; err != nil {
  308. return false, err
  309. }
  310. return count > 0, nil
  311. }