inbound.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. "sort"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  14. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. )
  18. type InboundService struct {
  19. xrayApi xray.XrayAPI
  20. clientService ClientService
  21. fallbackService FallbackService
  22. }
  23. // GetInbounds retrieves all inbounds for a specific user with client stats.
  24. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  25. db := database.GetDB()
  26. var inbounds []*model.Inbound
  27. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  28. if err != nil && err != gorm.ErrRecordNotFound {
  29. return nil, err
  30. }
  31. s.enrichClientStats(db, inbounds)
  32. s.annotateFallbackParents(db, inbounds)
  33. s.annotateLocalOriginGuid(inbounds)
  34. return inbounds, nil
  35. }
  36. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  37. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  38. // already carry the originating node's GUID. Read-time only (not persisted) so
  39. // the per-inbound online view can scope by GUID uniformly across a chain of
  40. // nodes (#4983).
  41. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  42. if len(inbounds) == 0 {
  43. return
  44. }
  45. guid := s.panelGuid()
  46. if guid == "" {
  47. return
  48. }
  49. for _, ib := range inbounds {
  50. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  51. ib.OriginNodeGuid = guid
  52. }
  53. }
  54. }
  55. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  56. // strips every per-client field other than email / enable / comment from
  57. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  58. // inbounds page only needs those three to roll up client counts and
  59. // render badges, so this trims tens of bytes per client (UUID, password,
  60. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  61. // up fast on installs with thousands of clients.
  62. //
  63. // Full client data is still available through GET /panel/api/inbounds/get/:id
  64. // for the edit/info/qr/export/clone flows that need it.
  65. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  66. db := database.GetDB()
  67. var inbounds []*model.Inbound
  68. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  69. if err != nil && err != gorm.ErrRecordNotFound {
  70. return nil, err
  71. }
  72. s.annotateFallbackParents(db, inbounds)
  73. s.annotateLocalOriginGuid(inbounds)
  74. for _, ib := range inbounds {
  75. ib.Settings = slimSettingsClients(ib.Settings)
  76. }
  77. return inbounds, nil
  78. }
  79. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  80. // keeps only the fields the list view actually reads. Returns the input
  81. // unchanged when the JSON can't be parsed or has no clients array.
  82. func slimSettingsClients(settings string) string {
  83. if settings == "" {
  84. return settings
  85. }
  86. var raw map[string]any
  87. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  88. return settings
  89. }
  90. clients, ok := raw["clients"].([]any)
  91. if !ok || len(clients) == 0 {
  92. return settings
  93. }
  94. slim := make([]any, 0, len(clients))
  95. for _, entry := range clients {
  96. c, ok := entry.(map[string]any)
  97. if !ok {
  98. continue
  99. }
  100. row := make(map[string]any, 3)
  101. if v, ok := c["email"]; ok {
  102. row["email"] = v
  103. }
  104. if v, ok := c["enable"]; ok {
  105. row["enable"] = v
  106. }
  107. if v, ok := c["comment"]; ok && v != "" {
  108. row["comment"] = v
  109. }
  110. slim = append(slim, row)
  111. }
  112. raw["clients"] = slim
  113. out, err := json.Marshal(raw)
  114. if err != nil {
  115. return settings
  116. }
  117. return string(out)
  118. }
  119. // annotateFallbackParents fills FallbackParent on each inbound that is
  120. // the child side of a fallback rule. One DB round-trip serves the full
  121. // list — the frontend needs this to rewrite the child's client-share
  122. // link so it points at the master's reachable endpoint.
  123. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  124. if len(inbounds) == 0 {
  125. return
  126. }
  127. childIds := make([]int, 0, len(inbounds))
  128. for _, ib := range inbounds {
  129. childIds = append(childIds, ib.Id)
  130. }
  131. var rows []model.InboundFallback
  132. if err := db.Where("child_id IN ?", childIds).
  133. Order("sort_order ASC, id ASC").
  134. Find(&rows).Error; err != nil {
  135. return
  136. }
  137. first := make(map[int]model.InboundFallback, len(rows))
  138. for _, r := range rows {
  139. if _, ok := first[r.ChildId]; !ok {
  140. first[r.ChildId] = r
  141. }
  142. }
  143. for _, ib := range inbounds {
  144. if r, ok := first[ib.Id]; ok {
  145. ib.FallbackParent = &model.FallbackParentInfo{
  146. MasterId: r.MasterId,
  147. Path: r.Path,
  148. }
  149. }
  150. }
  151. }
  152. type InboundOption struct {
  153. Id int `json:"id" example:"1"`
  154. Remark string `json:"remark" example:"VLESS-443"`
  155. Tag string `json:"tag" example:"in-443-tcp"`
  156. Protocol string `json:"protocol" example:"vless"`
  157. Port int `json:"port" example:"443"`
  158. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  159. SsMethod string `json:"ssMethod"`
  160. }
  161. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  162. db := database.GetDB()
  163. var rows []struct {
  164. Id int `gorm:"column:id"`
  165. Remark string `gorm:"column:remark"`
  166. Tag string `gorm:"column:tag"`
  167. Protocol string `gorm:"column:protocol"`
  168. Port int `gorm:"column:port"`
  169. StreamSettings string `gorm:"column:stream_settings"`
  170. Settings string `gorm:"column:settings"`
  171. }
  172. err := db.Table("inbounds").
  173. Select("id, remark, tag, protocol, port, stream_settings, settings").
  174. Where("user_id = ?", userId).
  175. Order("id ASC").
  176. Scan(&rows).Error
  177. if err != nil && err != gorm.ErrRecordNotFound {
  178. return nil, err
  179. }
  180. out := make([]InboundOption, 0, len(rows))
  181. for _, r := range rows {
  182. out = append(out, InboundOption{
  183. Id: r.Id,
  184. Remark: r.Remark,
  185. Tag: r.Tag,
  186. Protocol: r.Protocol,
  187. Port: r.Port,
  188. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings),
  189. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  190. })
  191. }
  192. return out, nil
  193. }
  194. // GetAllInbounds retrieves all inbounds with client stats.
  195. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  196. db := database.GetDB()
  197. var inbounds []*model.Inbound
  198. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  199. if err != nil && err != gorm.ErrRecordNotFound {
  200. return nil, err
  201. }
  202. s.enrichClientStats(db, inbounds)
  203. return inbounds, nil
  204. }
  205. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  206. db := database.GetDB()
  207. var inbounds []*model.Inbound
  208. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  209. if err != nil && err != gorm.ErrRecordNotFound {
  210. return nil, err
  211. }
  212. return inbounds, nil
  213. }
  214. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  215. settings := map[string][]model.Client{}
  216. json.Unmarshal([]byte(inbound.Settings), &settings)
  217. if settings == nil {
  218. return nil, fmt.Errorf("setting is null")
  219. }
  220. clients := settings["clients"]
  221. if clients == nil {
  222. return nil, nil
  223. }
  224. return clients, nil
  225. }
  226. func (s *InboundService) GetAllEmails() ([]string, error) {
  227. db := database.GetDB()
  228. var emails []string
  229. query := fmt.Sprintf(
  230. "SELECT DISTINCT %s %s",
  231. database.JSONFieldText("client.value", "email"),
  232. database.JSONClientsFromInbound(),
  233. )
  234. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  235. return nil, err
  236. }
  237. return emails, nil
  238. }
  239. // getAllEmailSubIDs returns email→subId. An email seen with two different
  240. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  241. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  242. db := database.GetDB()
  243. var rows []struct {
  244. Email string
  245. SubID string
  246. }
  247. query := fmt.Sprintf(
  248. "SELECT %s AS email, %s AS sub_id %s",
  249. database.JSONFieldText("client.value", "email"),
  250. database.JSONFieldText("client.value", "subId"),
  251. database.JSONClientsFromInbound(),
  252. )
  253. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  254. return nil, err
  255. }
  256. result := make(map[string]string, len(rows))
  257. for _, r := range rows {
  258. email := strings.ToLower(r.Email)
  259. if email == "" {
  260. continue
  261. }
  262. subID := r.SubID
  263. if existing, ok := result[email]; ok {
  264. if existing != subID {
  265. result[email] = ""
  266. }
  267. continue
  268. }
  269. result[email] = subID
  270. }
  271. return result, nil
  272. }
  273. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  274. // Only vmess, vless, trojan, shadowsocks, and hysteria protocols use streamSettings.
  275. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  276. protocolsWithStream := map[model.Protocol]bool{
  277. model.VMESS: true,
  278. model.VLESS: true,
  279. model.Trojan: true,
  280. model.Shadowsocks: true,
  281. model.Hysteria: true,
  282. }
  283. if !protocolsWithStream[inbound.Protocol] {
  284. inbound.StreamSettings = ""
  285. }
  286. }
  287. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  288. // always valid and matches the configured domain before the row is persisted.
  289. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  290. if inbound.Protocol != model.MTProto {
  291. return
  292. }
  293. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  294. inbound.Settings = healed
  295. }
  296. }
  297. // AddInbound creates a new inbound configuration.
  298. // It validates port uniqueness, client email uniqueness, and required fields,
  299. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  300. // Returns the created inbound, whether Xray needs restart, and any error.
  301. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  302. // Normalize streamSettings based on protocol
  303. s.normalizeStreamSettings(inbound)
  304. s.normalizeMtprotoSecret(inbound)
  305. conflict, err := s.checkPortConflict(inbound, 0)
  306. if err != nil {
  307. return inbound, false, err
  308. }
  309. if conflict != nil {
  310. return inbound, false, common.NewError(conflict.String())
  311. }
  312. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  313. if err != nil {
  314. return inbound, false, err
  315. }
  316. clients, err := s.GetClients(inbound)
  317. if err != nil {
  318. return inbound, false, err
  319. }
  320. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  321. if err != nil {
  322. return inbound, false, err
  323. }
  324. if existEmail != "" {
  325. return inbound, false, common.NewError("Duplicate email:", existEmail)
  326. }
  327. // Ensure created_at and updated_at on clients in settings
  328. if len(clients) > 0 {
  329. var settings map[string]any
  330. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  331. now := time.Now().Unix() * 1000
  332. updatedClients := make([]model.Client, 0, len(clients))
  333. for _, c := range clients {
  334. if c.CreatedAt == 0 {
  335. c.CreatedAt = now
  336. }
  337. c.UpdatedAt = now
  338. updatedClients = append(updatedClients, c)
  339. }
  340. settings["clients"] = updatedClients
  341. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  342. inbound.Settings = string(bs)
  343. } else {
  344. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  345. }
  346. } else if err2 != nil {
  347. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  348. }
  349. }
  350. // Secure client ID
  351. for _, client := range clients {
  352. switch inbound.Protocol {
  353. case "trojan":
  354. if client.Password == "" {
  355. return inbound, false, common.NewError("empty client ID")
  356. }
  357. case "shadowsocks":
  358. if client.Email == "" {
  359. return inbound, false, common.NewError("empty client ID")
  360. }
  361. case "hysteria":
  362. if client.Auth == "" {
  363. return inbound, false, common.NewError("empty client ID")
  364. }
  365. default:
  366. if client.ID == "" {
  367. return inbound, false, common.NewError("empty client ID")
  368. }
  369. }
  370. }
  371. db := database.GetDB()
  372. tx := db.Begin()
  373. markDirty := false
  374. defer func() {
  375. if err != nil {
  376. tx.Rollback()
  377. return
  378. }
  379. tx.Commit()
  380. if markDirty && inbound.NodeID != nil {
  381. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  382. logger.Warning("mark node dirty failed:", dErr)
  383. }
  384. }
  385. }()
  386. err = tx.Save(inbound).Error
  387. if err == nil {
  388. if len(inbound.ClientStats) == 0 {
  389. for _, client := range clients {
  390. s.AddClientStat(tx, inbound.Id, &client)
  391. }
  392. }
  393. } else {
  394. return inbound, false, err
  395. }
  396. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  397. return inbound, false, err
  398. }
  399. needRestart := false
  400. if inbound.Enable {
  401. rt, push, dirty, perr := s.nodePushPlan(inbound)
  402. if perr != nil {
  403. err = perr
  404. return inbound, false, err
  405. }
  406. if dirty {
  407. markDirty = true
  408. }
  409. if push {
  410. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  411. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  412. } else {
  413. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  414. if inbound.NodeID != nil {
  415. markDirty = true
  416. } else {
  417. needRestart = true
  418. }
  419. }
  420. }
  421. }
  422. return inbound, needRestart, err
  423. }
  424. func (s *InboundService) DelInbound(id int) (bool, error) {
  425. db := database.GetDB()
  426. needRestart := false
  427. markDirty := false
  428. var ib model.Inbound
  429. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  430. if loadErr == nil {
  431. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  432. if shouldPushToRuntime {
  433. rt, push, dirty, perr := s.nodePushPlan(&ib)
  434. if perr != nil {
  435. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  436. markDirty = true
  437. } else if push {
  438. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  439. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  440. } else {
  441. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  442. if ib.NodeID == nil {
  443. needRestart = true
  444. } else {
  445. markDirty = true
  446. }
  447. }
  448. } else if ib.NodeID == nil {
  449. needRestart = true
  450. } else if dirty {
  451. markDirty = true
  452. }
  453. } else {
  454. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  455. }
  456. } else {
  457. logger.Debug("DelInbound: inbound not found, id:", id)
  458. }
  459. if err := s.clientService.DetachInbound(db, id); err != nil {
  460. return false, err
  461. }
  462. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  463. return needRestart, err
  464. }
  465. if markDirty && ib.NodeID != nil {
  466. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  467. logger.Warning("mark node dirty failed:", dErr)
  468. }
  469. }
  470. if !database.IsPostgres() {
  471. var count int64
  472. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  473. return needRestart, err
  474. }
  475. if count == 0 {
  476. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  477. return needRestart, err
  478. }
  479. }
  480. }
  481. return needRestart, nil
  482. }
  483. type BulkDelInboundResult struct {
  484. Deleted int `json:"deleted"`
  485. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  486. }
  487. type BulkDelInboundReport struct {
  488. Id int `json:"id"`
  489. Reason string `json:"reason"`
  490. }
  491. // DelInbounds removes every inbound in the list, reusing the single-delete
  492. // path per id. Failures are recorded in Skipped and processing continues for
  493. // the rest; the aggregated needRestart is returned so the caller restarts
  494. // xray at most once.
  495. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  496. result := BulkDelInboundResult{}
  497. needRestart := false
  498. for _, id := range ids {
  499. r, err := s.DelInbound(id)
  500. if err != nil {
  501. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  502. continue
  503. }
  504. result.Deleted++
  505. if r {
  506. needRestart = true
  507. }
  508. }
  509. return result, needRestart, nil
  510. }
  511. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  512. db := database.GetDB()
  513. inbound := &model.Inbound{}
  514. err := db.Model(model.Inbound{}).First(inbound, id).Error
  515. if err != nil {
  516. return nil, err
  517. }
  518. return inbound, nil
  519. }
  520. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  521. db := database.GetDB()
  522. inbound := &model.Inbound{}
  523. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  524. if err != nil {
  525. return nil, err
  526. }
  527. s.enrichClientStats(db, []*model.Inbound{inbound})
  528. return inbound, nil
  529. }
  530. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  531. inbound, err := s.GetInbound(id)
  532. if err != nil {
  533. return false, err
  534. }
  535. if inbound.Enable == enable {
  536. return false, nil
  537. }
  538. db := database.GetDB()
  539. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  540. Update("enable", enable).Error; err != nil {
  541. return false, err
  542. }
  543. inbound.Enable = enable
  544. needRestart := false
  545. rt, push, dirty, perr := s.nodePushPlan(inbound)
  546. if perr != nil {
  547. return false, perr
  548. }
  549. // Remote nodes interpret DelInbound as a real row delete (it hits
  550. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  551. // switch on a remote inbound used to wipe the row entirely (#4402).
  552. // PATCH the remote row via UpdateInbound instead — preserves the
  553. // settings/client history and just flips the enable flag.
  554. if inbound.NodeID != nil {
  555. if push {
  556. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  557. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  558. dirty = true
  559. }
  560. }
  561. if dirty {
  562. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  563. logger.Warning("mark node dirty failed:", dErr)
  564. }
  565. }
  566. return false, nil
  567. }
  568. if !push {
  569. return true, nil
  570. }
  571. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  572. !strings.Contains(err.Error(), "not found") {
  573. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  574. needRestart = true
  575. }
  576. if !enable {
  577. return needRestart, nil
  578. }
  579. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  580. if err != nil {
  581. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  582. return true, nil
  583. }
  584. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  585. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  586. needRestart = true
  587. }
  588. return needRestart, nil
  589. }
  590. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  591. // Normalize streamSettings based on protocol
  592. s.normalizeStreamSettings(inbound)
  593. s.normalizeMtprotoSecret(inbound)
  594. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  595. if err != nil {
  596. return inbound, false, err
  597. }
  598. if conflict != nil {
  599. return inbound, false, common.NewError(conflict.String())
  600. }
  601. oldInbound, err := s.GetInbound(inbound.Id)
  602. if err != nil {
  603. return inbound, false, err
  604. }
  605. inbound.NodeID = oldInbound.NodeID
  606. tag := oldInbound.Tag
  607. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  608. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  609. db := database.GetDB()
  610. tx := db.Begin()
  611. markDirty := false
  612. defer func() {
  613. if err != nil {
  614. tx.Rollback()
  615. return
  616. }
  617. tx.Commit()
  618. if markDirty && oldInbound.NodeID != nil {
  619. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  620. logger.Warning("mark node dirty failed:", dErr)
  621. }
  622. }
  623. }()
  624. err = s.updateClientTraffics(tx, oldInbound, inbound)
  625. if err != nil {
  626. return inbound, false, err
  627. }
  628. // Ensure created_at and updated_at exist in inbound.Settings clients
  629. {
  630. var oldSettings map[string]any
  631. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  632. emailToCreated := map[string]int64{}
  633. emailToUpdated := map[string]int64{}
  634. if oldSettings != nil {
  635. if oc, ok := oldSettings["clients"].([]any); ok {
  636. for _, it := range oc {
  637. if m, ok2 := it.(map[string]any); ok2 {
  638. if email, ok3 := m["email"].(string); ok3 {
  639. switch v := m["created_at"].(type) {
  640. case float64:
  641. emailToCreated[email] = int64(v)
  642. case int64:
  643. emailToCreated[email] = v
  644. }
  645. switch v := m["updated_at"].(type) {
  646. case float64:
  647. emailToUpdated[email] = int64(v)
  648. case int64:
  649. emailToUpdated[email] = v
  650. }
  651. }
  652. }
  653. }
  654. }
  655. }
  656. var newSettings map[string]any
  657. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  658. now := time.Now().Unix() * 1000
  659. if nSlice, ok := newSettings["clients"].([]any); ok {
  660. for i := range nSlice {
  661. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  662. email, _ := m["email"].(string)
  663. if _, ok3 := m["created_at"]; !ok3 {
  664. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  665. m["created_at"] = v
  666. } else {
  667. m["created_at"] = now
  668. }
  669. }
  670. // Preserve client's updated_at if present; do not bump on parent inbound update
  671. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  672. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  673. m["updated_at"] = v
  674. }
  675. }
  676. nSlice[i] = m
  677. }
  678. }
  679. newSettings["clients"] = nSlice
  680. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  681. inbound.Settings = string(bs)
  682. }
  683. }
  684. }
  685. }
  686. oldInbound.Total = inbound.Total
  687. oldInbound.Remark = inbound.Remark
  688. oldInbound.Enable = inbound.Enable
  689. oldInbound.ExpiryTime = inbound.ExpiryTime
  690. oldInbound.TrafficReset = inbound.TrafficReset
  691. oldInbound.Listen = inbound.Listen
  692. oldInbound.Port = inbound.Port
  693. oldInbound.Protocol = inbound.Protocol
  694. oldInbound.Settings = inbound.Settings
  695. oldInbound.StreamSettings = inbound.StreamSettings
  696. oldInbound.Sniffing = inbound.Sniffing
  697. if oldTagWasAuto && inbound.Tag == tag {
  698. inbound.Tag = ""
  699. }
  700. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  701. if err != nil {
  702. return inbound, false, err
  703. }
  704. inbound.Tag = oldInbound.Tag
  705. needRestart := false
  706. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  707. if perr != nil {
  708. err = perr
  709. return inbound, false, err
  710. }
  711. if dirty {
  712. markDirty = true
  713. }
  714. if oldInbound.NodeID == nil {
  715. if !push {
  716. needRestart = true
  717. } else {
  718. oldSnapshot := *oldInbound
  719. oldSnapshot.Tag = tag
  720. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  721. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  722. }
  723. if inbound.Enable {
  724. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  725. if err2 != nil {
  726. logger.Debug("Unable to prepare runtime inbound config:", err2)
  727. needRestart = true
  728. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  729. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  730. } else {
  731. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  732. needRestart = true
  733. }
  734. }
  735. }
  736. } else if push {
  737. oldSnapshot := *oldInbound
  738. oldSnapshot.Tag = tag
  739. if !inbound.Enable {
  740. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  741. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  742. markDirty = true
  743. }
  744. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  745. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  746. markDirty = true
  747. }
  748. }
  749. if err = tx.Save(oldInbound).Error; err != nil {
  750. return inbound, false, err
  751. }
  752. newClients, gcErr := s.GetClients(oldInbound)
  753. if gcErr != nil {
  754. err = gcErr
  755. return inbound, false, err
  756. }
  757. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  758. return inbound, false, err
  759. }
  760. return inbound, needRestart, nil
  761. }
  762. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  763. if inbound == nil {
  764. return nil, fmt.Errorf("inbound is nil")
  765. }
  766. runtimeInbound := *inbound
  767. settings := map[string]any{}
  768. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  769. return nil, err
  770. }
  771. clients, ok := settings["clients"].([]any)
  772. if !ok {
  773. return &runtimeInbound, nil
  774. }
  775. var clientStats []xray.ClientTraffic
  776. err := tx.Model(xray.ClientTraffic{}).
  777. Where("inbound_id = ?", inbound.Id).
  778. Select("email", "enable").
  779. Find(&clientStats).Error
  780. if err != nil {
  781. return nil, err
  782. }
  783. enableMap := make(map[string]bool, len(clientStats))
  784. for _, clientTraffic := range clientStats {
  785. enableMap[clientTraffic.Email] = clientTraffic.Enable
  786. }
  787. finalClients := make([]any, 0, len(clients))
  788. for _, client := range clients {
  789. c, ok := client.(map[string]any)
  790. if !ok {
  791. continue
  792. }
  793. email, _ := c["email"].(string)
  794. if enable, exists := enableMap[email]; exists && !enable {
  795. continue
  796. }
  797. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  798. continue
  799. }
  800. finalClients = append(finalClients, c)
  801. }
  802. settings["clients"] = finalClients
  803. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  804. if err != nil {
  805. return nil, err
  806. }
  807. runtimeInbound.Settings = string(modifiedSettings)
  808. return &runtimeInbound, nil
  809. }
  810. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  811. // list: removes rows for emails that disappeared, inserts rows for newly-added
  812. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  813. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  814. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  815. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  816. oldClients, err := s.GetClients(oldInbound)
  817. if err != nil {
  818. return err
  819. }
  820. newClients, err := s.GetClients(newInbound)
  821. if err != nil {
  822. return err
  823. }
  824. // Email is the unique key for ClientTraffic rows. Clients without an
  825. // email have no stats row to sync — skip them on both sides instead of
  826. // risking a unique-constraint hit or accidental delete of an unrelated row.
  827. oldEmails := make(map[string]struct{}, len(oldClients))
  828. for i := range oldClients {
  829. if oldClients[i].Email == "" {
  830. continue
  831. }
  832. oldEmails[oldClients[i].Email] = struct{}{}
  833. }
  834. newEmails := make(map[string]struct{}, len(newClients))
  835. for i := range newClients {
  836. if newClients[i].Email == "" {
  837. continue
  838. }
  839. newEmails[newClients[i].Email] = struct{}{}
  840. }
  841. // Drop stats rows for removed emails — but not when a sibling inbound
  842. // still references the email, since the row is the shared accumulator.
  843. for i := range oldClients {
  844. email := oldClients[i].Email
  845. if email == "" {
  846. continue
  847. }
  848. if _, kept := newEmails[email]; kept {
  849. continue
  850. }
  851. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  852. if err != nil {
  853. return err
  854. }
  855. if stillUsed {
  856. continue
  857. }
  858. if err := s.DelClientStat(tx, email); err != nil {
  859. return err
  860. }
  861. // Keep inbound_client_ips in sync when the inbound edit drops an
  862. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  863. if err := s.DelClientIPs(tx, email); err != nil {
  864. return err
  865. }
  866. }
  867. for i := range newClients {
  868. email := newClients[i].Email
  869. if email == "" {
  870. continue
  871. }
  872. if _, existed := oldEmails[email]; existed {
  873. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  874. return err
  875. }
  876. continue
  877. }
  878. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  879. return err
  880. }
  881. }
  882. return nil
  883. }
  884. func (s *InboundService) GetInboundTags() (string, error) {
  885. db := database.GetDB()
  886. var inboundTags []string
  887. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  888. if err != nil && err != gorm.ErrRecordNotFound {
  889. return "", err
  890. }
  891. tags, _ := json.Marshal(inboundTags)
  892. return string(tags), nil
  893. }
  894. func (s *InboundService) GetClientReverseTags() (string, error) {
  895. db := database.GetDB()
  896. var inbounds []model.Inbound
  897. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  898. if err != nil && err != gorm.ErrRecordNotFound {
  899. return "[]", err
  900. }
  901. tagSet := make(map[string]struct{})
  902. for _, inbound := range inbounds {
  903. var settings map[string]any
  904. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  905. continue
  906. }
  907. clients, ok := settings["clients"].([]any)
  908. if !ok {
  909. continue
  910. }
  911. for _, client := range clients {
  912. clientMap, ok := client.(map[string]any)
  913. if !ok {
  914. continue
  915. }
  916. reverse, ok := clientMap["reverse"].(map[string]any)
  917. if !ok {
  918. continue
  919. }
  920. tag, _ := reverse["tag"].(string)
  921. tag = strings.TrimSpace(tag)
  922. if tag != "" {
  923. tagSet[tag] = struct{}{}
  924. }
  925. }
  926. }
  927. rawTags := make([]string, 0, len(tagSet))
  928. for tag := range tagSet {
  929. rawTags = append(rawTags, tag)
  930. }
  931. sort.Strings(rawTags)
  932. result, _ := json.Marshal(rawTags)
  933. return string(result), nil
  934. }
  935. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  936. db := database.GetDB()
  937. var inbounds []*model.Inbound
  938. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  939. if err != nil && err != gorm.ErrRecordNotFound {
  940. return nil, err
  941. }
  942. return inbounds, nil
  943. }