inbound.go 30 KB

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