port_conflict.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. // conflicts is true when the two masks share any L4 transport.
  19. func (b transportBits) conflicts(o transportBits) bool { return b&o != 0 }
  20. // inboundTransports returns the L4 transports the given inbound listens on.
  21. // always returns at least one bit (falls back to tcp on parse errors), so
  22. // the validator never gets looser than the old port-only check.
  23. //
  24. // the rules:
  25. // - hysteria, hysteria2, wireguard: udp regardless of streamSettings
  26. // - streamSettings.network=kcp: udp
  27. // - shadowsocks: whatever settings.network says ("tcp" / "udp" / "tcp,udp")
  28. // - mixed (socks/http combo): tcp + udp when settings.udp is true
  29. // - everything else: tcp
  30. func inboundTransports(protocol model.Protocol, streamSettings, settings string) transportBits {
  31. // protocols that ignore streamSettings entirely.
  32. switch protocol {
  33. case model.Hysteria, model.Hysteria2, model.WireGuard:
  34. return transportUDP
  35. }
  36. var bits transportBits
  37. // peek at streamSettings.network to spot udp transports like kcp.
  38. // parse errors are non-fatal: missing or weird streamSettings just
  39. // keeps the default tcp bit below.
  40. network := ""
  41. if streamSettings != "" {
  42. var ss map[string]any
  43. if json.Unmarshal([]byte(streamSettings), &ss) == nil {
  44. if n, _ := ss["network"].(string); n != "" {
  45. network = n
  46. }
  47. }
  48. }
  49. if network == "kcp" {
  50. bits |= transportUDP
  51. } else {
  52. bits |= transportTCP
  53. }
  54. // some protocols also listen on udp on the same port via their own
  55. // settings json. parse and merge.
  56. if settings != "" {
  57. var st map[string]any
  58. if json.Unmarshal([]byte(settings), &st) == nil {
  59. switch protocol {
  60. case model.Shadowsocks:
  61. // shadowsocks settings.network controls both tcp and udp,
  62. // independently of streamSettings. the field takes "tcp",
  63. // "udp", or "tcp,udp". if it's set, it wins outright.
  64. if n, ok := st["network"].(string); ok && n != "" {
  65. bits = 0
  66. for _, part := range strings.Split(n, ",") {
  67. switch strings.TrimSpace(part) {
  68. case "tcp":
  69. bits |= transportTCP
  70. case "udp":
  71. bits |= transportUDP
  72. }
  73. }
  74. }
  75. case model.Mixed:
  76. // socks/http "mixed" inbound: settings.udp=true means it
  77. // also relays udp on the same port (socks5 udp associate).
  78. if udpOn, _ := st["udp"].(bool); udpOn {
  79. bits |= transportUDP
  80. }
  81. }
  82. }
  83. }
  84. // safety net: never return zero, even if every parse failed.
  85. if bits == 0 {
  86. bits = transportTCP
  87. }
  88. return bits
  89. }
  90. // listenOverlaps reports whether two listen addresses can collide on the
  91. // same port. preserves the rule from the original checkPortExist:
  92. // any-address (empty / 0.0.0.0 / :: / ::0) overlaps with everything,
  93. // otherwise only identical specific addresses overlap.
  94. func listenOverlaps(a, b string) bool {
  95. if isAnyListen(a) || isAnyListen(b) {
  96. return true
  97. }
  98. return a == b
  99. }
  100. func isAnyListen(s string) bool {
  101. return s == "" || s == "0.0.0.0" || s == "::" || s == "::0"
  102. }
  103. // checkPortConflict reports whether adding/updating an inbound on
  104. // (listen, port) would clash with an existing inbound. unlike the old
  105. // port-only check, this one understands that tcp/443 and udp/443 are
  106. // independent sockets in linux and may coexist on the same address.
  107. //
  108. // node scope: inbounds with different NodeID run on different physical
  109. // machines (local panel xray vs a remote node, or two remote nodes),
  110. // so their sockets can't collide. only candidates with the same NodeID
  111. // participate in the listen/transport overlap check.
  112. //
  113. // the listen-overlap rule (specific addr conflicts with any-addr on the
  114. // same port, both directions) is preserved from the previous check.
  115. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (bool, error) {
  116. db := database.GetDB()
  117. var candidates []*model.Inbound
  118. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  119. if ignoreId > 0 {
  120. q = q.Where("id != ?", ignoreId)
  121. }
  122. if err := q.Find(&candidates).Error; err != nil {
  123. return false, err
  124. }
  125. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  126. for _, c := range candidates {
  127. if !sameNode(c.NodeID, inbound.NodeID) {
  128. continue
  129. }
  130. if !listenOverlaps(c.Listen, inbound.Listen) {
  131. continue
  132. }
  133. if inboundTransports(c.Protocol, c.StreamSettings, c.Settings).conflicts(newBits) {
  134. return true, nil
  135. }
  136. }
  137. return false, nil
  138. }
  139. // sameNode reports whether two NodeID pointers refer to the same xray
  140. // process. nil/nil means both inbounds run on the local panel; non-nil
  141. // with equal value means they share the same remote node. any mix
  142. // (local vs remote, remote-A vs remote-B) is "different node" and
  143. // can't produce a real socket collision.
  144. func sameNode(a, b *int) bool {
  145. if a == nil && b == nil {
  146. return true
  147. }
  148. if a == nil || b == nil {
  149. return false
  150. }
  151. return *a == *b
  152. }
  153. // baseInboundTag is the historical "inbound-<port>" / "inbound-<listen>:<port>"
  154. // shape. kept exactly so existing routing rules that reference these tags
  155. // keep working after the upgrade.
  156. func baseInboundTag(listen string, port int) string {
  157. if isAnyListen(listen) {
  158. return fmt.Sprintf("inbound-%v", port)
  159. }
  160. return fmt.Sprintf("inbound-%v:%v", listen, port)
  161. }
  162. // transportTagSuffix turns a transport mask into a short, stable string
  163. // for tag disambiguation. only used when the base "inbound-<port>" is
  164. // already taken on a coexisting transport (e.g. tcp inbound already lives
  165. // on 443 and we're now adding a udp one).
  166. func transportTagSuffix(b transportBits) string {
  167. switch b {
  168. case transportTCP:
  169. return "tcp"
  170. case transportUDP:
  171. return "udp"
  172. case transportTCP | transportUDP:
  173. return "mixed"
  174. }
  175. return "any"
  176. }
  177. // generateInboundTag picks a tag for the inbound that doesn't collide with
  178. // any existing row. for the common single-inbound-per-port case the tag
  179. // stays exactly as before ("inbound-443"), so user routing rules don't
  180. // silently change shape on upgrade. only when a same-port neighbour
  181. // already owns the base tag (now possible because tcp/443 and udp/443 can
  182. // coexist after the transport-aware port check) does this append a
  183. // transport suffix like "inbound-443-udp".
  184. //
  185. // ignoreId is the inbound's own id during update so it doesn't see itself
  186. // as a collision; pass 0 on add.
  187. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  188. base := baseInboundTag(inbound.Listen, inbound.Port)
  189. exists, err := s.tagExists(base, ignoreId)
  190. if err != nil {
  191. return "", err
  192. }
  193. if !exists {
  194. return base, nil
  195. }
  196. suffix := transportTagSuffix(inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings))
  197. candidate := base + "-" + suffix
  198. exists, err = s.tagExists(candidate, ignoreId)
  199. if err != nil {
  200. return "", err
  201. }
  202. if !exists {
  203. return candidate, nil
  204. }
  205. // the transport-aware port check should have already blocked this
  206. // path, but guard anyway so a unique-constraint failure doesn't reach
  207. // the user as an opaque sqlite error.
  208. for i := 2; i < 100; i++ {
  209. c := fmt.Sprintf("%s-%d", candidate, i)
  210. exists, err = s.tagExists(c, ignoreId)
  211. if err != nil {
  212. return "", err
  213. }
  214. if !exists {
  215. return c, nil
  216. }
  217. }
  218. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  219. }
  220. // resolveInboundTag chooses a tag for an Add or Update. when the caller
  221. // supplied a non-empty Tag (e.g. the central panel pushed its picked
  222. // tag to a node during a multi-node sync) and that tag is free in the
  223. // local DB, it's used verbatim so the two panels stay in agreement —
  224. // otherwise the node would regenerate (often back to bare
  225. // "inbound-<port>") and the eventual traffic sync-back would try to
  226. // INSERT a row whose tag already exists, hitting the UNIQUE constraint
  227. // on inbounds.tag and rolling the node-side row right back out.
  228. // when Tag is empty (the common UI path) or collides, fall back to the
  229. // transport-aware generateInboundTag.
  230. //
  231. // ignoreId mirrors generateInboundTag: pass 0 on add, the inbound's
  232. // own id on update so a row doesn't see its own current tag as taken.
  233. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  234. if inbound.Tag != "" {
  235. taken, err := s.tagExists(inbound.Tag, ignoreId)
  236. if err != nil {
  237. return "", err
  238. }
  239. if !taken {
  240. return inbound.Tag, nil
  241. }
  242. }
  243. return s.generateInboundTag(inbound, ignoreId)
  244. }
  245. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  246. db := database.GetDB()
  247. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  248. if ignoreId > 0 {
  249. q = q.Where("id != ?", ignoreId)
  250. }
  251. var count int64
  252. if err := q.Count(&count).Error; err != nil {
  253. return false, err
  254. }
  255. return count > 0, nil
  256. }