port_conflict.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  10. "gorm.io/gorm"
  11. )
  12. type transportBits uint8
  13. const (
  14. transportTCP transportBits = 1 << iota
  15. transportUDP
  16. )
  17. func inboundTransports(protocol model.Protocol, streamSettings, settings string) transportBits {
  18. // protocols that ignore streamSettings entirely.
  19. switch protocol {
  20. case model.Hysteria, model.WireGuard, model.AmneziaWG, model.TUIC:
  21. return transportUDP
  22. case model.MTProto:
  23. return transportTCP
  24. }
  25. var bits transportBits
  26. // peek at streamSettings.network to spot udp-based transports.
  27. // parse errors are non-fatal: missing or weird streamSettings just
  28. // keeps the default tcp bit below.
  29. network := ""
  30. if streamSettings != "" {
  31. var ss map[string]any
  32. if json.Unmarshal([]byte(streamSettings), &ss) == nil {
  33. if n, _ := ss["network"].(string); n != "" {
  34. network = n
  35. }
  36. }
  37. }
  38. switch network {
  39. case "kcp", "quic":
  40. bits |= transportUDP
  41. default:
  42. bits |= transportTCP
  43. }
  44. // a few protocols carry their L4 choice in settings instead of (or in
  45. // addition to) streamSettings: SS / Tunnel via a CSV field that wins
  46. // outright, Mixed via an additive udp boolean.
  47. if settings != "" {
  48. var st map[string]any
  49. if json.Unmarshal([]byte(settings), &st) == nil {
  50. switch protocol {
  51. case model.Shadowsocks, model.Tunnel:
  52. key := "network"
  53. if protocol == model.Tunnel {
  54. key = "allowedNetwork"
  55. }
  56. if n, ok := st[key].(string); ok && n != "" {
  57. bits = 0
  58. for part := range strings.SplitSeq(n, ",") {
  59. switch strings.TrimSpace(part) {
  60. case "tcp":
  61. bits |= transportTCP
  62. case "udp":
  63. bits |= transportUDP
  64. }
  65. }
  66. }
  67. case model.Mixed:
  68. // socks/http "mixed" inbound: settings.udp=true means it
  69. // also relays udp on the same port (socks5 udp associate).
  70. if udpOn, _ := st["udp"].(bool); udpOn {
  71. bits |= transportUDP
  72. }
  73. }
  74. }
  75. }
  76. // safety net: never return zero, even if every parse failed.
  77. if bits == 0 {
  78. bits = transportTCP
  79. }
  80. return bits
  81. }
  82. func listenOverlaps(a, b string) bool {
  83. if isAnyListen(a) || isAnyListen(b) {
  84. return true
  85. }
  86. return a == b
  87. }
  88. func isAnyListen(s string) bool {
  89. return s == "" || s == "0.0.0.0" || s == "::" || s == "::0"
  90. }
  91. type portConflictDetail struct {
  92. InboundID int
  93. Remark string
  94. Tag string
  95. Listen string
  96. Port int
  97. // Relay marks Port as an automatic loopback relay port, not a configured one.
  98. Relay bool
  99. Transports transportBits
  100. }
  101. // String renders the detail as a single-line, user-facing summary.
  102. func (d *portConflictDetail) String() string {
  103. name := d.Remark
  104. if name == "" {
  105. name = d.Tag
  106. }
  107. if name == "" {
  108. name = fmt.Sprintf("#%d", d.InboundID)
  109. } else if d.InboundID > 0 {
  110. name = fmt.Sprintf("'%s' (#%d)", name, d.InboundID)
  111. } else {
  112. // reserved/system inbounds (e.g. the Xray API) have no DB id.
  113. name = fmt.Sprintf("'%s'", name)
  114. }
  115. listen := d.Listen
  116. if isAnyListen(listen) {
  117. listen = "*"
  118. }
  119. port := fmt.Sprintf("port %d", d.Port)
  120. if d.Relay {
  121. port = fmt.Sprintf("relay port %d", d.Port)
  122. }
  123. return fmt.Sprintf("%s (%s) already used by inbound %s on %s",
  124. port, transportTagSuffix(d.Transports), name, listen)
  125. }
  126. // defaultXrayAPIPort is the loopback port of the internal Xray API inbound
  127. // (tag "api") seeded into the config template. Used as a fallback when the
  128. // template can't be parsed.
  129. const defaultXrayAPIPort = 62789
  130. // reservedAPIPort returns the port of the internal Xray API inbound declared
  131. // in the config template, falling back to defaultXrayAPIPort.
  132. func reservedAPIPort() int {
  133. tmpl, err := (&SettingService{}).GetXrayConfigTemplate()
  134. if err != nil || tmpl == "" {
  135. return defaultXrayAPIPort
  136. }
  137. var parsed struct {
  138. Inbounds []struct {
  139. Port int `json:"port"`
  140. Tag string `json:"tag"`
  141. } `json:"inbounds"`
  142. }
  143. if json.Unmarshal([]byte(tmpl), &parsed) != nil {
  144. return defaultXrayAPIPort
  145. }
  146. for _, in := range parsed.Inbounds {
  147. if in.Tag == "api" && in.Port > 0 {
  148. return in.Port
  149. }
  150. }
  151. return defaultXrayAPIPort
  152. }
  153. // checkPortConflict reads outside any transaction; callers that must not race a
  154. // concurrent create use checkPortConflictTx inside their own transaction.
  155. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  156. return checkPortConflictTx(database.GetDB(), inbound, ignoreId)
  157. }
  158. func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  159. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  160. // The internal Xray API inbound (tag "api", loopback TCP) isn't a DB row,
  161. // so a local user inbound reusing its port would leave Xray binding the
  162. // port twice (#5304). Nodes run their own Xray, so this only applies to
  163. // the local panel.
  164. if inbound.NodeID == nil && inbound.Port == reservedAPIPort() &&
  165. newBits&transportTCP != 0 && listenOverlaps("127.0.0.1", inbound.Listen) {
  166. return &portConflictDetail{
  167. Tag: "api",
  168. Listen: "127.0.0.1",
  169. Port: inbound.Port,
  170. Transports: transportTCP,
  171. }, nil
  172. }
  173. // Egress SOCKS server holds loopback EgressBasePort when AWG outbounds are
  174. // active; conflict check prevents inbounds from colliding with it.
  175. if inbound.NodeID == nil && inbound.Port == int(amneziawgnet.EgressBasePort) &&
  176. newBits&transportTCP != 0 && listenOverlaps("127.0.0.1", inbound.Listen) {
  177. return &portConflictDetail{
  178. Tag: "amneziawg-egress",
  179. Listen: "127.0.0.1",
  180. Port: inbound.Port,
  181. Transports: transportTCP,
  182. }, nil
  183. }
  184. // Every enabled local AmneziaWG inbound gets its own automatic Xray
  185. // SOCKS5 relay inbound (see injectAmneziawgnetSocks) on 127.0.0.1 at a
  186. // port derived purely from its id (amneziawgnet.SOCKSPortForInbound) --
  187. // like the internal Xray API inbound above, that relay inbound is not
  188. // itself a database row, so the ordinary DB-backed query below can never
  189. // see it. Without this check, an unrelated inbound saved onto that exact
  190. // port silently fails at the next Xray start, taking every other
  191. // protocol down with it, not just AmneziaWG.
  192. if inbound.NodeID == nil && listenOverlaps("127.0.0.1", inbound.Listen) {
  193. conflict, err := checkAmneziawgnetSocksConflict(db, inbound, ignoreId, newBits)
  194. if err != nil {
  195. return nil, err
  196. }
  197. if conflict != nil {
  198. return conflict, nil
  199. }
  200. }
  201. // The reverse direction, only meaningful once the id is known -- AddInbound
  202. // runs it after Save. Only a local row owns a relay slot (#6537 review).
  203. if inbound.NodeID == nil && inbound.Protocol == model.AmneziaWG && ignoreId > 0 {
  204. conflict, err := checkAmneziawgnetSocksRelayCollision(db, ignoreId)
  205. if err != nil {
  206. return nil, err
  207. }
  208. if conflict != nil {
  209. return conflict, nil
  210. }
  211. conflict, err = checkAmneziawgnetSocksReverseConflict(db, ignoreId)
  212. if err != nil {
  213. return nil, err
  214. }
  215. if conflict != nil {
  216. return conflict, nil
  217. }
  218. }
  219. var candidates []*model.Inbound
  220. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  221. if ignoreId > 0 {
  222. q = q.Where("id != ?", ignoreId)
  223. }
  224. if err := q.Find(&candidates).Error; err != nil {
  225. return nil, err
  226. }
  227. for _, c := range candidates {
  228. if !sameNode(c.NodeID, inbound.NodeID) {
  229. continue
  230. }
  231. if !listenOverlaps(c.Listen, inbound.Listen) {
  232. continue
  233. }
  234. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  235. shared := existingBits & newBits
  236. if shared == 0 {
  237. continue
  238. }
  239. return &portConflictDetail{
  240. InboundID: c.Id,
  241. Remark: c.Remark,
  242. Tag: c.Tag,
  243. Listen: c.Listen,
  244. Port: c.Port,
  245. Transports: shared,
  246. }, nil
  247. }
  248. return nil, nil
  249. }
  250. // checkAmneziawgnetSocksConflict: inbound's port vs the relay port every matching
  251. // local row reserves, emitted or not; db keeps it in the caller's transaction (#6225).
  252. func checkAmneziawgnetSocksConflict(db *gorm.DB, inbound *model.Inbound, ignoreId int, newBits transportBits) (*portConflictDetail, error) {
  253. // A disabled row still owns the slot its id derives: SetInboundEnable flips
  254. // the column with no port check, so enabling it later must not collide.
  255. var candidates []*model.Inbound
  256. q := db.Model(model.Inbound{}).Where("protocol = ? AND node_id IS NULL", model.AmneziaWG)
  257. if ignoreId > 0 {
  258. q = q.Where("id != ?", ignoreId)
  259. }
  260. if err := q.Find(&candidates).Error; err != nil {
  261. return nil, err
  262. }
  263. // Ownership does not depend on the peers: the relay appears when the first
  264. // client is added, and the client paths run no port check at all.
  265. for _, c := range candidates {
  266. if amneziawgnet.SOCKSPortForInbound(c.Id) != inbound.Port {
  267. continue
  268. }
  269. return &portConflictDetail{
  270. InboundID: c.Id,
  271. Remark: c.Remark,
  272. Tag: c.Tag,
  273. Listen: "127.0.0.1",
  274. Port: inbound.Port,
  275. Transports: newBits,
  276. }, nil
  277. }
  278. return nil, nil
  279. }
  280. // checkAmneziawgnetSocksRelayCollision reports whether id's derived relay port
  281. // is already claimed by another local AmneziaWG inbound, disabled rows included.
  282. func checkAmneziawgnetSocksRelayCollision(db *gorm.DB, id int) (*portConflictDetail, error) {
  283. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  284. var candidates []*model.Inbound
  285. if err := db.Model(model.Inbound{}).
  286. Where("protocol = ? AND node_id IS NULL AND id != ?", model.AmneziaWG, id).
  287. Find(&candidates).Error; err != nil {
  288. return nil, err
  289. }
  290. for _, c := range candidates {
  291. if amneziawgnet.SOCKSPortForInbound(c.Id) != relayPort {
  292. continue
  293. }
  294. return &portConflictDetail{
  295. InboundID: c.Id,
  296. Remark: c.Remark,
  297. Tag: c.Tag,
  298. Listen: "127.0.0.1",
  299. Port: relayPort,
  300. Relay: true,
  301. Transports: transportTCP,
  302. }, nil
  303. }
  304. return nil, nil
  305. }
  306. // checkAmneziawgnetSocksReverseConflict mirrors checkAmneziawgnetSocksConflict:
  307. // does id's own derived relay port collide with some other inbound's port.
  308. func checkAmneziawgnetSocksReverseConflict(db *gorm.DB, id int) (*portConflictDetail, error) {
  309. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  310. var candidates []*model.Inbound
  311. if err := db.Model(model.Inbound{}).
  312. Where("port = ? AND node_id IS NULL AND id != ?", relayPort, id).
  313. Find(&candidates).Error; err != nil {
  314. return nil, err
  315. }
  316. for _, c := range candidates {
  317. if !listenOverlaps("127.0.0.1", c.Listen) {
  318. continue
  319. }
  320. return &portConflictDetail{
  321. InboundID: c.Id,
  322. Remark: c.Remark,
  323. Tag: c.Tag,
  324. Listen: c.Listen,
  325. Port: relayPort,
  326. Relay: true,
  327. Transports: transportTCP,
  328. }, nil
  329. }
  330. return nil, nil
  331. }
  332. func sameNode(a, b *int) bool {
  333. if a == nil && b == nil {
  334. return true
  335. }
  336. if a == nil || b == nil {
  337. return false
  338. }
  339. return *a == *b
  340. }
  341. func baseInboundTag(port int) string {
  342. return fmt.Sprintf("in-%v", port)
  343. }
  344. func transportTagSuffix(b transportBits) string {
  345. switch b {
  346. case transportTCP:
  347. return "tcp"
  348. case transportUDP:
  349. return "udp"
  350. case transportTCP | transportUDP:
  351. return "tcpudp"
  352. }
  353. return "any"
  354. }
  355. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  356. // can live on the central panel and on a node without bumping the global
  357. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  358. func nodeTagPrefix(nodeID *int) string {
  359. if nodeID == nil {
  360. return ""
  361. }
  362. return fmt.Sprintf("n%d-", *nodeID)
  363. }
  364. func composeInboundTag(port int, nodeID *int, bits transportBits) string {
  365. return nodeTagPrefix(nodeID) + baseInboundTag(port) + "-" + transportTagSuffix(bits)
  366. }
  367. func isAutoGeneratedTag(tag string, port int, nodeID *int, bits transportBits) bool {
  368. base := composeInboundTag(port, nodeID, bits)
  369. if tag == base {
  370. return true
  371. }
  372. suffix, ok := strings.CutPrefix(tag, base+"-")
  373. if !ok || suffix == "" {
  374. return false
  375. }
  376. for _, r := range suffix {
  377. if r < '0' || r > '9' {
  378. return false
  379. }
  380. }
  381. return true
  382. }
  383. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  384. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  385. candidate := composeInboundTag(inbound.Port, inbound.NodeID, bits)
  386. exists, err := s.tagExists(candidate, ignoreId)
  387. if err != nil {
  388. return "", err
  389. }
  390. if !exists {
  391. return candidate, nil
  392. }
  393. for i := 2; i < 100; i++ {
  394. c := fmt.Sprintf("%s-%d", candidate, i)
  395. exists, err = s.tagExists(c, ignoreId)
  396. if err != nil {
  397. return "", err
  398. }
  399. if !exists {
  400. return c, nil
  401. }
  402. }
  403. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  404. }
  405. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  406. if inbound.Tag != "" {
  407. taken, err := s.tagExists(inbound.Tag, ignoreId)
  408. if err != nil {
  409. return "", err
  410. }
  411. if !taken {
  412. return inbound.Tag, nil
  413. }
  414. }
  415. return s.generateInboundTag(inbound, ignoreId)
  416. }
  417. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  418. db := database.GetDB()
  419. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  420. if ignoreId > 0 {
  421. q = q.Where("id != ?", ignoreId)
  422. }
  423. var count int64
  424. if err := q.Count(&count).Error; err != nil {
  425. return false, err
  426. }
  427. return count > 0, nil
  428. }