1
0

inbound.go 34 KB

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