inbound.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "net"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  18. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/clause"
  21. )
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. clientService ClientService
  25. fallbackService FallbackService
  26. }
  27. func normalizeInboundShareAddrStrategy(strategy string) string {
  28. strategy = strings.TrimSpace(strategy)
  29. switch strategy {
  30. case "listen", "custom":
  31. return strategy
  32. default:
  33. return "node"
  34. }
  35. }
  36. func normalizeInboundShareAddress(inbound *model.Inbound) {
  37. if inbound == nil {
  38. return
  39. }
  40. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  41. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  42. inbound.ShareAddr = addr
  43. } else {
  44. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  45. }
  46. }
  47. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  48. if inbound == nil {
  49. return nil
  50. }
  51. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  52. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  53. if err != nil {
  54. return common.NewError("shareAddr must be a host or IP without scheme or port")
  55. }
  56. inbound.ShareAddr = addr
  57. return nil
  58. }
  59. func normalizeInboundShareHost(raw string) (string, error) {
  60. addr := strings.TrimSpace(raw)
  61. if addr == "" {
  62. return "", nil
  63. }
  64. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  65. return "", fmt.Errorf("invalid share address %q", raw)
  66. }
  67. if strings.HasPrefix(addr, "[") {
  68. if !strings.HasSuffix(addr, "]") {
  69. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  70. }
  71. ip := net.ParseIP(addr[1 : len(addr)-1])
  72. if ip == nil || ip.To4() != nil {
  73. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  74. }
  75. return "[" + ip.String() + "]", nil
  76. }
  77. if strings.Contains(addr, ":") {
  78. if _, _, err := net.SplitHostPort(addr); err == nil {
  79. return "", fmt.Errorf("share address must not include port")
  80. }
  81. ip := net.ParseIP(addr)
  82. if ip == nil || ip.To4() != nil {
  83. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  84. }
  85. return "[" + ip.String() + "]", nil
  86. }
  87. host, err := netsafe.NormalizeHost(addr)
  88. if err != nil {
  89. return "", err
  90. }
  91. return host, nil
  92. }
  93. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  94. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  95. return nil
  96. }
  97. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  98. if err := tx.Exec(`UPDATE inbounds SET share_addr_strategy = ` + strategyExpr + ` WHERE share_addr_strategy IS NULL OR share_addr_strategy <> ` + strategyExpr).Error; err != nil {
  99. return err
  100. }
  101. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  102. if hasShareAddr {
  103. if err := tx.Exec(`UPDATE inbounds SET share_addr = TRIM(share_addr) WHERE share_addr IS NOT NULL AND share_addr <> TRIM(share_addr)`).Error; err != nil {
  104. return err
  105. }
  106. }
  107. if !hasShareAddr {
  108. return nil
  109. }
  110. var rows []struct {
  111. Id int
  112. ShareAddrStrategy string
  113. ShareAddr string
  114. }
  115. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  116. return err
  117. }
  118. for _, row := range rows {
  119. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  120. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  121. if addrErr != nil {
  122. strategy = "node"
  123. addr = ""
  124. }
  125. updates := map[string]any{}
  126. if strategy != row.ShareAddrStrategy {
  127. updates["share_addr_strategy"] = strategy
  128. }
  129. if addr != row.ShareAddr {
  130. updates["share_addr"] = addr
  131. }
  132. if len(updates) > 0 {
  133. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. return nil
  139. }
  140. // GetInbounds retrieves all inbounds for a specific user with client stats.
  141. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  142. db := database.GetDB()
  143. var inbounds []*model.Inbound
  144. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  145. if err != nil && err != gorm.ErrRecordNotFound {
  146. return nil, err
  147. }
  148. s.enrichClientStats(db, inbounds)
  149. s.annotateFallbackParents(db, inbounds)
  150. s.annotateLocalOriginGuid(inbounds)
  151. return inbounds, nil
  152. }
  153. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  154. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  155. // already carry the originating node's GUID. Read-time only (not persisted) so
  156. // the per-inbound online view can scope by GUID uniformly across a chain of
  157. // nodes (#4983).
  158. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  159. if len(inbounds) == 0 {
  160. return
  161. }
  162. guid := s.panelGuid()
  163. if guid == "" {
  164. return
  165. }
  166. for _, ib := range inbounds {
  167. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  168. ib.OriginNodeGuid = guid
  169. }
  170. }
  171. }
  172. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  173. // strips every per-client field other than email / enable / comment from
  174. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  175. // inbounds page only needs those three to roll up client counts and
  176. // render badges, so this trims tens of bytes per client (UUID, password,
  177. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  178. // up fast on installs with thousands of clients.
  179. //
  180. // Full client data is still available through GET /panel/api/inbounds/get/:id
  181. // for the edit/info/qr/export/clone flows that need it.
  182. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  183. db := database.GetDB()
  184. var inbounds []*model.Inbound
  185. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  186. if err != nil && err != gorm.ErrRecordNotFound {
  187. return nil, err
  188. }
  189. s.annotateFallbackParents(db, inbounds)
  190. s.annotateLocalOriginGuid(inbounds)
  191. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  192. // so the list's depleted/expiring badges see every client; the UUID/SubId
  193. // enrichment stays skipped. Must run before slimming strips the settings.
  194. s.backfillClientStats(db, inbounds)
  195. // Slim feeds the panel UI only (masters poll the full list), so the badge
  196. // math may see the cross-panel totals a master pushed.
  197. s.overlayInboundsClientStats(db, inbounds)
  198. for _, ib := range inbounds {
  199. ib.Settings = slimSettingsClients(ib.Settings)
  200. }
  201. return inbounds, nil
  202. }
  203. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  204. // keeps only the fields the list view actually reads. Returns the input
  205. // unchanged when the JSON can't be parsed or has no clients array.
  206. func slimSettingsClients(settings string) string {
  207. if settings == "" {
  208. return settings
  209. }
  210. var raw map[string]any
  211. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  212. return settings
  213. }
  214. clients, ok := raw["clients"].([]any)
  215. if !ok || len(clients) == 0 {
  216. return settings
  217. }
  218. slim := make([]any, 0, len(clients))
  219. for _, entry := range clients {
  220. c, ok := entry.(map[string]any)
  221. if !ok {
  222. continue
  223. }
  224. row := make(map[string]any, 3)
  225. if v, ok := c["email"]; ok {
  226. row["email"] = v
  227. }
  228. if v, ok := c["enable"]; ok {
  229. row["enable"] = v
  230. }
  231. if v, ok := c["comment"]; ok && v != "" {
  232. row["comment"] = v
  233. }
  234. slim = append(slim, row)
  235. }
  236. raw["clients"] = slim
  237. out, err := json.Marshal(raw)
  238. if err != nil {
  239. return settings
  240. }
  241. return string(out)
  242. }
  243. // annotateFallbackParents fills FallbackParent on each inbound that is
  244. // the child side of a fallback rule. One DB round-trip serves the full
  245. // list — the frontend needs this to rewrite the child's client-share
  246. // link so it points at the master's reachable endpoint.
  247. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  248. if len(inbounds) == 0 {
  249. return
  250. }
  251. childIds := make([]int, 0, len(inbounds))
  252. for _, ib := range inbounds {
  253. childIds = append(childIds, ib.Id)
  254. }
  255. var rows []model.InboundFallback
  256. if err := db.Where("child_id IN ?", childIds).
  257. Order("sort_order ASC, id ASC").
  258. Find(&rows).Error; err != nil {
  259. return
  260. }
  261. first := make(map[int]model.InboundFallback, len(rows))
  262. for _, r := range rows {
  263. if _, ok := first[r.ChildId]; !ok {
  264. first[r.ChildId] = r
  265. }
  266. }
  267. for _, ib := range inbounds {
  268. if r, ok := first[ib.Id]; ok {
  269. ib.FallbackParent = &model.FallbackParentInfo{
  270. MasterId: r.MasterId,
  271. Path: r.Path,
  272. }
  273. }
  274. }
  275. }
  276. type InboundOption struct {
  277. Id int `json:"id" example:"1"`
  278. Remark string `json:"remark" example:"VLESS-443"`
  279. Tag string `json:"tag" example:"in-443-tcp"`
  280. Protocol string `json:"protocol" example:"vless"`
  281. Port int `json:"port" example:"443"`
  282. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  283. SsMethod string `json:"ssMethod"`
  284. // Hosting node; nil for this panel's own inbounds. Lets the clients
  285. // page map a node filter onto inbound IDs (#4997).
  286. NodeId *int `json:"nodeId,omitempty"`
  287. }
  288. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  289. db := database.GetDB()
  290. var rows []struct {
  291. Id int `gorm:"column:id"`
  292. Remark string `gorm:"column:remark"`
  293. Tag string `gorm:"column:tag"`
  294. Protocol string `gorm:"column:protocol"`
  295. Port int `gorm:"column:port"`
  296. StreamSettings string `gorm:"column:stream_settings"`
  297. Settings string `gorm:"column:settings"`
  298. NodeId *int `gorm:"column:node_id"`
  299. }
  300. err := db.Table("inbounds").
  301. Select("id, remark, tag, protocol, port, stream_settings, settings, node_id").
  302. Where("user_id = ?", userId).
  303. Order("id ASC").
  304. Scan(&rows).Error
  305. if err != nil && err != gorm.ErrRecordNotFound {
  306. return nil, err
  307. }
  308. out := make([]InboundOption, 0, len(rows))
  309. for _, r := range rows {
  310. out = append(out, InboundOption{
  311. Id: r.Id,
  312. Remark: r.Remark,
  313. Tag: r.Tag,
  314. Protocol: r.Protocol,
  315. Port: r.Port,
  316. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  317. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  318. NodeId: r.NodeId,
  319. })
  320. }
  321. return out, nil
  322. }
  323. // GetAllInbounds retrieves all inbounds with client stats.
  324. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  325. db := database.GetDB()
  326. var inbounds []*model.Inbound
  327. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  328. if err != nil && err != gorm.ErrRecordNotFound {
  329. return nil, err
  330. }
  331. s.enrichClientStats(db, inbounds)
  332. return inbounds, nil
  333. }
  334. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  335. db := database.GetDB()
  336. var inbounds []*model.Inbound
  337. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  338. if err != nil && err != gorm.ErrRecordNotFound {
  339. return nil, err
  340. }
  341. return inbounds, nil
  342. }
  343. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  344. settings := map[string][]model.Client{}
  345. json.Unmarshal([]byte(inbound.Settings), &settings)
  346. if settings == nil {
  347. return nil, fmt.Errorf("setting is null")
  348. }
  349. clients := settings["clients"]
  350. if clients == nil {
  351. return nil, nil
  352. }
  353. return clients, nil
  354. }
  355. func (s *InboundService) GetAllEmails() ([]string, error) {
  356. db := database.GetDB()
  357. var emails []string
  358. query := fmt.Sprintf(
  359. "SELECT DISTINCT %s %s",
  360. database.JSONFieldText("client.value", "email"),
  361. database.JSONClientsFromInbound(),
  362. )
  363. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  364. return nil, err
  365. }
  366. return emails, nil
  367. }
  368. // getAllEmailSubIDs returns email→subId. An email seen with two different
  369. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  370. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  371. db := database.GetDB()
  372. var rows []struct {
  373. Email string
  374. SubID string
  375. }
  376. query := fmt.Sprintf(
  377. "SELECT %s AS email, %s AS sub_id %s",
  378. database.JSONFieldText("client.value", "email"),
  379. database.JSONFieldText("client.value", "subId"),
  380. database.JSONClientsFromInbound(),
  381. )
  382. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  383. return nil, err
  384. }
  385. result := make(map[string]string, len(rows))
  386. for _, r := range rows {
  387. email := strings.ToLower(r.Email)
  388. if email == "" {
  389. continue
  390. }
  391. subID := r.SubID
  392. if existing, ok := result[email]; ok {
  393. if existing != subID {
  394. result[email] = ""
  395. }
  396. continue
  397. }
  398. result[email] = subID
  399. }
  400. return result, nil
  401. }
  402. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  403. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  404. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  405. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  406. // mode).
  407. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  408. protocolsWithStream := map[model.Protocol]bool{
  409. model.VMESS: true,
  410. model.VLESS: true,
  411. model.Trojan: true,
  412. model.Shadowsocks: true,
  413. model.Hysteria: true,
  414. model.WireGuard: true,
  415. model.Tunnel: true,
  416. }
  417. if !protocolsWithStream[inbound.Protocol] {
  418. inbound.StreamSettings = ""
  419. }
  420. }
  421. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  422. // always valid and matches the configured domain before the row is persisted.
  423. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  424. if inbound.Protocol != model.MTProto {
  425. return
  426. }
  427. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  428. inbound.Settings = healed
  429. }
  430. }
  431. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  432. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  433. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  434. if inbound == nil || inbound.Protocol != model.MTProto {
  435. return false
  436. }
  437. var parsed struct {
  438. RouteThroughXray bool `json:"routeThroughXray"`
  439. }
  440. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  441. return false
  442. }
  443. return parsed.RouteThroughXray
  444. }
  445. func settingsRouteXrayPort(parsed map[string]any) int {
  446. switch v := parsed["routeXrayPort"].(type) {
  447. case float64:
  448. return int(v)
  449. case int:
  450. return v
  451. case json.Number:
  452. if n, err := v.Int64(); err == nil {
  453. return int(n)
  454. }
  455. }
  456. return 0
  457. }
  458. func parseRouteXrayPort(settings string) int {
  459. if settings == "" {
  460. return 0
  461. }
  462. var parsed map[string]any
  463. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  464. return 0
  465. }
  466. return settingsRouteXrayPort(parsed)
  467. }
  468. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  469. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  470. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  471. // allocated once when routing is first enabled and preserved across edits
  472. // (carried over from oldSettings, which wins over any value the client echoed
  473. // back). When routing is off it — together with the now-inert outbound
  474. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  475. //
  476. // It returns an error when an egress port cannot be allocated or persisted, so
  477. // the caller refuses the save rather than storing a routed-but-portless inbound,
  478. // which would otherwise route no traffic and have its mtg metrics skipped (see
  479. // mtproto_job) — silently losing its accounting.
  480. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  481. if inbound.Protocol != model.MTProto {
  482. return nil
  483. }
  484. var parsed map[string]any
  485. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  486. return nil
  487. }
  488. routed, _ := parsed["routeThroughXray"].(bool)
  489. if !routed {
  490. _, hadPort := parsed["routeXrayPort"]
  491. _, hadTag := parsed["outboundTag"]
  492. if !hadPort && !hadTag {
  493. return nil
  494. }
  495. delete(parsed, "routeXrayPort")
  496. delete(parsed, "outboundTag")
  497. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  498. inbound.Settings = string(bs)
  499. } else {
  500. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  501. }
  502. return nil
  503. }
  504. // Prefer the already-stored port (carried across edits), then any value the
  505. // client sent, then allocate a fresh one.
  506. port := parseRouteXrayPort(oldSettings)
  507. if port <= 0 {
  508. port = settingsRouteXrayPort(parsed)
  509. }
  510. if port <= 0 {
  511. allocated, err := mtproto.FreeLocalPort()
  512. if err != nil {
  513. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  514. }
  515. port = allocated
  516. }
  517. if settingsRouteXrayPort(parsed) == port {
  518. return nil
  519. }
  520. parsed["routeXrayPort"] = port
  521. bs, err := json.MarshalIndent(parsed, "", " ")
  522. if err != nil {
  523. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  524. }
  525. inbound.Settings = string(bs)
  526. return nil
  527. }
  528. // AddInbound creates a new inbound configuration.
  529. // It validates port uniqueness, client email uniqueness, and required fields,
  530. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  531. // Returns the created inbound, whether Xray needs restart, and any error.
  532. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  533. // Normalize streamSettings based on protocol
  534. s.normalizeStreamSettings(inbound)
  535. s.normalizeMtprotoSecret(inbound)
  536. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  537. return inbound, false, err
  538. }
  539. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  540. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  541. return inbound, false, err
  542. }
  543. conflict, err := s.checkPortConflict(inbound, 0)
  544. if err != nil {
  545. return inbound, false, err
  546. }
  547. if conflict != nil {
  548. return inbound, false, common.NewError(conflict.String())
  549. }
  550. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  551. if err != nil {
  552. return inbound, false, err
  553. }
  554. clients, err := s.GetClients(inbound)
  555. if err != nil {
  556. return inbound, false, err
  557. }
  558. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  559. if err != nil {
  560. return inbound, false, err
  561. }
  562. if existEmail != "" {
  563. return inbound, false, common.NewError("Duplicate email:", existEmail)
  564. }
  565. // Ensure created_at and updated_at on clients in settings
  566. if len(clients) > 0 {
  567. var settings map[string]any
  568. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  569. now := time.Now().Unix() * 1000
  570. updatedClients := make([]model.Client, 0, len(clients))
  571. for _, c := range clients {
  572. if c.CreatedAt == 0 {
  573. c.CreatedAt = now
  574. }
  575. c.UpdatedAt = now
  576. updatedClients = append(updatedClients, c)
  577. }
  578. settings["clients"] = updatedClients
  579. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  580. inbound.Settings = string(bs)
  581. } else {
  582. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  583. }
  584. } else if err2 != nil {
  585. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  586. }
  587. }
  588. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  589. // the inbound method (e.g. an API caller supplied a wrong-size key).
  590. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  591. inbound.Settings = normalized
  592. }
  593. // Secure client ID
  594. for _, client := range clients {
  595. switch inbound.Protocol {
  596. case "trojan":
  597. if client.Password == "" {
  598. return inbound, false, common.NewError("empty client ID")
  599. }
  600. case "shadowsocks":
  601. if client.Email == "" {
  602. return inbound, false, common.NewError("empty client ID")
  603. }
  604. case "hysteria":
  605. if client.Auth == "" {
  606. return inbound, false, common.NewError("empty client ID")
  607. }
  608. default:
  609. if client.ID == "" {
  610. return inbound, false, common.NewError("empty client ID")
  611. }
  612. }
  613. }
  614. db := database.GetDB()
  615. tx := db.Begin()
  616. markDirty := false
  617. defer func() {
  618. if err != nil {
  619. tx.Rollback()
  620. return
  621. }
  622. tx.Commit()
  623. if markDirty && inbound.NodeID != nil {
  624. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  625. logger.Warning("mark node dirty failed:", dErr)
  626. }
  627. }
  628. }()
  629. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  630. // those rows with an ON CONFLICT target on the primary key only, which
  631. // collides with the globally-unique client_traffics.email when an imported
  632. // inbound carries clients that another inbound already created (e.g.
  633. // importing two inbounds that share the same clients). We insert the stats
  634. // ourselves below with the same email-conflict guard AddClientStat uses.
  635. err = tx.Omit("ClientStats").Save(inbound).Error
  636. if err != nil {
  637. return inbound, false, err
  638. }
  639. // Imported stats first, so their traffic counters survive; emails that
  640. // already own a (shared) row are skipped instead of tripping the unique
  641. // constraint.
  642. for i := range inbound.ClientStats {
  643. if inbound.ClientStats[i].Email == "" {
  644. continue
  645. }
  646. inbound.ClientStats[i].Id = 0
  647. inbound.ClientStats[i].InboundId = inbound.Id
  648. if err = tx.Clauses(clause.OnConflict{
  649. Columns: []clause.Column{{Name: "email"}},
  650. DoNothing: true,
  651. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  652. return inbound, false, err
  653. }
  654. }
  655. // Then make sure every client has a stats row. AddClientStat is a no-op
  656. // where one exists (including the rows just inserted), and fills the gap
  657. // for clients an import payload didn't carry stats for.
  658. for _, client := range clients {
  659. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  660. return inbound, false, err
  661. }
  662. }
  663. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  664. return inbound, false, err
  665. }
  666. // Legacy import: an inbound exported from a build that predated the hosts
  667. // table carries its external proxies inline in streamSettings.externalProxy.
  668. // The startup migration that converts those to host rows runs once and is
  669. // gated off afterwards, so it never sees a freshly imported inbound —
  670. // reproduce it here. No-op for inbounds without externalProxy (everything the
  671. // current UI builds), so this only fires on such imports.
  672. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  673. return inbound, false, err
  674. }
  675. // Before the deferred commit, so a node in "selected" sync mode cannot
  676. // sweep the new central row in the gap before its tag is allowed.
  677. if inbound.NodeID != nil {
  678. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  679. logger.Warning("allow inbound tag on node failed:", aErr)
  680. }
  681. }
  682. needRestart := false
  683. if inbound.Enable {
  684. rt, push, dirty, perr := s.nodePushPlan(inbound)
  685. if perr != nil {
  686. err = perr
  687. return inbound, false, err
  688. }
  689. if dirty {
  690. markDirty = true
  691. }
  692. if push {
  693. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  694. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  695. } else {
  696. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  697. if inbound.NodeID != nil {
  698. markDirty = true
  699. } else {
  700. needRestart = true
  701. }
  702. }
  703. }
  704. }
  705. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  706. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  707. // in the generated config, so force a regen to wire it in.
  708. if mtprotoRoutesThroughXray(inbound) {
  709. needRestart = true
  710. }
  711. return inbound, needRestart, err
  712. }
  713. func (s *InboundService) DelInbound(id int) (bool, error) {
  714. db := database.GetDB()
  715. needRestart := false
  716. markDirty := false
  717. var ib model.Inbound
  718. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  719. if loadErr == nil {
  720. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  721. if shouldPushToRuntime {
  722. rt, push, dirty, perr := s.nodePushPlan(&ib)
  723. if perr != nil {
  724. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  725. markDirty = true
  726. } else if push {
  727. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  728. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  729. } else {
  730. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  731. if ib.NodeID == nil {
  732. needRestart = true
  733. } else {
  734. markDirty = true
  735. }
  736. }
  737. } else if ib.NodeID == nil {
  738. needRestart = true
  739. } else if dirty {
  740. markDirty = true
  741. }
  742. } else {
  743. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  744. }
  745. } else {
  746. logger.Debug("DelInbound: inbound not found, id:", id)
  747. }
  748. if err := s.clientService.DetachInbound(db, id); err != nil {
  749. return false, err
  750. }
  751. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  752. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  753. if loadErr == nil && ib.Tag != "" {
  754. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  755. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  756. } else if routingChanged {
  757. needRestart = true
  758. }
  759. }
  760. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  761. return needRestart, err
  762. }
  763. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  764. if err := db.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  765. return needRestart, err
  766. }
  767. if markDirty && ib.NodeID != nil {
  768. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  769. logger.Warning("mark node dirty failed:", dErr)
  770. }
  771. }
  772. if !database.IsPostgres() {
  773. var count int64
  774. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  775. return needRestart, err
  776. }
  777. if count == 0 {
  778. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  779. return needRestart, err
  780. }
  781. }
  782. }
  783. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  784. if mtprotoRoutesThroughXray(&ib) {
  785. needRestart = true
  786. }
  787. return needRestart, nil
  788. }
  789. type BulkDelInboundResult struct {
  790. Deleted int `json:"deleted"`
  791. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  792. }
  793. type BulkDelInboundReport struct {
  794. Id int `json:"id"`
  795. Reason string `json:"reason"`
  796. }
  797. // DelInbounds removes every inbound in the list, reusing the single-delete
  798. // path per id. Failures are recorded in Skipped and processing continues for
  799. // the rest; the aggregated needRestart is returned so the caller restarts
  800. // xray at most once.
  801. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  802. result := BulkDelInboundResult{}
  803. needRestart := false
  804. for _, id := range ids {
  805. r, err := s.DelInbound(id)
  806. if err != nil {
  807. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  808. continue
  809. }
  810. result.Deleted++
  811. if r {
  812. needRestart = true
  813. }
  814. }
  815. return result, needRestart, nil
  816. }
  817. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  818. db := database.GetDB()
  819. inbound := &model.Inbound{}
  820. err := db.Model(model.Inbound{}).First(inbound, id).Error
  821. if err != nil {
  822. return nil, err
  823. }
  824. return inbound, nil
  825. }
  826. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  827. db := database.GetDB()
  828. inbound := &model.Inbound{}
  829. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  830. if err != nil {
  831. return nil, err
  832. }
  833. s.enrichClientStats(db, []*model.Inbound{inbound})
  834. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  835. return inbound, nil
  836. }
  837. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  838. inbound, err := s.GetInbound(id)
  839. if err != nil {
  840. return false, err
  841. }
  842. if inbound.Enable == enable {
  843. return false, nil
  844. }
  845. db := database.GetDB()
  846. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  847. Update("enable", enable).Error; err != nil {
  848. return false, err
  849. }
  850. inbound.Enable = enable
  851. needRestart := false
  852. rt, push, dirty, perr := s.nodePushPlan(inbound)
  853. if perr != nil {
  854. return false, perr
  855. }
  856. // Remote nodes interpret DelInbound as a real row delete (it hits
  857. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  858. // switch on a remote inbound used to wipe the row entirely (#4402).
  859. // PATCH the remote row via UpdateInbound instead — preserves the
  860. // settings/client history and just flips the enable flag.
  861. if inbound.NodeID != nil {
  862. if push {
  863. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  864. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  865. dirty = true
  866. }
  867. }
  868. if dirty {
  869. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  870. logger.Warning("mark node dirty failed:", dErr)
  871. }
  872. }
  873. return false, nil
  874. }
  875. if !push {
  876. return true, nil
  877. }
  878. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  879. !strings.Contains(err.Error(), "not found") {
  880. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  881. needRestart = true
  882. }
  883. if !enable {
  884. return needRestart, nil
  885. }
  886. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  887. if err != nil {
  888. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  889. return true, nil
  890. }
  891. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  892. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  893. needRestart = true
  894. }
  895. return needRestart, nil
  896. }
  897. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  898. // Normalize streamSettings based on protocol
  899. s.normalizeStreamSettings(inbound)
  900. s.normalizeMtprotoSecret(inbound)
  901. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  902. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  903. if err != nil {
  904. return inbound, false, err
  905. }
  906. if conflict != nil {
  907. return inbound, false, common.NewError(conflict.String())
  908. }
  909. oldInbound, err := s.GetInbound(inbound.Id)
  910. if err != nil {
  911. return inbound, false, err
  912. }
  913. inbound.NodeID = oldInbound.NodeID
  914. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  915. // with the new settings further down, then ensure a routed inbound keeps a
  916. // stable egress port (reusing the one already stored).
  917. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  918. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  919. return inbound, false, err
  920. }
  921. tag := oldInbound.Tag
  922. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  923. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  924. needRestart := false
  925. markDirty := false
  926. // Persist the client-stat sync, settings munging, runtime push and inbound
  927. // save as one transaction routed through the serial traffic writer, so it
  928. // never runs concurrently with the @every 5s traffic poll. Both touch
  929. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  930. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  931. //
  932. // The runtime push stays inside the transaction here (unlike the client-edit
  933. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  934. // node before the central row is committed, or a "selected"-mode node would
  935. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  936. // holding the writer across the node call is an acceptable trade.
  937. txErr := runSerializedTx(func(tx *gorm.DB) error {
  938. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  939. return err
  940. }
  941. // Ensure created_at and updated_at exist in inbound.Settings clients
  942. {
  943. var oldSettings map[string]any
  944. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  945. emailToCreated := map[string]int64{}
  946. emailToUpdated := map[string]int64{}
  947. if oldSettings != nil {
  948. if oc, ok := oldSettings["clients"].([]any); ok {
  949. for _, it := range oc {
  950. if m, ok2 := it.(map[string]any); ok2 {
  951. if email, ok3 := m["email"].(string); ok3 {
  952. switch v := m["created_at"].(type) {
  953. case float64:
  954. emailToCreated[email] = int64(v)
  955. case int64:
  956. emailToCreated[email] = v
  957. }
  958. switch v := m["updated_at"].(type) {
  959. case float64:
  960. emailToUpdated[email] = int64(v)
  961. case int64:
  962. emailToUpdated[email] = v
  963. }
  964. }
  965. }
  966. }
  967. }
  968. }
  969. var newSettings map[string]any
  970. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  971. now := time.Now().Unix() * 1000
  972. if nSlice, ok := newSettings["clients"].([]any); ok {
  973. for i := range nSlice {
  974. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  975. email, _ := m["email"].(string)
  976. if _, ok3 := m["created_at"]; !ok3 {
  977. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  978. m["created_at"] = v
  979. } else {
  980. m["created_at"] = now
  981. }
  982. }
  983. // Preserve client's updated_at if present; do not bump on parent inbound update
  984. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  985. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  986. m["updated_at"] = v
  987. }
  988. }
  989. nSlice[i] = m
  990. }
  991. }
  992. newSettings["clients"] = nSlice
  993. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  994. inbound.Settings = string(bs)
  995. }
  996. }
  997. }
  998. }
  999. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1000. // keep their old length and would be rejected by xray. Regenerate mismatched
  1001. // client keys so the inbound stays connectable.
  1002. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1003. inbound.Settings = normalized
  1004. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1005. }
  1006. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1007. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1008. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1009. // but was stripped while the inbound was ineligible.
  1010. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1011. inbound.Settings = restored
  1012. }
  1013. oldInbound.Total = inbound.Total
  1014. oldInbound.Remark = inbound.Remark
  1015. oldInbound.SubSortIndex = inbound.SubSortIndex
  1016. oldInbound.Enable = inbound.Enable
  1017. oldInbound.ExpiryTime = inbound.ExpiryTime
  1018. oldInbound.TrafficReset = inbound.TrafficReset
  1019. oldInbound.Listen = inbound.Listen
  1020. oldInbound.Port = inbound.Port
  1021. oldInbound.Protocol = inbound.Protocol
  1022. oldInbound.Settings = inbound.Settings
  1023. oldInbound.StreamSettings = inbound.StreamSettings
  1024. oldInbound.Sniffing = inbound.Sniffing
  1025. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1026. normalizeInboundShareAddress(oldInbound)
  1027. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1028. inbound.ShareAddr = oldInbound.ShareAddr
  1029. } else {
  1030. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1031. return err
  1032. }
  1033. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1034. oldInbound.ShareAddr = inbound.ShareAddr
  1035. }
  1036. if oldTagWasAuto && inbound.Tag == tag {
  1037. inbound.Tag = ""
  1038. }
  1039. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1040. if err != nil {
  1041. return err
  1042. }
  1043. oldInbound.Tag = resolvedTag
  1044. inbound.Tag = oldInbound.Tag
  1045. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  1046. if perr != nil {
  1047. return perr
  1048. }
  1049. if dirty {
  1050. markDirty = true
  1051. }
  1052. if oldInbound.NodeID == nil {
  1053. if !push {
  1054. needRestart = true
  1055. } else {
  1056. oldSnapshot := *oldInbound
  1057. oldSnapshot.Tag = tag
  1058. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1059. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1060. }
  1061. if inbound.Enable {
  1062. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1063. if err2 != nil {
  1064. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1065. needRestart = true
  1066. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1067. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1068. } else {
  1069. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1070. needRestart = true
  1071. }
  1072. }
  1073. }
  1074. } else if push {
  1075. oldSnapshot := *oldInbound
  1076. oldSnapshot.Tag = tag
  1077. if !inbound.Enable {
  1078. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1079. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1080. markDirty = true
  1081. }
  1082. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1083. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1084. markDirty = true
  1085. }
  1086. }
  1087. // A rename must allow the new tag before the inbound row is committed, or a
  1088. // node in "selected" sync mode would sweep the renamed central row on the
  1089. // next pull.
  1090. if oldInbound.NodeID != nil {
  1091. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1092. logger.Warning("allow inbound tag on node failed:", aErr)
  1093. }
  1094. }
  1095. if err := tx.Save(oldInbound).Error; err != nil {
  1096. return err
  1097. }
  1098. newClients, gcErr := s.GetClients(oldInbound)
  1099. if gcErr != nil {
  1100. return gcErr
  1101. }
  1102. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1103. return err
  1104. }
  1105. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1106. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1107. // settings.
  1108. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1109. needRestart = true
  1110. }
  1111. return nil
  1112. })
  1113. if txErr != nil {
  1114. return inbound, false, txErr
  1115. }
  1116. // After the rename is committed, point any routing rules / loopback outbounds
  1117. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1118. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1119. // can't roll back the inbound edit.
  1120. if tag != oldInbound.Tag {
  1121. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1122. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1123. } else if routingChanged {
  1124. needRestart = true
  1125. }
  1126. }
  1127. if markDirty && oldInbound.NodeID != nil {
  1128. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  1129. logger.Warning("mark node dirty failed:", dErr)
  1130. }
  1131. }
  1132. return inbound, needRestart, nil
  1133. }
  1134. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1135. if inbound == nil {
  1136. return nil, fmt.Errorf("inbound is nil")
  1137. }
  1138. runtimeInbound := *inbound
  1139. settings := map[string]any{}
  1140. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1141. return nil, err
  1142. }
  1143. clients, ok := settings["clients"].([]any)
  1144. if !ok {
  1145. return &runtimeInbound, nil
  1146. }
  1147. var clientStats []xray.ClientTraffic
  1148. err := tx.Model(xray.ClientTraffic{}).
  1149. Where("inbound_id = ?", inbound.Id).
  1150. Select("email", "enable").
  1151. Find(&clientStats).Error
  1152. if err != nil {
  1153. return nil, err
  1154. }
  1155. enableMap := make(map[string]bool, len(clientStats))
  1156. for _, clientTraffic := range clientStats {
  1157. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1158. }
  1159. finalClients := make([]any, 0, len(clients))
  1160. for _, client := range clients {
  1161. c, ok := client.(map[string]any)
  1162. if !ok {
  1163. continue
  1164. }
  1165. email, _ := c["email"].(string)
  1166. if enable, exists := enableMap[email]; exists && !enable {
  1167. continue
  1168. }
  1169. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1170. continue
  1171. }
  1172. finalClients = append(finalClients, c)
  1173. }
  1174. settings["clients"] = finalClients
  1175. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. runtimeInbound.Settings = string(modifiedSettings)
  1180. return &runtimeInbound, nil
  1181. }
  1182. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1183. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1184. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1185. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1186. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1187. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1188. oldClients, err := s.GetClients(oldInbound)
  1189. if err != nil {
  1190. return err
  1191. }
  1192. newClients, err := s.GetClients(newInbound)
  1193. if err != nil {
  1194. return err
  1195. }
  1196. // Email is the unique key for ClientTraffic rows. Clients without an
  1197. // email have no stats row to sync — skip them on both sides instead of
  1198. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1199. oldEmails := make(map[string]struct{}, len(oldClients))
  1200. for i := range oldClients {
  1201. if oldClients[i].Email == "" {
  1202. continue
  1203. }
  1204. oldEmails[oldClients[i].Email] = struct{}{}
  1205. }
  1206. newEmails := make(map[string]struct{}, len(newClients))
  1207. for i := range newClients {
  1208. if newClients[i].Email == "" {
  1209. continue
  1210. }
  1211. newEmails[newClients[i].Email] = struct{}{}
  1212. }
  1213. // Drop stats rows for removed emails — but not when a sibling inbound
  1214. // still references the email, since the row is the shared accumulator.
  1215. for i := range oldClients {
  1216. email := oldClients[i].Email
  1217. if email == "" {
  1218. continue
  1219. }
  1220. if _, kept := newEmails[email]; kept {
  1221. continue
  1222. }
  1223. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1224. if err != nil {
  1225. return err
  1226. }
  1227. if stillUsed {
  1228. continue
  1229. }
  1230. if err := s.DelClientStat(tx, email); err != nil {
  1231. return err
  1232. }
  1233. // Keep inbound_client_ips in sync when the inbound edit drops an
  1234. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1235. if err := s.DelClientIPs(tx, email); err != nil {
  1236. return err
  1237. }
  1238. }
  1239. for i := range newClients {
  1240. email := newClients[i].Email
  1241. if email == "" {
  1242. continue
  1243. }
  1244. if _, existed := oldEmails[email]; existed {
  1245. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1246. return err
  1247. }
  1248. continue
  1249. }
  1250. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1251. return err
  1252. }
  1253. }
  1254. return nil
  1255. }
  1256. func (s *InboundService) GetInboundTags() (string, error) {
  1257. db := database.GetDB()
  1258. var inboundTags []string
  1259. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1260. if err != nil && err != gorm.ErrRecordNotFound {
  1261. return "", err
  1262. }
  1263. tags, _ := json.Marshal(inboundTags)
  1264. return string(tags), nil
  1265. }
  1266. func (s *InboundService) GetClientReverseTags() (string, error) {
  1267. db := database.GetDB()
  1268. var inbounds []model.Inbound
  1269. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1270. if err != nil && err != gorm.ErrRecordNotFound {
  1271. return "[]", err
  1272. }
  1273. tagSet := make(map[string]struct{})
  1274. for _, inbound := range inbounds {
  1275. var settings map[string]any
  1276. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1277. continue
  1278. }
  1279. clients, ok := settings["clients"].([]any)
  1280. if !ok {
  1281. continue
  1282. }
  1283. for _, client := range clients {
  1284. clientMap, ok := client.(map[string]any)
  1285. if !ok {
  1286. continue
  1287. }
  1288. reverse, ok := clientMap["reverse"].(map[string]any)
  1289. if !ok {
  1290. continue
  1291. }
  1292. tag, _ := reverse["tag"].(string)
  1293. tag = strings.TrimSpace(tag)
  1294. if tag != "" {
  1295. tagSet[tag] = struct{}{}
  1296. }
  1297. }
  1298. }
  1299. rawTags := make([]string, 0, len(tagSet))
  1300. for tag := range tagSet {
  1301. rawTags = append(rawTags, tag)
  1302. }
  1303. sort.Strings(rawTags)
  1304. result, _ := json.Marshal(rawTags)
  1305. return string(result), nil
  1306. }
  1307. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1308. db := database.GetDB()
  1309. var inbounds []*model.Inbound
  1310. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1311. if err != nil && err != gorm.ErrRecordNotFound {
  1312. return nil, err
  1313. }
  1314. return inbounds, nil
  1315. }