port_conflict.go 15 KB

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