port_conflict.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. Transports transportBits
  101. }
  102. // String renders the detail as a single-line, user-facing summary.
  103. func (d *portConflictDetail) String() string {
  104. name := d.Remark
  105. if name == "" {
  106. name = d.Tag
  107. }
  108. if name == "" {
  109. name = fmt.Sprintf("#%d", d.InboundID)
  110. } else if d.InboundID > 0 {
  111. name = fmt.Sprintf("'%s' (#%d)", name, d.InboundID)
  112. } else {
  113. // reserved/system inbounds (e.g. the Xray API) have no DB id.
  114. name = fmt.Sprintf("'%s'", name)
  115. }
  116. listen := d.Listen
  117. if isAnyListen(listen) {
  118. listen = "*"
  119. }
  120. port := fmt.Sprintf("port %d", d.Port)
  121. if d.Relay {
  122. port = fmt.Sprintf("relay port %d", d.Port)
  123. }
  124. return fmt.Sprintf("%s (%s) already used by inbound %s on %s",
  125. port, transportTagSuffix(d.Transports), name, listen)
  126. }
  127. // defaultXrayAPIPort is the loopback port of the internal Xray API inbound
  128. // (tag "api") seeded into the config template. Used as a fallback when the
  129. // template can't be parsed.
  130. const defaultXrayAPIPort = 62789
  131. // reservedAPIPort returns the port of the internal Xray API inbound declared
  132. // in the config template, falling back to defaultXrayAPIPort.
  133. func reservedAPIPort() int {
  134. tmpl, err := (&SettingService{}).GetXrayConfigTemplate()
  135. if err != nil || tmpl == "" {
  136. return defaultXrayAPIPort
  137. }
  138. var parsed struct {
  139. Inbounds []struct {
  140. Port int `json:"port"`
  141. Tag string `json:"tag"`
  142. } `json:"inbounds"`
  143. }
  144. if json.Unmarshal([]byte(tmpl), &parsed) != nil {
  145. return defaultXrayAPIPort
  146. }
  147. for _, in := range parsed.Inbounds {
  148. if in.Tag == "api" && in.Port > 0 {
  149. return in.Port
  150. }
  151. }
  152. return defaultXrayAPIPort
  153. }
  154. // checkPortConflict reads outside any transaction; callers that must not race a
  155. // concurrent create use checkPortConflictTx inside their own transaction.
  156. func (s *InboundService) checkPortConflict(inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  157. return checkPortConflictTx(database.GetDB(), inbound, ignoreId)
  158. }
  159. func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*portConflictDetail, error) {
  160. newBits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  161. // The internal Xray API inbound (tag "api", loopback TCP) isn't a DB row,
  162. // so a local user inbound reusing its port would leave Xray binding the
  163. // port twice (#5304). Nodes run their own Xray, so this only applies to
  164. // the local panel.
  165. if inbound.NodeID == nil && inbound.Port == reservedAPIPort() &&
  166. newBits&transportTCP != 0 && listenOverlaps("127.0.0.1", inbound.Listen) {
  167. return &portConflictDetail{
  168. Tag: "api",
  169. Listen: "127.0.0.1",
  170. Port: inbound.Port,
  171. Transports: transportTCP,
  172. }, nil
  173. }
  174. // Egress SOCKS server holds loopback EgressBasePort when AWG outbounds are
  175. // active; conflict check prevents inbounds from colliding with it.
  176. if inbound.NodeID == nil && inbound.Port == int(amneziawgnet.EgressBasePort) &&
  177. newBits&transportTCP != 0 && listenOverlaps("127.0.0.1", inbound.Listen) {
  178. return &portConflictDetail{
  179. Tag: "amneziawg-egress",
  180. Listen: "127.0.0.1",
  181. Port: inbound.Port,
  182. Transports: transportTCP,
  183. }, nil
  184. }
  185. // Every enabled local AmneziaWG inbound gets its own automatic Xray
  186. // SOCKS5 relay inbound (see injectAmneziawgnetSocks) on 127.0.0.1 at a
  187. // port derived purely from its id (amneziawgnet.SOCKSPortForInbound) --
  188. // like the internal Xray API inbound above, that relay inbound is not
  189. // itself a database row, so the ordinary DB-backed query below can never
  190. // see it. Without this check, an unrelated inbound saved onto that exact
  191. // port silently fails at the next Xray start, taking every other
  192. // protocol down with it, not just AmneziaWG.
  193. if inbound.NodeID == nil && listenOverlaps("127.0.0.1", inbound.Listen) {
  194. conflict, err := checkAmneziawgnetSocksConflict(db, inbound, ignoreId, newBits)
  195. if err != nil {
  196. return nil, err
  197. }
  198. if conflict != nil {
  199. return conflict, nil
  200. }
  201. }
  202. // The reverse direction, only meaningful once the id is known -- AddInbound
  203. // runs it after Save. Only a local row owns a relay slot (#6537 review).
  204. if inbound.NodeID == nil && inbound.Protocol == model.AmneziaWG && ignoreId > 0 {
  205. conflict, err := checkAmneziawgnetSocksRelayCollision(db, ignoreId)
  206. if err != nil {
  207. return nil, err
  208. }
  209. if conflict != nil {
  210. return conflict, nil
  211. }
  212. conflict, err = checkAmneziawgnetSocksReverseConflict(db, ignoreId)
  213. if err != nil {
  214. return nil, err
  215. }
  216. if conflict != nil {
  217. return conflict, nil
  218. }
  219. }
  220. var candidates []*model.Inbound
  221. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  222. if ignoreId > 0 {
  223. q = q.Where("id != ?", ignoreId)
  224. }
  225. if err := q.Find(&candidates).Error; err != nil {
  226. return nil, err
  227. }
  228. for _, c := range candidates {
  229. if !sameNode(c.NodeID, inbound.NodeID) {
  230. continue
  231. }
  232. if !listenOverlaps(c.Listen, inbound.Listen) {
  233. continue
  234. }
  235. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  236. shared := existingBits & newBits
  237. if shared == 0 {
  238. continue
  239. }
  240. return &portConflictDetail{
  241. InboundID: c.Id,
  242. Remark: c.Remark,
  243. Tag: c.Tag,
  244. Listen: c.Listen,
  245. Port: c.Port,
  246. Transports: shared,
  247. }, nil
  248. }
  249. return nil, nil
  250. }
  251. // checkAmneziawgnetSocksConflict reports whether inbound's own port
  252. // collides with an existing local AmneziaWG inbound's automatic
  253. // Xray SOCKS5 relay port. Unlike the retired kernel-module bridge this
  254. // checks every qualifying AmneziaWG inbound unconditionally: the embedded
  255. // relay has no RouteThroughXray-style opt-in, every one of them gets a
  256. // relay inbound (see injectAmneziawgnetSocks). ignoreId excludes one inbound
  257. // id from the AmneziaWG candidates, the same way the general DB-backed
  258. // conflict query above excludes the inbound being edited from matching
  259. // itself. Takes db rather than fetching its own handle so it runs inside the
  260. // same serialized transaction as the rest of checkPortConflictTx (#6225) --
  261. // otherwise two concurrent AmneziaWG creates could both pass this check
  262. // before either row commits.
  263. func checkAmneziawgnetSocksConflict(db *gorm.DB, inbound *model.Inbound, ignoreId int, newBits transportBits) (*portConflictDetail, error) {
  264. // A disabled row still owns the slot its id derives: SetInboundEnable flips
  265. // the column with no port check, so enabling it later must not collide.
  266. var candidates []*model.Inbound
  267. q := db.Model(model.Inbound{}).Where("protocol = ? AND node_id IS NULL", model.AmneziaWG)
  268. if ignoreId > 0 {
  269. q = q.Where("id != ?", ignoreId)
  270. }
  271. if err := q.Find(&candidates).Error; err != nil {
  272. return nil, err
  273. }
  274. for _, c := range candidates {
  275. if _, ok := amneziawg.InstanceFromInbound(c); !ok {
  276. continue
  277. }
  278. if amneziawgnet.SOCKSPortForInbound(c.Id) != inbound.Port {
  279. continue
  280. }
  281. return &portConflictDetail{
  282. InboundID: c.Id,
  283. Remark: c.Remark,
  284. Tag: c.Tag,
  285. Listen: "127.0.0.1",
  286. Port: inbound.Port,
  287. Transports: newBits,
  288. }, nil
  289. }
  290. return nil, nil
  291. }
  292. // checkAmneziawgnetSocksRelayCollision reports whether id's derived relay port
  293. // is already claimed by another local AmneziaWG inbound, disabled rows included.
  294. func checkAmneziawgnetSocksRelayCollision(db *gorm.DB, id int) (*portConflictDetail, error) {
  295. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  296. var candidates []*model.Inbound
  297. if err := db.Model(model.Inbound{}).
  298. Where("protocol = ? AND node_id IS NULL AND id != ?", model.AmneziaWG, id).
  299. Find(&candidates).Error; err != nil {
  300. return nil, err
  301. }
  302. for _, c := range candidates {
  303. if amneziawgnet.SOCKSPortForInbound(c.Id) != relayPort {
  304. continue
  305. }
  306. return &portConflictDetail{
  307. InboundID: c.Id,
  308. Remark: c.Remark,
  309. Tag: c.Tag,
  310. Listen: "127.0.0.1",
  311. Port: relayPort,
  312. Relay: true,
  313. Transports: transportTCP,
  314. }, nil
  315. }
  316. return nil, nil
  317. }
  318. // checkAmneziawgnetSocksReverseConflict mirrors checkAmneziawgnetSocksConflict:
  319. // does id's own derived relay port collide with some other inbound's port.
  320. func checkAmneziawgnetSocksReverseConflict(db *gorm.DB, id int) (*portConflictDetail, error) {
  321. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  322. var candidates []*model.Inbound
  323. if err := db.Model(model.Inbound{}).
  324. Where("port = ? AND node_id IS NULL AND id != ?", relayPort, id).
  325. Find(&candidates).Error; err != nil {
  326. return nil, err
  327. }
  328. for _, c := range candidates {
  329. if !listenOverlaps("127.0.0.1", c.Listen) {
  330. continue
  331. }
  332. return &portConflictDetail{
  333. InboundID: c.Id,
  334. Remark: c.Remark,
  335. Tag: c.Tag,
  336. Listen: c.Listen,
  337. Port: relayPort,
  338. Relay: true,
  339. Transports: transportTCP,
  340. }, nil
  341. }
  342. return nil, nil
  343. }
  344. func sameNode(a, b *int) bool {
  345. if a == nil && b == nil {
  346. return true
  347. }
  348. if a == nil || b == nil {
  349. return false
  350. }
  351. return *a == *b
  352. }
  353. func baseInboundTag(port int) string {
  354. return fmt.Sprintf("in-%v", port)
  355. }
  356. func transportTagSuffix(b transportBits) string {
  357. switch b {
  358. case transportTCP:
  359. return "tcp"
  360. case transportUDP:
  361. return "udp"
  362. case transportTCP | transportUDP:
  363. return "tcpudp"
  364. }
  365. return "any"
  366. }
  367. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  368. // can live on the central panel and on a node without bumping the global
  369. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  370. func nodeTagPrefix(nodeID *int) string {
  371. if nodeID == nil {
  372. return ""
  373. }
  374. return fmt.Sprintf("n%d-", *nodeID)
  375. }
  376. func composeInboundTag(port int, nodeID *int, bits transportBits) string {
  377. return nodeTagPrefix(nodeID) + baseInboundTag(port) + "-" + transportTagSuffix(bits)
  378. }
  379. func isAutoGeneratedTag(tag string, port int, nodeID *int, bits transportBits) bool {
  380. base := composeInboundTag(port, nodeID, bits)
  381. if tag == base {
  382. return true
  383. }
  384. suffix, ok := strings.CutPrefix(tag, base+"-")
  385. if !ok || suffix == "" {
  386. return false
  387. }
  388. for _, r := range suffix {
  389. if r < '0' || r > '9' {
  390. return false
  391. }
  392. }
  393. return true
  394. }
  395. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  396. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  397. candidate := composeInboundTag(inbound.Port, inbound.NodeID, bits)
  398. exists, err := s.tagExists(candidate, ignoreId)
  399. if err != nil {
  400. return "", err
  401. }
  402. if !exists {
  403. return candidate, nil
  404. }
  405. for i := 2; i < 100; i++ {
  406. c := fmt.Sprintf("%s-%d", candidate, i)
  407. exists, err = s.tagExists(c, ignoreId)
  408. if err != nil {
  409. return "", err
  410. }
  411. if !exists {
  412. return c, nil
  413. }
  414. }
  415. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  416. }
  417. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  418. if inbound.Tag != "" {
  419. taken, err := s.tagExists(inbound.Tag, ignoreId)
  420. if err != nil {
  421. return "", err
  422. }
  423. if !taken {
  424. return inbound.Tag, nil
  425. }
  426. }
  427. return s.generateInboundTag(inbound, ignoreId)
  428. }
  429. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  430. db := database.GetDB()
  431. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  432. if ignoreId > 0 {
  433. q = q.Where("id != ?", ignoreId)
  434. }
  435. var count int64
  436. if err := q.Count(&count).Error; err != nil {
  437. return false, err
  438. }
  439. return count > 0, nil
  440. }