port_conflict.go 21 KB

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