1
0

port_conflict.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v2/database"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. "github.com/mhsanaei/3x-ui/v2/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. // the listen-overlap rule (specific addr conflicts with any-addr on the
  109. // same port, both directions) is preserved from the previous check.
  110. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (bool, error) {
  111. db := database.GetDB()
  112. // pull every candidate on this port; we filter by listen-overlap and
  113. // transport in go to keep the sql plain. the port column is indexed
  114. // in practice by the existing port check, and the candidate set is
  115. // tiny (one per coexisting socket family at most).
  116. var candidates []*model.Inbound
  117. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  118. if ignoreId > 0 {
  119. q = q.Where("id != ?", ignoreId)
  120. }
  121. if err := q.Find(&candidates).Error; err != nil {
  122. return false, err
  123. }
  124. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  125. for _, c := range candidates {
  126. if !listenOverlaps(c.Listen, inbound.Listen) {
  127. continue
  128. }
  129. if inboundTransports(c.Protocol, c.StreamSettings, c.Settings).conflicts(newBits) {
  130. return true, nil
  131. }
  132. }
  133. return false, nil
  134. }
  135. // baseInboundTag is the historical "inbound-<port>" / "inbound-<listen>:<port>"
  136. // shape. kept exactly so existing routing rules that reference these tags
  137. // keep working after the upgrade.
  138. func baseInboundTag(listen string, port int) string {
  139. if isAnyListen(listen) {
  140. return fmt.Sprintf("inbound-%v", port)
  141. }
  142. return fmt.Sprintf("inbound-%v:%v", listen, port)
  143. }
  144. // transportTagSuffix turns a transport mask into a short, stable string
  145. // for tag disambiguation. only used when the base "inbound-<port>" is
  146. // already taken on a coexisting transport (e.g. tcp inbound already lives
  147. // on 443 and we're now adding a udp one).
  148. func transportTagSuffix(b transportBits) string {
  149. switch b {
  150. case transportTCP:
  151. return "tcp"
  152. case transportUDP:
  153. return "udp"
  154. case transportTCP | transportUDP:
  155. return "mixed"
  156. }
  157. return "any"
  158. }
  159. // generateInboundTag picks a tag for the inbound that doesn't collide with
  160. // any existing row. for the common single-inbound-per-port case the tag
  161. // stays exactly as before ("inbound-443"), so user routing rules don't
  162. // silently change shape on upgrade. only when a same-port neighbour
  163. // already owns the base tag (now possible because tcp/443 and udp/443 can
  164. // coexist after the transport-aware port check) does this append a
  165. // transport suffix like "inbound-443-udp".
  166. //
  167. // ignoreId is the inbound's own id during update so it doesn't see itself
  168. // as a collision; pass 0 on add.
  169. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  170. base := baseInboundTag(inbound.Listen, inbound.Port)
  171. exists, err := s.tagExists(base, ignoreId)
  172. if err != nil {
  173. return "", err
  174. }
  175. if !exists {
  176. return base, nil
  177. }
  178. suffix := transportTagSuffix(inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings))
  179. candidate := base + "-" + suffix
  180. exists, err = s.tagExists(candidate, ignoreId)
  181. if err != nil {
  182. return "", err
  183. }
  184. if !exists {
  185. return candidate, nil
  186. }
  187. // the transport-aware port check should have already blocked this
  188. // path, but guard anyway so a unique-constraint failure doesn't reach
  189. // the user as an opaque sqlite error.
  190. for i := 2; i < 100; i++ {
  191. c := fmt.Sprintf("%s-%d", candidate, i)
  192. exists, err = s.tagExists(c, ignoreId)
  193. if err != nil {
  194. return "", err
  195. }
  196. if !exists {
  197. return c, nil
  198. }
  199. }
  200. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  201. }
  202. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  203. db := database.GetDB()
  204. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  205. if ignoreId > 0 {
  206. q = q.Where("id != ?", ignoreId)
  207. }
  208. var count int64
  209. if err := q.Count(&count).Error; err != nil {
  210. return false, err
  211. }
  212. return count > 0, nil
  213. }