1
0

port_conflict.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  9. "gorm.io/gorm"
  10. )
  11. type transportBits uint8
  12. const (
  13. transportTCP transportBits = 1 << iota
  14. transportUDP
  15. )
  16. func inboundTransports(protocol model.Protocol, streamSettings, settings string) transportBits {
  17. // protocols that ignore streamSettings entirely.
  18. switch protocol {
  19. case model.Hysteria, model.WireGuard:
  20. return transportUDP
  21. case model.MTProto:
  22. return transportTCP
  23. }
  24. var bits transportBits
  25. // peek at streamSettings.network to spot udp-based transports.
  26. // parse errors are non-fatal: missing or weird streamSettings just
  27. // keeps the default tcp bit below.
  28. network := ""
  29. if streamSettings != "" {
  30. var ss map[string]any
  31. if json.Unmarshal([]byte(streamSettings), &ss) == nil {
  32. if n, _ := ss["network"].(string); n != "" {
  33. network = n
  34. }
  35. }
  36. }
  37. switch network {
  38. case "kcp", "quic":
  39. bits |= transportUDP
  40. default:
  41. bits |= transportTCP
  42. }
  43. // a few protocols carry their L4 choice in settings instead of (or in
  44. // addition to) streamSettings: SS / Tunnel via a CSV field that wins
  45. // outright, Mixed via an additive udp boolean.
  46. if settings != "" {
  47. var st map[string]any
  48. if json.Unmarshal([]byte(settings), &st) == nil {
  49. switch protocol {
  50. case model.Shadowsocks, model.Tunnel:
  51. key := "network"
  52. if protocol == model.Tunnel {
  53. key = "allowedNetwork"
  54. }
  55. if n, ok := st[key].(string); ok && n != "" {
  56. bits = 0
  57. for part := range strings.SplitSeq(n, ",") {
  58. switch strings.TrimSpace(part) {
  59. case "tcp":
  60. bits |= transportTCP
  61. case "udp":
  62. bits |= transportUDP
  63. }
  64. }
  65. }
  66. case model.Mixed:
  67. // socks/http "mixed" inbound: settings.udp=true means it
  68. // also relays udp on the same port (socks5 udp associate).
  69. if udpOn, _ := st["udp"].(bool); udpOn {
  70. bits |= transportUDP
  71. }
  72. }
  73. }
  74. }
  75. // safety net: never return zero, even if every parse failed.
  76. if bits == 0 {
  77. bits = transportTCP
  78. }
  79. return bits
  80. }
  81. func listenOverlaps(a, b string) bool {
  82. if isAnyListen(a) || isAnyListen(b) {
  83. return true
  84. }
  85. return a == b
  86. }
  87. func isAnyListen(s string) bool {
  88. return s == "" || s == "0.0.0.0" || s == "::" || s == "::0"
  89. }
  90. type portConflictDetail struct {
  91. InboundID int
  92. Remark string
  93. Tag string
  94. Listen string
  95. Port int
  96. Transports transportBits
  97. }
  98. // String renders the detail as a single-line, user-facing summary.
  99. func (d *portConflictDetail) String() string {
  100. name := d.Remark
  101. if name == "" {
  102. name = d.Tag
  103. }
  104. if name == "" {
  105. name = fmt.Sprintf("#%d", d.InboundID)
  106. } else if d.InboundID > 0 {
  107. name = fmt.Sprintf("'%s' (#%d)", name, d.InboundID)
  108. } else {
  109. // reserved/system inbounds (e.g. the Xray API) have no DB id.
  110. name = fmt.Sprintf("'%s'", name)
  111. }
  112. listen := d.Listen
  113. if isAnyListen(listen) {
  114. listen = "*"
  115. }
  116. return fmt.Sprintf("port %d (%s) already used by inbound %s on %s",
  117. d.Port, transportTagSuffix(d.Transports), name, listen)
  118. }
  119. // defaultXrayAPIPort is the loopback port of the internal Xray API inbound
  120. // (tag "api") seeded into the config template. Used as a fallback when the
  121. // template can't be parsed.
  122. const defaultXrayAPIPort = 62789
  123. // reservedAPIPort returns the port of the internal Xray API inbound declared
  124. // in the config template, falling back to defaultXrayAPIPort.
  125. func reservedAPIPort() int {
  126. tmpl, err := (&SettingService{}).GetXrayConfigTemplate()
  127. if err != nil || tmpl == "" {
  128. return defaultXrayAPIPort
  129. }
  130. var parsed struct {
  131. Inbounds []struct {
  132. Port int `json:"port"`
  133. Tag string `json:"tag"`
  134. } `json:"inbounds"`
  135. }
  136. if json.Unmarshal([]byte(tmpl), &parsed) != nil {
  137. return defaultXrayAPIPort
  138. }
  139. for _, in := range parsed.Inbounds {
  140. if in.Tag == "api" && in.Port > 0 {
  141. return in.Port
  142. }
  143. }
  144. return defaultXrayAPIPort
  145. }
  146. // checkPortConflict reads outside any transaction; callers that must not race a
  147. // concurrent create use checkPortConflictTx inside their own transaction.
  148. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  149. return checkPortConflictTx(database.GetDB(), inbound, ignoreId)
  150. }
  151. func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  152. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  153. // The internal Xray API inbound (tag "api", loopback TCP) isn't a DB row,
  154. // so a local user inbound reusing its port would leave Xray binding the
  155. // port twice (#5304). Nodes run their own Xray, so this only applies to
  156. // the local panel.
  157. if inbound.NodeID == nil && inbound.Port == reservedAPIPort() &&
  158. newBits&transportTCP != 0 && listenOverlaps("127.0.0.1", inbound.Listen) {
  159. return &portConflictDetail{
  160. Tag: "api",
  161. Listen: "127.0.0.1",
  162. Port: inbound.Port,
  163. Transports: transportTCP,
  164. }, nil
  165. }
  166. var candidates []*model.Inbound
  167. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  168. if ignoreId > 0 {
  169. q = q.Where("id != ?", ignoreId)
  170. }
  171. if err := q.Find(&candidates).Error; err != nil {
  172. return nil, err
  173. }
  174. for _, c := range candidates {
  175. if !sameNode(c.NodeID, inbound.NodeID) {
  176. continue
  177. }
  178. if !listenOverlaps(c.Listen, inbound.Listen) {
  179. continue
  180. }
  181. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  182. shared := existingBits & newBits
  183. if shared == 0 {
  184. continue
  185. }
  186. return &portConflictDetail{
  187. InboundID: c.Id,
  188. Remark: c.Remark,
  189. Tag: c.Tag,
  190. Listen: c.Listen,
  191. Port: c.Port,
  192. Transports: shared,
  193. }, nil
  194. }
  195. return nil, nil
  196. }
  197. func sameNode(a, b *int) bool {
  198. if a == nil && b == nil {
  199. return true
  200. }
  201. if a == nil || b == nil {
  202. return false
  203. }
  204. return *a == *b
  205. }
  206. func baseInboundTag(port int) string {
  207. return fmt.Sprintf("in-%v", port)
  208. }
  209. func transportTagSuffix(b transportBits) string {
  210. switch b {
  211. case transportTCP:
  212. return "tcp"
  213. case transportUDP:
  214. return "udp"
  215. case transportTCP | transportUDP:
  216. return "tcpudp"
  217. }
  218. return "any"
  219. }
  220. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  221. // can live on the central panel and on a node without bumping the global
  222. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  223. func nodeTagPrefix(nodeID *int) string {
  224. if nodeID == nil {
  225. return ""
  226. }
  227. return fmt.Sprintf("n%d-", *nodeID)
  228. }
  229. func composeInboundTag(port int, nodeID *int, bits transportBits) string {
  230. return nodeTagPrefix(nodeID) + baseInboundTag(port) + "-" + transportTagSuffix(bits)
  231. }
  232. func isAutoGeneratedTag(tag string, port int, nodeID *int, bits transportBits) bool {
  233. base := composeInboundTag(port, nodeID, bits)
  234. if tag == base {
  235. return true
  236. }
  237. suffix, ok := strings.CutPrefix(tag, base+"-")
  238. if !ok || suffix == "" {
  239. return false
  240. }
  241. for _, r := range suffix {
  242. if r < '0' || r > '9' {
  243. return false
  244. }
  245. }
  246. return true
  247. }
  248. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  249. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  250. candidate := composeInboundTag(inbound.Port, inbound.NodeID, bits)
  251. exists, err := s.tagExists(candidate, ignoreId)
  252. if err != nil {
  253. return "", err
  254. }
  255. if !exists {
  256. return candidate, nil
  257. }
  258. for i := 2; i < 100; i++ {
  259. c := fmt.Sprintf("%s-%d", candidate, i)
  260. exists, err = s.tagExists(c, ignoreId)
  261. if err != nil {
  262. return "", err
  263. }
  264. if !exists {
  265. return c, nil
  266. }
  267. }
  268. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  269. }
  270. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  271. if inbound.Tag != "" {
  272. taken, err := s.tagExists(inbound.Tag, ignoreId)
  273. if err != nil {
  274. return "", err
  275. }
  276. if !taken {
  277. return inbound.Tag, nil
  278. }
  279. }
  280. return s.generateInboundTag(inbound, ignoreId)
  281. }
  282. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  283. db := database.GetDB()
  284. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  285. if ignoreId > 0 {
  286. q = q.Where("id != ?", ignoreId)
  287. }
  288. var count int64
  289. if err := q.Count(&count).Error; err != nil {
  290. return false, err
  291. }
  292. return count > 0, nil
  293. }