port_conflict.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. if self := amneziawgnetSocksSelfConflict(inbound, ignoreId); self != "" {
  205. return nil, common.NewError(self)
  206. }
  207. conflict, err := checkAmneziawgnetSocksRelayCollision(db, ignoreId)
  208. if err != nil {
  209. return nil, err
  210. }
  211. if conflict != nil {
  212. return conflict, nil
  213. }
  214. conflict, err = checkAmneziawgnetSocksReverseConflict(db, ignoreId)
  215. if err != nil {
  216. return nil, err
  217. }
  218. if conflict != nil {
  219. return conflict, nil
  220. }
  221. }
  222. var candidates []*model.Inbound
  223. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  224. if ignoreId > 0 {
  225. q = q.Where("id != ?", ignoreId)
  226. }
  227. if err := q.Find(&candidates).Error; err != nil {
  228. return nil, err
  229. }
  230. for _, c := range candidates {
  231. if !sameNode(c.NodeID, inbound.NodeID) {
  232. continue
  233. }
  234. if !listenOverlaps(c.Listen, inbound.Listen) {
  235. continue
  236. }
  237. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  238. shared := existingBits & newBits
  239. if shared == 0 {
  240. continue
  241. }
  242. return &portConflictDetail{
  243. InboundID: c.Id,
  244. Remark: c.Remark,
  245. Tag: c.Tag,
  246. Listen: c.Listen,
  247. Port: c.Port,
  248. Transports: shared,
  249. }, nil
  250. }
  251. return nil, nil
  252. }
  253. // checkAmneziawgnetSocksConflict: inbound's port vs the relay port every matching
  254. // local row reserves, emitted or not; db keeps it in the caller's transaction (#6225).
  255. func checkAmneziawgnetSocksConflict(db *gorm.DB, inbound *model.Inbound, ignoreId int, newBits transportBits) (*portConflictDetail, error) {
  256. // A disabled row still owns the slot its id derives: SetInboundEnable flips
  257. // the column with no port check, so enabling it later must not collide.
  258. var candidates []*model.Inbound
  259. q := db.Model(model.Inbound{}).Where("protocol = ? AND node_id IS NULL", model.AmneziaWG)
  260. if ignoreId > 0 {
  261. q = q.Where("id != ?", ignoreId)
  262. }
  263. if err := q.Find(&candidates).Error; err != nil {
  264. return nil, err
  265. }
  266. // Ownership does not depend on the peers: the relay appears when the first
  267. // client is added, and the client paths run no port check at all.
  268. for _, c := range candidates {
  269. if amneziawgnet.SOCKSPortForInbound(c.Id) != inbound.Port {
  270. continue
  271. }
  272. return &portConflictDetail{
  273. InboundID: c.Id,
  274. Remark: c.Remark,
  275. Tag: c.Tag,
  276. Listen: "127.0.0.1",
  277. Port: inbound.Port,
  278. Transports: newBits,
  279. }, nil
  280. }
  281. return nil, nil
  282. }
  283. // checkAmneziawgnetSocksRelayCollision reports whether id's derived relay port
  284. // is already claimed by another local AmneziaWG inbound, disabled rows included.
  285. func checkAmneziawgnetSocksRelayCollision(db *gorm.DB, id int) (*portConflictDetail, error) {
  286. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  287. var candidates []*model.Inbound
  288. if err := db.Model(model.Inbound{}).
  289. Where("protocol = ? AND node_id IS NULL AND id != ?", model.AmneziaWG, id).
  290. Find(&candidates).Error; err != nil {
  291. return nil, err
  292. }
  293. for _, c := range candidates {
  294. if amneziawgnet.SOCKSPortForInbound(c.Id) != relayPort {
  295. continue
  296. }
  297. return &portConflictDetail{
  298. InboundID: c.Id,
  299. Remark: c.Remark,
  300. Tag: c.Tag,
  301. Listen: "127.0.0.1",
  302. Port: relayPort,
  303. Relay: true,
  304. Transports: transportTCP,
  305. }, nil
  306. }
  307. return nil, nil
  308. }
  309. // amneziawgnetSocksSelfConflict: a row's own WireGuard port vs the relay port its
  310. // own id derives -- all three checks below exclude that id, so nothing else does.
  311. func amneziawgnetSocksSelfConflict(inbound *model.Inbound, id int) string {
  312. if id <= 0 || inbound.NodeID != nil || !listenOverlaps("127.0.0.1", inbound.Listen) {
  313. return ""
  314. }
  315. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  316. if inbound.Port != relayPort {
  317. return ""
  318. }
  319. return fmt.Sprintf("WireGuard port %d is inbound #%d's own SOCKS5 relay port on 127.0.0.1; choose a different WireGuard port",
  320. relayPort, id)
  321. }
  322. // checkAmneziawgnetSocksReverseConflict mirrors checkAmneziawgnetSocksConflict:
  323. // does id's own derived relay port collide with some other inbound's port.
  324. func checkAmneziawgnetSocksReverseConflict(db *gorm.DB, id int) (*portConflictDetail, error) {
  325. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  326. var candidates []*model.Inbound
  327. if err := db.Model(model.Inbound{}).
  328. Where("port = ? AND node_id IS NULL AND id != ?", relayPort, id).
  329. Find(&candidates).Error; err != nil {
  330. return nil, err
  331. }
  332. for _, c := range candidates {
  333. if !listenOverlaps("127.0.0.1", c.Listen) {
  334. continue
  335. }
  336. return &portConflictDetail{
  337. InboundID: c.Id,
  338. Remark: c.Remark,
  339. Tag: c.Tag,
  340. Listen: c.Listen,
  341. Port: relayPort,
  342. Relay: true,
  343. Transports: transportTCP,
  344. }, nil
  345. }
  346. return nil, nil
  347. }
  348. func sameNode(a, b *int) bool {
  349. if a == nil && b == nil {
  350. return true
  351. }
  352. if a == nil || b == nil {
  353. return false
  354. }
  355. return *a == *b
  356. }
  357. func baseInboundTag(port int) string {
  358. return fmt.Sprintf("in-%v", port)
  359. }
  360. func transportTagSuffix(b transportBits) string {
  361. switch b {
  362. case transportTCP:
  363. return "tcp"
  364. case transportUDP:
  365. return "udp"
  366. case transportTCP | transportUDP:
  367. return "tcpudp"
  368. }
  369. return "any"
  370. }
  371. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  372. // can live on the central panel and on a node without bumping the global
  373. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  374. func nodeTagPrefix(nodeID *int) string {
  375. if nodeID == nil {
  376. return ""
  377. }
  378. return fmt.Sprintf("n%d-", *nodeID)
  379. }
  380. func composeInboundTag(port int, nodeID *int, bits transportBits) string {
  381. return nodeTagPrefix(nodeID) + baseInboundTag(port) + "-" + transportTagSuffix(bits)
  382. }
  383. func isAutoGeneratedTag(tag string, port int, nodeID *int, bits transportBits) bool {
  384. base := composeInboundTag(port, nodeID, bits)
  385. if tag == base {
  386. return true
  387. }
  388. suffix, ok := strings.CutPrefix(tag, base+"-")
  389. if !ok || suffix == "" {
  390. return false
  391. }
  392. for _, r := range suffix {
  393. if r < '0' || r > '9' {
  394. return false
  395. }
  396. }
  397. return true
  398. }
  399. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  400. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  401. candidate := composeInboundTag(inbound.Port, inbound.NodeID, bits)
  402. exists, err := s.tagExists(candidate, ignoreId)
  403. if err != nil {
  404. return "", err
  405. }
  406. if !exists {
  407. return candidate, nil
  408. }
  409. for i := 2; i < 100; i++ {
  410. c := fmt.Sprintf("%s-%d", candidate, i)
  411. exists, err = s.tagExists(c, ignoreId)
  412. if err != nil {
  413. return "", err
  414. }
  415. if !exists {
  416. return c, nil
  417. }
  418. }
  419. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  420. }
  421. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  422. if inbound.Tag != "" {
  423. taken, err := s.tagExists(inbound.Tag, ignoreId)
  424. if err != nil {
  425. return "", err
  426. }
  427. if !taken {
  428. return inbound.Tag, nil
  429. }
  430. }
  431. return s.generateInboundTag(inbound, ignoreId)
  432. }
  433. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  434. db := database.GetDB()
  435. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  436. if ignoreId > 0 {
  437. q = q.Where("id != ?", ignoreId)
  438. }
  439. var count int64
  440. if err := q.Count(&count).Error; err != nil {
  441. return false, err
  442. }
  443. return count > 0, nil
  444. }