port_conflict.go 12 KB

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