inbound.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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, and wireguard protocols use
  404. // streamSettings (wireguard for finalmask UDP masks and sockopt on its listener).
  405. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  406. protocolsWithStream := map[model.Protocol]bool{
  407. model.VMESS: true,
  408. model.VLESS: true,
  409. model.Trojan: true,
  410. model.Shadowsocks: true,
  411. model.Hysteria: true,
  412. model.WireGuard: true,
  413. }
  414. if !protocolsWithStream[inbound.Protocol] {
  415. inbound.StreamSettings = ""
  416. }
  417. }
  418. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  419. // always valid and matches the configured domain before the row is persisted.
  420. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  421. if inbound.Protocol != model.MTProto {
  422. return
  423. }
  424. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  425. inbound.Settings = healed
  426. }
  427. }
  428. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  429. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  430. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  431. if inbound == nil || inbound.Protocol != model.MTProto {
  432. return false
  433. }
  434. var parsed struct {
  435. RouteThroughXray bool `json:"routeThroughXray"`
  436. }
  437. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  438. return false
  439. }
  440. return parsed.RouteThroughXray
  441. }
  442. func settingsRouteXrayPort(parsed map[string]any) int {
  443. switch v := parsed["routeXrayPort"].(type) {
  444. case float64:
  445. return int(v)
  446. case int:
  447. return v
  448. case json.Number:
  449. if n, err := v.Int64(); err == nil {
  450. return int(n)
  451. }
  452. }
  453. return 0
  454. }
  455. func parseRouteXrayPort(settings string) int {
  456. if settings == "" {
  457. return 0
  458. }
  459. var parsed map[string]any
  460. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  461. return 0
  462. }
  463. return settingsRouteXrayPort(parsed)
  464. }
  465. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  466. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  467. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  468. // allocated once when routing is first enabled and preserved across edits
  469. // (carried over from oldSettings, which wins over any value the client echoed
  470. // back). When routing is off it — together with the now-inert outbound
  471. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  472. //
  473. // It returns an error when an egress port cannot be allocated or persisted, so
  474. // the caller refuses the save rather than storing a routed-but-portless inbound,
  475. // which would otherwise route no traffic and have its mtg metrics skipped (see
  476. // mtproto_job) — silently losing its accounting.
  477. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  478. if inbound.Protocol != model.MTProto {
  479. return nil
  480. }
  481. var parsed map[string]any
  482. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  483. return nil
  484. }
  485. routed, _ := parsed["routeThroughXray"].(bool)
  486. if !routed {
  487. _, hadPort := parsed["routeXrayPort"]
  488. _, hadTag := parsed["outboundTag"]
  489. if !hadPort && !hadTag {
  490. return nil
  491. }
  492. delete(parsed, "routeXrayPort")
  493. delete(parsed, "outboundTag")
  494. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  495. inbound.Settings = string(bs)
  496. } else {
  497. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  498. }
  499. return nil
  500. }
  501. // Prefer the already-stored port (carried across edits), then any value the
  502. // client sent, then allocate a fresh one.
  503. port := parseRouteXrayPort(oldSettings)
  504. if port <= 0 {
  505. port = settingsRouteXrayPort(parsed)
  506. }
  507. if port <= 0 {
  508. allocated, err := mtproto.FreeLocalPort()
  509. if err != nil {
  510. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  511. }
  512. port = allocated
  513. }
  514. if settingsRouteXrayPort(parsed) == port {
  515. return nil
  516. }
  517. parsed["routeXrayPort"] = port
  518. bs, err := json.MarshalIndent(parsed, "", " ")
  519. if err != nil {
  520. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  521. }
  522. inbound.Settings = string(bs)
  523. return nil
  524. }
  525. // AddInbound creates a new inbound configuration.
  526. // It validates port uniqueness, client email uniqueness, and required fields,
  527. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  528. // Returns the created inbound, whether Xray needs restart, and any error.
  529. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  530. // Normalize streamSettings based on protocol
  531. s.normalizeStreamSettings(inbound)
  532. s.normalizeMtprotoSecret(inbound)
  533. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  534. return inbound, false, err
  535. }
  536. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  537. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  538. return inbound, false, err
  539. }
  540. conflict, err := s.checkPortConflict(inbound, 0)
  541. if err != nil {
  542. return inbound, false, err
  543. }
  544. if conflict != nil {
  545. return inbound, false, common.NewError(conflict.String())
  546. }
  547. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  548. if err != nil {
  549. return inbound, false, err
  550. }
  551. clients, err := s.GetClients(inbound)
  552. if err != nil {
  553. return inbound, false, err
  554. }
  555. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  556. if err != nil {
  557. return inbound, false, err
  558. }
  559. if existEmail != "" {
  560. return inbound, false, common.NewError("Duplicate email:", existEmail)
  561. }
  562. // Ensure created_at and updated_at on clients in settings
  563. if len(clients) > 0 {
  564. var settings map[string]any
  565. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  566. now := time.Now().Unix() * 1000
  567. updatedClients := make([]model.Client, 0, len(clients))
  568. for _, c := range clients {
  569. if c.CreatedAt == 0 {
  570. c.CreatedAt = now
  571. }
  572. c.UpdatedAt = now
  573. updatedClients = append(updatedClients, c)
  574. }
  575. settings["clients"] = updatedClients
  576. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  577. inbound.Settings = string(bs)
  578. } else {
  579. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  580. }
  581. } else if err2 != nil {
  582. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  583. }
  584. }
  585. // Secure client ID
  586. for _, client := range clients {
  587. switch inbound.Protocol {
  588. case "trojan":
  589. if client.Password == "" {
  590. return inbound, false, common.NewError("empty client ID")
  591. }
  592. case "shadowsocks":
  593. if client.Email == "" {
  594. return inbound, false, common.NewError("empty client ID")
  595. }
  596. case "hysteria":
  597. if client.Auth == "" {
  598. return inbound, false, common.NewError("empty client ID")
  599. }
  600. default:
  601. if client.ID == "" {
  602. return inbound, false, common.NewError("empty client ID")
  603. }
  604. }
  605. }
  606. db := database.GetDB()
  607. tx := db.Begin()
  608. markDirty := false
  609. defer func() {
  610. if err != nil {
  611. tx.Rollback()
  612. return
  613. }
  614. tx.Commit()
  615. if markDirty && inbound.NodeID != nil {
  616. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  617. logger.Warning("mark node dirty failed:", dErr)
  618. }
  619. }
  620. }()
  621. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  622. // those rows with an ON CONFLICT target on the primary key only, which
  623. // collides with the globally-unique client_traffics.email when an imported
  624. // inbound carries clients that another inbound already created (e.g.
  625. // importing two inbounds that share the same clients). We insert the stats
  626. // ourselves below with the same email-conflict guard AddClientStat uses.
  627. err = tx.Omit("ClientStats").Save(inbound).Error
  628. if err != nil {
  629. return inbound, false, err
  630. }
  631. // Imported stats first, so their traffic counters survive; emails that
  632. // already own a (shared) row are skipped instead of tripping the unique
  633. // constraint.
  634. for i := range inbound.ClientStats {
  635. if inbound.ClientStats[i].Email == "" {
  636. continue
  637. }
  638. inbound.ClientStats[i].Id = 0
  639. inbound.ClientStats[i].InboundId = inbound.Id
  640. if err = tx.Clauses(clause.OnConflict{
  641. Columns: []clause.Column{{Name: "email"}},
  642. DoNothing: true,
  643. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  644. return inbound, false, err
  645. }
  646. }
  647. // Then make sure every client has a stats row. AddClientStat is a no-op
  648. // where one exists (including the rows just inserted), and fills the gap
  649. // for clients an import payload didn't carry stats for.
  650. for _, client := range clients {
  651. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  652. return inbound, false, err
  653. }
  654. }
  655. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  656. return inbound, false, err
  657. }
  658. // Before the deferred commit, so a node in "selected" sync mode cannot
  659. // sweep the new central row in the gap before its tag is allowed.
  660. if inbound.NodeID != nil {
  661. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  662. logger.Warning("allow inbound tag on node failed:", aErr)
  663. }
  664. }
  665. needRestart := false
  666. if inbound.Enable {
  667. rt, push, dirty, perr := s.nodePushPlan(inbound)
  668. if perr != nil {
  669. err = perr
  670. return inbound, false, err
  671. }
  672. if dirty {
  673. markDirty = true
  674. }
  675. if push {
  676. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  677. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  678. } else {
  679. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  680. if inbound.NodeID != nil {
  681. markDirty = true
  682. } else {
  683. needRestart = true
  684. }
  685. }
  686. }
  687. }
  688. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  689. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  690. // in the generated config, so force a regen to wire it in.
  691. if mtprotoRoutesThroughXray(inbound) {
  692. needRestart = true
  693. }
  694. return inbound, needRestart, err
  695. }
  696. func (s *InboundService) DelInbound(id int) (bool, error) {
  697. db := database.GetDB()
  698. needRestart := false
  699. markDirty := false
  700. var ib model.Inbound
  701. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  702. if loadErr == nil {
  703. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  704. if shouldPushToRuntime {
  705. rt, push, dirty, perr := s.nodePushPlan(&ib)
  706. if perr != nil {
  707. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  708. markDirty = true
  709. } else if push {
  710. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  711. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  712. } else {
  713. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  714. if ib.NodeID == nil {
  715. needRestart = true
  716. } else {
  717. markDirty = true
  718. }
  719. }
  720. } else if ib.NodeID == nil {
  721. needRestart = true
  722. } else if dirty {
  723. markDirty = true
  724. }
  725. } else {
  726. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  727. }
  728. } else {
  729. logger.Debug("DelInbound: inbound not found, id:", id)
  730. }
  731. if err := s.clientService.DetachInbound(db, id); err != nil {
  732. return false, err
  733. }
  734. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  735. return needRestart, err
  736. }
  737. if markDirty && ib.NodeID != nil {
  738. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  739. logger.Warning("mark node dirty failed:", dErr)
  740. }
  741. }
  742. if !database.IsPostgres() {
  743. var count int64
  744. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  745. return needRestart, err
  746. }
  747. if count == 0 {
  748. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  749. return needRestart, err
  750. }
  751. }
  752. }
  753. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  754. if mtprotoRoutesThroughXray(&ib) {
  755. needRestart = true
  756. }
  757. return needRestart, nil
  758. }
  759. type BulkDelInboundResult struct {
  760. Deleted int `json:"deleted"`
  761. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  762. }
  763. type BulkDelInboundReport struct {
  764. Id int `json:"id"`
  765. Reason string `json:"reason"`
  766. }
  767. // DelInbounds removes every inbound in the list, reusing the single-delete
  768. // path per id. Failures are recorded in Skipped and processing continues for
  769. // the rest; the aggregated needRestart is returned so the caller restarts
  770. // xray at most once.
  771. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  772. result := BulkDelInboundResult{}
  773. needRestart := false
  774. for _, id := range ids {
  775. r, err := s.DelInbound(id)
  776. if err != nil {
  777. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  778. continue
  779. }
  780. result.Deleted++
  781. if r {
  782. needRestart = true
  783. }
  784. }
  785. return result, needRestart, nil
  786. }
  787. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  788. db := database.GetDB()
  789. inbound := &model.Inbound{}
  790. err := db.Model(model.Inbound{}).First(inbound, id).Error
  791. if err != nil {
  792. return nil, err
  793. }
  794. return inbound, nil
  795. }
  796. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  797. db := database.GetDB()
  798. inbound := &model.Inbound{}
  799. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  800. if err != nil {
  801. return nil, err
  802. }
  803. s.enrichClientStats(db, []*model.Inbound{inbound})
  804. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  805. return inbound, nil
  806. }
  807. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  808. inbound, err := s.GetInbound(id)
  809. if err != nil {
  810. return false, err
  811. }
  812. if inbound.Enable == enable {
  813. return false, nil
  814. }
  815. db := database.GetDB()
  816. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  817. Update("enable", enable).Error; err != nil {
  818. return false, err
  819. }
  820. inbound.Enable = enable
  821. needRestart := false
  822. rt, push, dirty, perr := s.nodePushPlan(inbound)
  823. if perr != nil {
  824. return false, perr
  825. }
  826. // Remote nodes interpret DelInbound as a real row delete (it hits
  827. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  828. // switch on a remote inbound used to wipe the row entirely (#4402).
  829. // PATCH the remote row via UpdateInbound instead — preserves the
  830. // settings/client history and just flips the enable flag.
  831. if inbound.NodeID != nil {
  832. if push {
  833. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  834. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  835. dirty = true
  836. }
  837. }
  838. if dirty {
  839. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  840. logger.Warning("mark node dirty failed:", dErr)
  841. }
  842. }
  843. return false, nil
  844. }
  845. if !push {
  846. return true, nil
  847. }
  848. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  849. !strings.Contains(err.Error(), "not found") {
  850. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  851. needRestart = true
  852. }
  853. if !enable {
  854. return needRestart, nil
  855. }
  856. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  857. if err != nil {
  858. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  859. return true, nil
  860. }
  861. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  862. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  863. needRestart = true
  864. }
  865. return needRestart, nil
  866. }
  867. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  868. // Normalize streamSettings based on protocol
  869. s.normalizeStreamSettings(inbound)
  870. s.normalizeMtprotoSecret(inbound)
  871. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  872. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  873. if err != nil {
  874. return inbound, false, err
  875. }
  876. if conflict != nil {
  877. return inbound, false, common.NewError(conflict.String())
  878. }
  879. oldInbound, err := s.GetInbound(inbound.Id)
  880. if err != nil {
  881. return inbound, false, err
  882. }
  883. inbound.NodeID = oldInbound.NodeID
  884. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  885. // with the new settings further down, then ensure a routed inbound keeps a
  886. // stable egress port (reusing the one already stored).
  887. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  888. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  889. return inbound, false, err
  890. }
  891. tag := oldInbound.Tag
  892. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  893. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  894. db := database.GetDB()
  895. tx := db.Begin()
  896. markDirty := false
  897. defer func() {
  898. if err != nil {
  899. tx.Rollback()
  900. return
  901. }
  902. tx.Commit()
  903. if markDirty && oldInbound.NodeID != nil {
  904. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  905. logger.Warning("mark node dirty failed:", dErr)
  906. }
  907. }
  908. }()
  909. err = s.updateClientTraffics(tx, oldInbound, inbound)
  910. if err != nil {
  911. return inbound, false, err
  912. }
  913. // Ensure created_at and updated_at exist in inbound.Settings clients
  914. {
  915. var oldSettings map[string]any
  916. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  917. emailToCreated := map[string]int64{}
  918. emailToUpdated := map[string]int64{}
  919. if oldSettings != nil {
  920. if oc, ok := oldSettings["clients"].([]any); ok {
  921. for _, it := range oc {
  922. if m, ok2 := it.(map[string]any); ok2 {
  923. if email, ok3 := m["email"].(string); ok3 {
  924. switch v := m["created_at"].(type) {
  925. case float64:
  926. emailToCreated[email] = int64(v)
  927. case int64:
  928. emailToCreated[email] = v
  929. }
  930. switch v := m["updated_at"].(type) {
  931. case float64:
  932. emailToUpdated[email] = int64(v)
  933. case int64:
  934. emailToUpdated[email] = v
  935. }
  936. }
  937. }
  938. }
  939. }
  940. }
  941. var newSettings map[string]any
  942. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  943. now := time.Now().Unix() * 1000
  944. if nSlice, ok := newSettings["clients"].([]any); ok {
  945. for i := range nSlice {
  946. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  947. email, _ := m["email"].(string)
  948. if _, ok3 := m["created_at"]; !ok3 {
  949. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  950. m["created_at"] = v
  951. } else {
  952. m["created_at"] = now
  953. }
  954. }
  955. // Preserve client's updated_at if present; do not bump on parent inbound update
  956. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  957. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  958. m["updated_at"] = v
  959. }
  960. }
  961. nSlice[i] = m
  962. }
  963. }
  964. newSettings["clients"] = nSlice
  965. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  966. inbound.Settings = string(bs)
  967. }
  968. }
  969. }
  970. }
  971. oldInbound.Total = inbound.Total
  972. oldInbound.Remark = inbound.Remark
  973. oldInbound.SubSortIndex = inbound.SubSortIndex
  974. oldInbound.Enable = inbound.Enable
  975. oldInbound.ExpiryTime = inbound.ExpiryTime
  976. oldInbound.TrafficReset = inbound.TrafficReset
  977. oldInbound.Listen = inbound.Listen
  978. oldInbound.Port = inbound.Port
  979. oldInbound.Protocol = inbound.Protocol
  980. oldInbound.Settings = inbound.Settings
  981. oldInbound.StreamSettings = inbound.StreamSettings
  982. oldInbound.Sniffing = inbound.Sniffing
  983. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  984. normalizeInboundShareAddress(oldInbound)
  985. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  986. inbound.ShareAddr = oldInbound.ShareAddr
  987. } else {
  988. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  989. return inbound, false, err
  990. }
  991. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  992. oldInbound.ShareAddr = inbound.ShareAddr
  993. }
  994. if oldTagWasAuto && inbound.Tag == tag {
  995. inbound.Tag = ""
  996. }
  997. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  998. if err != nil {
  999. return inbound, false, err
  1000. }
  1001. inbound.Tag = oldInbound.Tag
  1002. needRestart := false
  1003. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  1004. if perr != nil {
  1005. err = perr
  1006. return inbound, false, err
  1007. }
  1008. if dirty {
  1009. markDirty = true
  1010. }
  1011. if oldInbound.NodeID == nil {
  1012. if !push {
  1013. needRestart = true
  1014. } else {
  1015. oldSnapshot := *oldInbound
  1016. oldSnapshot.Tag = tag
  1017. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1018. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1019. }
  1020. if inbound.Enable {
  1021. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1022. if err2 != nil {
  1023. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1024. needRestart = true
  1025. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1026. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1027. } else {
  1028. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1029. needRestart = true
  1030. }
  1031. }
  1032. }
  1033. } else if push {
  1034. oldSnapshot := *oldInbound
  1035. oldSnapshot.Tag = tag
  1036. if !inbound.Enable {
  1037. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1038. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1039. markDirty = true
  1040. }
  1041. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1042. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1043. markDirty = true
  1044. }
  1045. }
  1046. // A rename must allow the new tag before the deferred commit, or a node in
  1047. // "selected" sync mode would sweep the renamed central row on the next pull.
  1048. if oldInbound.NodeID != nil {
  1049. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1050. logger.Warning("allow inbound tag on node failed:", aErr)
  1051. }
  1052. }
  1053. if err = tx.Save(oldInbound).Error; err != nil {
  1054. return inbound, false, err
  1055. }
  1056. newClients, gcErr := s.GetClients(oldInbound)
  1057. if gcErr != nil {
  1058. err = gcErr
  1059. return inbound, false, err
  1060. }
  1061. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1062. return inbound, false, err
  1063. }
  1064. // (Re)generate the Xray config whenever routing was or is now enabled, so the
  1065. // egress SOCKS bridge is added, moved, or dropped to match the new settings.
  1066. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1067. needRestart = true
  1068. }
  1069. return inbound, needRestart, nil
  1070. }
  1071. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1072. if inbound == nil {
  1073. return nil, fmt.Errorf("inbound is nil")
  1074. }
  1075. runtimeInbound := *inbound
  1076. settings := map[string]any{}
  1077. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1078. return nil, err
  1079. }
  1080. clients, ok := settings["clients"].([]any)
  1081. if !ok {
  1082. return &runtimeInbound, nil
  1083. }
  1084. var clientStats []xray.ClientTraffic
  1085. err := tx.Model(xray.ClientTraffic{}).
  1086. Where("inbound_id = ?", inbound.Id).
  1087. Select("email", "enable").
  1088. Find(&clientStats).Error
  1089. if err != nil {
  1090. return nil, err
  1091. }
  1092. enableMap := make(map[string]bool, len(clientStats))
  1093. for _, clientTraffic := range clientStats {
  1094. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1095. }
  1096. finalClients := make([]any, 0, len(clients))
  1097. for _, client := range clients {
  1098. c, ok := client.(map[string]any)
  1099. if !ok {
  1100. continue
  1101. }
  1102. email, _ := c["email"].(string)
  1103. if enable, exists := enableMap[email]; exists && !enable {
  1104. continue
  1105. }
  1106. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1107. continue
  1108. }
  1109. finalClients = append(finalClients, c)
  1110. }
  1111. settings["clients"] = finalClients
  1112. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. runtimeInbound.Settings = string(modifiedSettings)
  1117. return &runtimeInbound, nil
  1118. }
  1119. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1120. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1121. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1122. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1123. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1124. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1125. oldClients, err := s.GetClients(oldInbound)
  1126. if err != nil {
  1127. return err
  1128. }
  1129. newClients, err := s.GetClients(newInbound)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. // Email is the unique key for ClientTraffic rows. Clients without an
  1134. // email have no stats row to sync — skip them on both sides instead of
  1135. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1136. oldEmails := make(map[string]struct{}, len(oldClients))
  1137. for i := range oldClients {
  1138. if oldClients[i].Email == "" {
  1139. continue
  1140. }
  1141. oldEmails[oldClients[i].Email] = struct{}{}
  1142. }
  1143. newEmails := make(map[string]struct{}, len(newClients))
  1144. for i := range newClients {
  1145. if newClients[i].Email == "" {
  1146. continue
  1147. }
  1148. newEmails[newClients[i].Email] = struct{}{}
  1149. }
  1150. // Drop stats rows for removed emails — but not when a sibling inbound
  1151. // still references the email, since the row is the shared accumulator.
  1152. for i := range oldClients {
  1153. email := oldClients[i].Email
  1154. if email == "" {
  1155. continue
  1156. }
  1157. if _, kept := newEmails[email]; kept {
  1158. continue
  1159. }
  1160. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1161. if err != nil {
  1162. return err
  1163. }
  1164. if stillUsed {
  1165. continue
  1166. }
  1167. if err := s.DelClientStat(tx, email); err != nil {
  1168. return err
  1169. }
  1170. // Keep inbound_client_ips in sync when the inbound edit drops an
  1171. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1172. if err := s.DelClientIPs(tx, email); err != nil {
  1173. return err
  1174. }
  1175. }
  1176. for i := range newClients {
  1177. email := newClients[i].Email
  1178. if email == "" {
  1179. continue
  1180. }
  1181. if _, existed := oldEmails[email]; existed {
  1182. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1183. return err
  1184. }
  1185. continue
  1186. }
  1187. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1188. return err
  1189. }
  1190. }
  1191. return nil
  1192. }
  1193. func (s *InboundService) GetInboundTags() (string, error) {
  1194. db := database.GetDB()
  1195. var inboundTags []string
  1196. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1197. if err != nil && err != gorm.ErrRecordNotFound {
  1198. return "", err
  1199. }
  1200. tags, _ := json.Marshal(inboundTags)
  1201. return string(tags), nil
  1202. }
  1203. func (s *InboundService) GetClientReverseTags() (string, error) {
  1204. db := database.GetDB()
  1205. var inbounds []model.Inbound
  1206. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1207. if err != nil && err != gorm.ErrRecordNotFound {
  1208. return "[]", err
  1209. }
  1210. tagSet := make(map[string]struct{})
  1211. for _, inbound := range inbounds {
  1212. var settings map[string]any
  1213. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1214. continue
  1215. }
  1216. clients, ok := settings["clients"].([]any)
  1217. if !ok {
  1218. continue
  1219. }
  1220. for _, client := range clients {
  1221. clientMap, ok := client.(map[string]any)
  1222. if !ok {
  1223. continue
  1224. }
  1225. reverse, ok := clientMap["reverse"].(map[string]any)
  1226. if !ok {
  1227. continue
  1228. }
  1229. tag, _ := reverse["tag"].(string)
  1230. tag = strings.TrimSpace(tag)
  1231. if tag != "" {
  1232. tagSet[tag] = struct{}{}
  1233. }
  1234. }
  1235. }
  1236. rawTags := make([]string, 0, len(tagSet))
  1237. for tag := range tagSet {
  1238. rawTags = append(rawTags, tag)
  1239. }
  1240. sort.Strings(rawTags)
  1241. result, _ := json.Marshal(rawTags)
  1242. return string(result), nil
  1243. }
  1244. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1245. db := database.GetDB()
  1246. var inbounds []*model.Inbound
  1247. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1248. if err != nil && err != gorm.ErrRecordNotFound {
  1249. return nil, err
  1250. }
  1251. return inbounds, nil
  1252. }