inbound.go 36 KB

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