port_conflict.go 17 KB

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