port_conflict.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. // Every enabled local AmneziaWG inbound gets its own automatic Xray
  169. // SOCKS5 relay inbound (see injectAmneziawgnetSocks) on 127.0.0.1 at a
  170. // port derived purely from its id (amneziawgnet.SOCKSPortForInbound) --
  171. // like the internal Xray API inbound above, that relay inbound is not
  172. // itself a database row, so the ordinary DB-backed query below can never
  173. // see it. Without this check, an unrelated inbound saved onto that exact
  174. // port silently fails at the next Xray start, taking every other
  175. // protocol down with it, not just AmneziaWG.
  176. if inbound.NodeID == nil && listenOverlaps("127.0.0.1", inbound.Listen) {
  177. conflict, err := checkAmneziawgnetSocksConflict(db, inbound, ignoreId, newBits)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if conflict != nil {
  182. return conflict, nil
  183. }
  184. }
  185. // The reverse direction, only meaningful once the id is known (create's
  186. // ignoreId==0 means AddInbound must run this itself after Save assigns one).
  187. if inbound.Protocol == model.AmneziaWG && ignoreId > 0 {
  188. conflict, err := checkAmneziawgnetSocksReverseConflict(db, ignoreId)
  189. if err != nil {
  190. return nil, err
  191. }
  192. if conflict != nil {
  193. return conflict, nil
  194. }
  195. }
  196. var candidates []*model.Inbound
  197. q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
  198. if ignoreId > 0 {
  199. q = q.Where("id != ?", ignoreId)
  200. }
  201. if err := q.Find(&candidates).Error; err != nil {
  202. return nil, err
  203. }
  204. for _, c := range candidates {
  205. if !sameNode(c.NodeID, inbound.NodeID) {
  206. continue
  207. }
  208. if !listenOverlaps(c.Listen, inbound.Listen) {
  209. continue
  210. }
  211. existingBits := inboundTransports(c.Protocol, c.StreamSettings, c.Settings)
  212. shared := existingBits & newBits
  213. if shared == 0 {
  214. continue
  215. }
  216. return &portConflictDetail{
  217. InboundID: c.Id,
  218. Remark: c.Remark,
  219. Tag: c.Tag,
  220. Listen: c.Listen,
  221. Port: c.Port,
  222. Transports: shared,
  223. }, nil
  224. }
  225. return nil, nil
  226. }
  227. // checkAmneziawgnetSocksConflict reports whether inbound's own port
  228. // collides with an existing, enabled local AmneziaWG inbound's automatic
  229. // Xray SOCKS5 relay port. Unlike the retired kernel-module bridge this
  230. // checks every qualifying AmneziaWG inbound unconditionally: the embedded
  231. // relay has no RouteThroughXray-style opt-in, every one of them gets a
  232. // relay inbound (see injectAmneziawgnetSocks). ignoreId excludes one inbound
  233. // id from the AmneziaWG candidates, the same way the general DB-backed
  234. // conflict query above excludes the inbound being edited from matching
  235. // itself. Takes db rather than fetching its own handle so it runs inside the
  236. // same serialized transaction as the rest of checkPortConflictTx (#6225) --
  237. // otherwise two concurrent AmneziaWG creates could both pass this check
  238. // before either row commits.
  239. func checkAmneziawgnetSocksConflict(db *gorm.DB, inbound *model.Inbound, ignoreId int, newBits transportBits) (*portConflictDetail, error) {
  240. var candidates []*model.Inbound
  241. q := db.Model(model.Inbound{}).Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true)
  242. if ignoreId > 0 {
  243. q = q.Where("id != ?", ignoreId)
  244. }
  245. if err := q.Find(&candidates).Error; err != nil {
  246. return nil, err
  247. }
  248. for _, c := range candidates {
  249. if _, ok := amneziawg.InstanceFromInbound(c); !ok {
  250. continue
  251. }
  252. if amneziawgnet.SOCKSPortForInbound(c.Id) != inbound.Port {
  253. continue
  254. }
  255. return &portConflictDetail{
  256. InboundID: c.Id,
  257. Remark: c.Remark,
  258. Tag: c.Tag,
  259. Listen: "127.0.0.1",
  260. Port: inbound.Port,
  261. Transports: newBits,
  262. }, nil
  263. }
  264. return nil, nil
  265. }
  266. // checkAmneziawgnetSocksReverseConflict mirrors checkAmneziawgnetSocksConflict:
  267. // does id's own derived relay port collide with some other inbound's port.
  268. func checkAmneziawgnetSocksReverseConflict(db *gorm.DB, id int) (*portConflictDetail, error) {
  269. relayPort := amneziawgnet.SOCKSPortForInbound(id)
  270. var candidates []*model.Inbound
  271. if err := db.Model(model.Inbound{}).
  272. Where("port = ? AND node_id IS NULL AND id != ?", relayPort, id).
  273. Find(&candidates).Error; err != nil {
  274. return nil, err
  275. }
  276. for _, c := range candidates {
  277. if !listenOverlaps("127.0.0.1", c.Listen) {
  278. continue
  279. }
  280. return &portConflictDetail{
  281. InboundID: c.Id,
  282. Remark: c.Remark,
  283. Tag: c.Tag,
  284. Listen: c.Listen,
  285. Port: relayPort,
  286. Transports: transportTCP,
  287. }, nil
  288. }
  289. return nil, nil
  290. }
  291. func sameNode(a, b *int) bool {
  292. if a == nil && b == nil {
  293. return true
  294. }
  295. if a == nil || b == nil {
  296. return false
  297. }
  298. return *a == *b
  299. }
  300. func baseInboundTag(port int) string {
  301. return fmt.Sprintf("in-%v", port)
  302. }
  303. func transportTagSuffix(b transportBits) string {
  304. switch b {
  305. case transportTCP:
  306. return "tcp"
  307. case transportUDP:
  308. return "udp"
  309. case transportTCP | transportUDP:
  310. return "tcpudp"
  311. }
  312. return "any"
  313. }
  314. // nodeTagPrefix scopes a tag to one remote node so the same listen+port
  315. // can live on the central panel and on a node without bumping the global
  316. // UNIQUE(inbounds.tag) constraint. nil → "" (local panel).
  317. func nodeTagPrefix(nodeID *int) string {
  318. if nodeID == nil {
  319. return ""
  320. }
  321. return fmt.Sprintf("n%d-", *nodeID)
  322. }
  323. func composeInboundTag(port int, nodeID *int, bits transportBits) string {
  324. return nodeTagPrefix(nodeID) + baseInboundTag(port) + "-" + transportTagSuffix(bits)
  325. }
  326. func isAutoGeneratedTag(tag string, port int, nodeID *int, bits transportBits) bool {
  327. base := composeInboundTag(port, nodeID, bits)
  328. if tag == base {
  329. return true
  330. }
  331. suffix, ok := strings.CutPrefix(tag, base+"-")
  332. if !ok || suffix == "" {
  333. return false
  334. }
  335. for _, r := range suffix {
  336. if r < '0' || r > '9' {
  337. return false
  338. }
  339. }
  340. return true
  341. }
  342. func (s *InboundService) generateInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  343. bits := inboundTransports(inbound.Protocol, inbound.StreamSettings, inbound.Settings)
  344. candidate := composeInboundTag(inbound.Port, inbound.NodeID, bits)
  345. exists, err := s.tagExists(candidate, ignoreId)
  346. if err != nil {
  347. return "", err
  348. }
  349. if !exists {
  350. return candidate, nil
  351. }
  352. for i := 2; i < 100; i++ {
  353. c := fmt.Sprintf("%s-%d", candidate, i)
  354. exists, err = s.tagExists(c, ignoreId)
  355. if err != nil {
  356. return "", err
  357. }
  358. if !exists {
  359. return c, nil
  360. }
  361. }
  362. return "", common.NewError("could not pick a unique inbound tag for port:", inbound.Port)
  363. }
  364. func (s *InboundService) resolveInboundTag(inbound *model.Inbound, ignoreId int) (string, error) {
  365. if inbound.Tag != "" {
  366. taken, err := s.tagExists(inbound.Tag, ignoreId)
  367. if err != nil {
  368. return "", err
  369. }
  370. if !taken {
  371. return inbound.Tag, nil
  372. }
  373. }
  374. return s.generateInboundTag(inbound, ignoreId)
  375. }
  376. func (s *InboundService) tagExists(tag string, ignoreId int) (bool, error) {
  377. db := database.GetDB()
  378. q := db.Model(model.Inbound{}).Where("tag = ?", tag)
  379. if ignoreId > 0 {
  380. q = q.Where("id != ?", ignoreId)
  381. }
  382. var count int64
  383. if err := q.Count(&count).Error; err != nil {
  384. return false, err
  385. }
  386. return count > 0, nil
  387. }