inbound.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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. // Before the deferred commit, so a node in "selected" sync mode cannot
  667. // sweep the new central row in the gap before its tag is allowed.
  668. if inbound.NodeID != nil {
  669. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  670. logger.Warning("allow inbound tag on node failed:", aErr)
  671. }
  672. }
  673. needRestart := false
  674. if inbound.Enable {
  675. rt, push, dirty, perr := s.nodePushPlan(inbound)
  676. if perr != nil {
  677. err = perr
  678. return inbound, false, err
  679. }
  680. if dirty {
  681. markDirty = true
  682. }
  683. if push {
  684. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  685. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  686. } else {
  687. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  688. if inbound.NodeID != nil {
  689. markDirty = true
  690. } else {
  691. needRestart = true
  692. }
  693. }
  694. }
  695. }
  696. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  697. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  698. // in the generated config, so force a regen to wire it in.
  699. if mtprotoRoutesThroughXray(inbound) {
  700. needRestart = true
  701. }
  702. return inbound, needRestart, err
  703. }
  704. func (s *InboundService) DelInbound(id int) (bool, error) {
  705. db := database.GetDB()
  706. needRestart := false
  707. markDirty := false
  708. var ib model.Inbound
  709. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  710. if loadErr == nil {
  711. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  712. if shouldPushToRuntime {
  713. rt, push, dirty, perr := s.nodePushPlan(&ib)
  714. if perr != nil {
  715. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  716. markDirty = true
  717. } else if push {
  718. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  719. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  720. } else {
  721. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  722. if ib.NodeID == nil {
  723. needRestart = true
  724. } else {
  725. markDirty = true
  726. }
  727. }
  728. } else if ib.NodeID == nil {
  729. needRestart = true
  730. } else if dirty {
  731. markDirty = true
  732. }
  733. } else {
  734. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  735. }
  736. } else {
  737. logger.Debug("DelInbound: inbound not found, id:", id)
  738. }
  739. if err := s.clientService.DetachInbound(db, id); err != nil {
  740. return false, err
  741. }
  742. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  743. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  744. if loadErr == nil && ib.Tag != "" {
  745. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  746. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  747. } else if routingChanged {
  748. needRestart = true
  749. }
  750. }
  751. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  752. return needRestart, err
  753. }
  754. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  755. if err := db.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  756. return needRestart, err
  757. }
  758. if markDirty && ib.NodeID != nil {
  759. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  760. logger.Warning("mark node dirty failed:", dErr)
  761. }
  762. }
  763. if !database.IsPostgres() {
  764. var count int64
  765. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  766. return needRestart, err
  767. }
  768. if count == 0 {
  769. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  770. return needRestart, err
  771. }
  772. }
  773. }
  774. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  775. if mtprotoRoutesThroughXray(&ib) {
  776. needRestart = true
  777. }
  778. return needRestart, nil
  779. }
  780. type BulkDelInboundResult struct {
  781. Deleted int `json:"deleted"`
  782. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  783. }
  784. type BulkDelInboundReport struct {
  785. Id int `json:"id"`
  786. Reason string `json:"reason"`
  787. }
  788. // DelInbounds removes every inbound in the list, reusing the single-delete
  789. // path per id. Failures are recorded in Skipped and processing continues for
  790. // the rest; the aggregated needRestart is returned so the caller restarts
  791. // xray at most once.
  792. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  793. result := BulkDelInboundResult{}
  794. needRestart := false
  795. for _, id := range ids {
  796. r, err := s.DelInbound(id)
  797. if err != nil {
  798. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  799. continue
  800. }
  801. result.Deleted++
  802. if r {
  803. needRestart = true
  804. }
  805. }
  806. return result, needRestart, nil
  807. }
  808. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  809. db := database.GetDB()
  810. inbound := &model.Inbound{}
  811. err := db.Model(model.Inbound{}).First(inbound, id).Error
  812. if err != nil {
  813. return nil, err
  814. }
  815. return inbound, nil
  816. }
  817. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  818. db := database.GetDB()
  819. inbound := &model.Inbound{}
  820. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  821. if err != nil {
  822. return nil, err
  823. }
  824. s.enrichClientStats(db, []*model.Inbound{inbound})
  825. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  826. return inbound, nil
  827. }
  828. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  829. inbound, err := s.GetInbound(id)
  830. if err != nil {
  831. return false, err
  832. }
  833. if inbound.Enable == enable {
  834. return false, nil
  835. }
  836. db := database.GetDB()
  837. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  838. Update("enable", enable).Error; err != nil {
  839. return false, err
  840. }
  841. inbound.Enable = enable
  842. needRestart := false
  843. rt, push, dirty, perr := s.nodePushPlan(inbound)
  844. if perr != nil {
  845. return false, perr
  846. }
  847. // Remote nodes interpret DelInbound as a real row delete (it hits
  848. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  849. // switch on a remote inbound used to wipe the row entirely (#4402).
  850. // PATCH the remote row via UpdateInbound instead — preserves the
  851. // settings/client history and just flips the enable flag.
  852. if inbound.NodeID != nil {
  853. if push {
  854. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  855. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  856. dirty = true
  857. }
  858. }
  859. if dirty {
  860. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  861. logger.Warning("mark node dirty failed:", dErr)
  862. }
  863. }
  864. return false, nil
  865. }
  866. if !push {
  867. return true, nil
  868. }
  869. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  870. !strings.Contains(err.Error(), "not found") {
  871. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  872. needRestart = true
  873. }
  874. if !enable {
  875. return needRestart, nil
  876. }
  877. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  878. if err != nil {
  879. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  880. return true, nil
  881. }
  882. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  883. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  884. needRestart = true
  885. }
  886. return needRestart, nil
  887. }
  888. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  889. // Normalize streamSettings based on protocol
  890. s.normalizeStreamSettings(inbound)
  891. s.normalizeMtprotoSecret(inbound)
  892. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  893. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  894. if err != nil {
  895. return inbound, false, err
  896. }
  897. if conflict != nil {
  898. return inbound, false, common.NewError(conflict.String())
  899. }
  900. oldInbound, err := s.GetInbound(inbound.Id)
  901. if err != nil {
  902. return inbound, false, err
  903. }
  904. inbound.NodeID = oldInbound.NodeID
  905. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  906. // with the new settings further down, then ensure a routed inbound keeps a
  907. // stable egress port (reusing the one already stored).
  908. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  909. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  910. return inbound, false, err
  911. }
  912. tag := oldInbound.Tag
  913. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  914. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  915. needRestart := false
  916. markDirty := false
  917. // Persist the client-stat sync, settings munging, runtime push and inbound
  918. // save as one transaction routed through the serial traffic writer, so it
  919. // never runs concurrently with the @every 5s traffic poll. Both touch
  920. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  921. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  922. //
  923. // The runtime push stays inside the transaction here (unlike the client-edit
  924. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  925. // node before the central row is committed, or a "selected"-mode node would
  926. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  927. // holding the writer across the node call is an acceptable trade.
  928. txErr := runSerializedTx(func(tx *gorm.DB) error {
  929. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  930. return err
  931. }
  932. // Ensure created_at and updated_at exist in inbound.Settings clients
  933. {
  934. var oldSettings map[string]any
  935. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  936. emailToCreated := map[string]int64{}
  937. emailToUpdated := map[string]int64{}
  938. if oldSettings != nil {
  939. if oc, ok := oldSettings["clients"].([]any); ok {
  940. for _, it := range oc {
  941. if m, ok2 := it.(map[string]any); ok2 {
  942. if email, ok3 := m["email"].(string); ok3 {
  943. switch v := m["created_at"].(type) {
  944. case float64:
  945. emailToCreated[email] = int64(v)
  946. case int64:
  947. emailToCreated[email] = v
  948. }
  949. switch v := m["updated_at"].(type) {
  950. case float64:
  951. emailToUpdated[email] = int64(v)
  952. case int64:
  953. emailToUpdated[email] = v
  954. }
  955. }
  956. }
  957. }
  958. }
  959. }
  960. var newSettings map[string]any
  961. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  962. now := time.Now().Unix() * 1000
  963. if nSlice, ok := newSettings["clients"].([]any); ok {
  964. for i := range nSlice {
  965. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  966. email, _ := m["email"].(string)
  967. if _, ok3 := m["created_at"]; !ok3 {
  968. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  969. m["created_at"] = v
  970. } else {
  971. m["created_at"] = now
  972. }
  973. }
  974. // Preserve client's updated_at if present; do not bump on parent inbound update
  975. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  976. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  977. m["updated_at"] = v
  978. }
  979. }
  980. nSlice[i] = m
  981. }
  982. }
  983. newSettings["clients"] = nSlice
  984. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  985. inbound.Settings = string(bs)
  986. }
  987. }
  988. }
  989. }
  990. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  991. // keep their old length and would be rejected by xray. Regenerate mismatched
  992. // client keys so the inbound stays connectable.
  993. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  994. inbound.Settings = normalized
  995. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  996. }
  997. oldInbound.Total = inbound.Total
  998. oldInbound.Remark = inbound.Remark
  999. oldInbound.SubSortIndex = inbound.SubSortIndex
  1000. oldInbound.Enable = inbound.Enable
  1001. oldInbound.ExpiryTime = inbound.ExpiryTime
  1002. oldInbound.TrafficReset = inbound.TrafficReset
  1003. oldInbound.Listen = inbound.Listen
  1004. oldInbound.Port = inbound.Port
  1005. oldInbound.Protocol = inbound.Protocol
  1006. oldInbound.Settings = inbound.Settings
  1007. oldInbound.StreamSettings = inbound.StreamSettings
  1008. oldInbound.Sniffing = inbound.Sniffing
  1009. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1010. normalizeInboundShareAddress(oldInbound)
  1011. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1012. inbound.ShareAddr = oldInbound.ShareAddr
  1013. } else {
  1014. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1015. return err
  1016. }
  1017. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1018. oldInbound.ShareAddr = inbound.ShareAddr
  1019. }
  1020. if oldTagWasAuto && inbound.Tag == tag {
  1021. inbound.Tag = ""
  1022. }
  1023. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1024. if err != nil {
  1025. return err
  1026. }
  1027. oldInbound.Tag = resolvedTag
  1028. inbound.Tag = oldInbound.Tag
  1029. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  1030. if perr != nil {
  1031. return perr
  1032. }
  1033. if dirty {
  1034. markDirty = true
  1035. }
  1036. if oldInbound.NodeID == nil {
  1037. if !push {
  1038. needRestart = true
  1039. } else {
  1040. oldSnapshot := *oldInbound
  1041. oldSnapshot.Tag = tag
  1042. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1043. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1044. }
  1045. if inbound.Enable {
  1046. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1047. if err2 != nil {
  1048. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1049. needRestart = true
  1050. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1051. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1052. } else {
  1053. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1054. needRestart = true
  1055. }
  1056. }
  1057. }
  1058. } else if push {
  1059. oldSnapshot := *oldInbound
  1060. oldSnapshot.Tag = tag
  1061. if !inbound.Enable {
  1062. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1063. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1064. markDirty = true
  1065. }
  1066. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1067. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1068. markDirty = true
  1069. }
  1070. }
  1071. // A rename must allow the new tag before the inbound row is committed, or a
  1072. // node in "selected" sync mode would sweep the renamed central row on the
  1073. // next pull.
  1074. if oldInbound.NodeID != nil {
  1075. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1076. logger.Warning("allow inbound tag on node failed:", aErr)
  1077. }
  1078. }
  1079. if err := tx.Save(oldInbound).Error; err != nil {
  1080. return err
  1081. }
  1082. newClients, gcErr := s.GetClients(oldInbound)
  1083. if gcErr != nil {
  1084. return gcErr
  1085. }
  1086. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1087. return err
  1088. }
  1089. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1090. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1091. // settings.
  1092. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1093. needRestart = true
  1094. }
  1095. return nil
  1096. })
  1097. if txErr != nil {
  1098. return inbound, false, txErr
  1099. }
  1100. // After the rename is committed, point any routing rules / loopback outbounds
  1101. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1102. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1103. // can't roll back the inbound edit.
  1104. if tag != oldInbound.Tag {
  1105. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1106. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1107. } else if routingChanged {
  1108. needRestart = true
  1109. }
  1110. }
  1111. if markDirty && oldInbound.NodeID != nil {
  1112. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  1113. logger.Warning("mark node dirty failed:", dErr)
  1114. }
  1115. }
  1116. return inbound, needRestart, nil
  1117. }
  1118. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1119. if inbound == nil {
  1120. return nil, fmt.Errorf("inbound is nil")
  1121. }
  1122. runtimeInbound := *inbound
  1123. settings := map[string]any{}
  1124. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1125. return nil, err
  1126. }
  1127. clients, ok := settings["clients"].([]any)
  1128. if !ok {
  1129. return &runtimeInbound, nil
  1130. }
  1131. var clientStats []xray.ClientTraffic
  1132. err := tx.Model(xray.ClientTraffic{}).
  1133. Where("inbound_id = ?", inbound.Id).
  1134. Select("email", "enable").
  1135. Find(&clientStats).Error
  1136. if err != nil {
  1137. return nil, err
  1138. }
  1139. enableMap := make(map[string]bool, len(clientStats))
  1140. for _, clientTraffic := range clientStats {
  1141. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1142. }
  1143. finalClients := make([]any, 0, len(clients))
  1144. for _, client := range clients {
  1145. c, ok := client.(map[string]any)
  1146. if !ok {
  1147. continue
  1148. }
  1149. email, _ := c["email"].(string)
  1150. if enable, exists := enableMap[email]; exists && !enable {
  1151. continue
  1152. }
  1153. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1154. continue
  1155. }
  1156. finalClients = append(finalClients, c)
  1157. }
  1158. settings["clients"] = finalClients
  1159. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1160. if err != nil {
  1161. return nil, err
  1162. }
  1163. runtimeInbound.Settings = string(modifiedSettings)
  1164. return &runtimeInbound, nil
  1165. }
  1166. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1167. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1168. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1169. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1170. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1171. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1172. oldClients, err := s.GetClients(oldInbound)
  1173. if err != nil {
  1174. return err
  1175. }
  1176. newClients, err := s.GetClients(newInbound)
  1177. if err != nil {
  1178. return err
  1179. }
  1180. // Email is the unique key for ClientTraffic rows. Clients without an
  1181. // email have no stats row to sync — skip them on both sides instead of
  1182. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1183. oldEmails := make(map[string]struct{}, len(oldClients))
  1184. for i := range oldClients {
  1185. if oldClients[i].Email == "" {
  1186. continue
  1187. }
  1188. oldEmails[oldClients[i].Email] = struct{}{}
  1189. }
  1190. newEmails := make(map[string]struct{}, len(newClients))
  1191. for i := range newClients {
  1192. if newClients[i].Email == "" {
  1193. continue
  1194. }
  1195. newEmails[newClients[i].Email] = struct{}{}
  1196. }
  1197. // Drop stats rows for removed emails — but not when a sibling inbound
  1198. // still references the email, since the row is the shared accumulator.
  1199. for i := range oldClients {
  1200. email := oldClients[i].Email
  1201. if email == "" {
  1202. continue
  1203. }
  1204. if _, kept := newEmails[email]; kept {
  1205. continue
  1206. }
  1207. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1208. if err != nil {
  1209. return err
  1210. }
  1211. if stillUsed {
  1212. continue
  1213. }
  1214. if err := s.DelClientStat(tx, email); err != nil {
  1215. return err
  1216. }
  1217. // Keep inbound_client_ips in sync when the inbound edit drops an
  1218. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1219. if err := s.DelClientIPs(tx, email); err != nil {
  1220. return err
  1221. }
  1222. }
  1223. for i := range newClients {
  1224. email := newClients[i].Email
  1225. if email == "" {
  1226. continue
  1227. }
  1228. if _, existed := oldEmails[email]; existed {
  1229. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1230. return err
  1231. }
  1232. continue
  1233. }
  1234. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1235. return err
  1236. }
  1237. }
  1238. return nil
  1239. }
  1240. func (s *InboundService) GetInboundTags() (string, error) {
  1241. db := database.GetDB()
  1242. var inboundTags []string
  1243. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1244. if err != nil && err != gorm.ErrRecordNotFound {
  1245. return "", err
  1246. }
  1247. tags, _ := json.Marshal(inboundTags)
  1248. return string(tags), nil
  1249. }
  1250. func (s *InboundService) GetClientReverseTags() (string, error) {
  1251. db := database.GetDB()
  1252. var inbounds []model.Inbound
  1253. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1254. if err != nil && err != gorm.ErrRecordNotFound {
  1255. return "[]", err
  1256. }
  1257. tagSet := make(map[string]struct{})
  1258. for _, inbound := range inbounds {
  1259. var settings map[string]any
  1260. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1261. continue
  1262. }
  1263. clients, ok := settings["clients"].([]any)
  1264. if !ok {
  1265. continue
  1266. }
  1267. for _, client := range clients {
  1268. clientMap, ok := client.(map[string]any)
  1269. if !ok {
  1270. continue
  1271. }
  1272. reverse, ok := clientMap["reverse"].(map[string]any)
  1273. if !ok {
  1274. continue
  1275. }
  1276. tag, _ := reverse["tag"].(string)
  1277. tag = strings.TrimSpace(tag)
  1278. if tag != "" {
  1279. tagSet[tag] = struct{}{}
  1280. }
  1281. }
  1282. }
  1283. rawTags := make([]string, 0, len(tagSet))
  1284. for tag := range tagSet {
  1285. rawTags = append(rawTags, tag)
  1286. }
  1287. sort.Strings(rawTags)
  1288. result, _ := json.Marshal(rawTags)
  1289. return string(result), nil
  1290. }
  1291. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1292. db := database.GetDB()
  1293. var inbounds []*model.Inbound
  1294. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1295. if err != nil && err != gorm.ErrRecordNotFound {
  1296. return nil, err
  1297. }
  1298. return inbounds, nil
  1299. }