inbound.go 41 KB

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