inbound.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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. // Hosting node; nil for this panel's own inbounds. Lets the clients
  283. // page map a node filter onto inbound IDs (#4997).
  284. NodeId *int `json:"nodeId,omitempty"`
  285. }
  286. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  287. db := database.GetDB()
  288. var rows []struct {
  289. Id int `gorm:"column:id"`
  290. Remark string `gorm:"column:remark"`
  291. Tag string `gorm:"column:tag"`
  292. Protocol string `gorm:"column:protocol"`
  293. Port int `gorm:"column:port"`
  294. StreamSettings string `gorm:"column:stream_settings"`
  295. Settings string `gorm:"column:settings"`
  296. NodeId *int `gorm:"column:node_id"`
  297. }
  298. err := db.Table("inbounds").
  299. Select("id, remark, tag, protocol, port, stream_settings, settings, node_id").
  300. Where("user_id = ?", userId).
  301. Order("id ASC").
  302. Scan(&rows).Error
  303. if err != nil && err != gorm.ErrRecordNotFound {
  304. return nil, err
  305. }
  306. out := make([]InboundOption, 0, len(rows))
  307. for _, r := range rows {
  308. out = append(out, InboundOption{
  309. Id: r.Id,
  310. Remark: r.Remark,
  311. Tag: r.Tag,
  312. Protocol: r.Protocol,
  313. Port: r.Port,
  314. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  315. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  316. NodeId: r.NodeId,
  317. })
  318. }
  319. return out, nil
  320. }
  321. // GetAllInbounds retrieves all inbounds with client stats.
  322. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  323. db := database.GetDB()
  324. var inbounds []*model.Inbound
  325. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  326. if err != nil && err != gorm.ErrRecordNotFound {
  327. return nil, err
  328. }
  329. s.enrichClientStats(db, inbounds)
  330. return inbounds, nil
  331. }
  332. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  333. db := database.GetDB()
  334. var inbounds []*model.Inbound
  335. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  336. if err != nil && err != gorm.ErrRecordNotFound {
  337. return nil, err
  338. }
  339. return inbounds, nil
  340. }
  341. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  342. settings := map[string][]model.Client{}
  343. json.Unmarshal([]byte(inbound.Settings), &settings)
  344. if settings == nil {
  345. return nil, fmt.Errorf("setting is null")
  346. }
  347. clients := settings["clients"]
  348. if clients == nil {
  349. return nil, nil
  350. }
  351. return clients, nil
  352. }
  353. func (s *InboundService) GetAllEmails() ([]string, error) {
  354. db := database.GetDB()
  355. var emails []string
  356. query := fmt.Sprintf(
  357. "SELECT DISTINCT %s %s",
  358. database.JSONFieldText("client.value", "email"),
  359. database.JSONClientsFromInbound(),
  360. )
  361. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  362. return nil, err
  363. }
  364. return emails, nil
  365. }
  366. // getAllEmailSubIDs returns email→subId. An email seen with two different
  367. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  368. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  369. db := database.GetDB()
  370. var rows []struct {
  371. Email string
  372. SubID string
  373. }
  374. query := fmt.Sprintf(
  375. "SELECT %s AS email, %s AS sub_id %s",
  376. database.JSONFieldText("client.value", "email"),
  377. database.JSONFieldText("client.value", "subId"),
  378. database.JSONClientsFromInbound(),
  379. )
  380. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  381. return nil, err
  382. }
  383. result := make(map[string]string, len(rows))
  384. for _, r := range rows {
  385. email := strings.ToLower(r.Email)
  386. if email == "" {
  387. continue
  388. }
  389. subID := r.SubID
  390. if existing, ok := result[email]; ok {
  391. if existing != subID {
  392. result[email] = ""
  393. }
  394. continue
  395. }
  396. result[email] = subID
  397. }
  398. return result, nil
  399. }
  400. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  401. // Only vmess, vless, trojan, shadowsocks, hysteria, and wireguard protocols use
  402. // streamSettings (wireguard for finalmask UDP masks and sockopt on its listener).
  403. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  404. protocolsWithStream := map[model.Protocol]bool{
  405. model.VMESS: true,
  406. model.VLESS: true,
  407. model.Trojan: true,
  408. model.Shadowsocks: true,
  409. model.Hysteria: true,
  410. model.WireGuard: true,
  411. }
  412. if !protocolsWithStream[inbound.Protocol] {
  413. inbound.StreamSettings = ""
  414. }
  415. }
  416. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  417. // always valid and matches the configured domain before the row is persisted.
  418. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  419. if inbound.Protocol != model.MTProto {
  420. return
  421. }
  422. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  423. inbound.Settings = healed
  424. }
  425. }
  426. // AddInbound creates a new inbound configuration.
  427. // It validates port uniqueness, client email uniqueness, and required fields,
  428. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  429. // Returns the created inbound, whether Xray needs restart, and any error.
  430. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  431. // Normalize streamSettings based on protocol
  432. s.normalizeStreamSettings(inbound)
  433. s.normalizeMtprotoSecret(inbound)
  434. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  435. return inbound, false, err
  436. }
  437. conflict, err := s.checkPortConflict(inbound, 0)
  438. if err != nil {
  439. return inbound, false, err
  440. }
  441. if conflict != nil {
  442. return inbound, false, common.NewError(conflict.String())
  443. }
  444. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  445. if err != nil {
  446. return inbound, false, err
  447. }
  448. clients, err := s.GetClients(inbound)
  449. if err != nil {
  450. return inbound, false, err
  451. }
  452. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  453. if err != nil {
  454. return inbound, false, err
  455. }
  456. if existEmail != "" {
  457. return inbound, false, common.NewError("Duplicate email:", existEmail)
  458. }
  459. // Ensure created_at and updated_at on clients in settings
  460. if len(clients) > 0 {
  461. var settings map[string]any
  462. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  463. now := time.Now().Unix() * 1000
  464. updatedClients := make([]model.Client, 0, len(clients))
  465. for _, c := range clients {
  466. if c.CreatedAt == 0 {
  467. c.CreatedAt = now
  468. }
  469. c.UpdatedAt = now
  470. updatedClients = append(updatedClients, c)
  471. }
  472. settings["clients"] = updatedClients
  473. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  474. inbound.Settings = string(bs)
  475. } else {
  476. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  477. }
  478. } else if err2 != nil {
  479. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  480. }
  481. }
  482. // Secure client ID
  483. for _, client := range clients {
  484. switch inbound.Protocol {
  485. case "trojan":
  486. if client.Password == "" {
  487. return inbound, false, common.NewError("empty client ID")
  488. }
  489. case "shadowsocks":
  490. if client.Email == "" {
  491. return inbound, false, common.NewError("empty client ID")
  492. }
  493. case "hysteria":
  494. if client.Auth == "" {
  495. return inbound, false, common.NewError("empty client ID")
  496. }
  497. default:
  498. if client.ID == "" {
  499. return inbound, false, common.NewError("empty client ID")
  500. }
  501. }
  502. }
  503. db := database.GetDB()
  504. tx := db.Begin()
  505. markDirty := false
  506. defer func() {
  507. if err != nil {
  508. tx.Rollback()
  509. return
  510. }
  511. tx.Commit()
  512. if markDirty && inbound.NodeID != nil {
  513. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  514. logger.Warning("mark node dirty failed:", dErr)
  515. }
  516. }
  517. }()
  518. err = tx.Save(inbound).Error
  519. if err == nil {
  520. if len(inbound.ClientStats) == 0 {
  521. for _, client := range clients {
  522. s.AddClientStat(tx, inbound.Id, &client)
  523. }
  524. }
  525. } else {
  526. return inbound, false, err
  527. }
  528. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  529. return inbound, false, err
  530. }
  531. // Before the deferred commit, so a node in "selected" sync mode cannot
  532. // sweep the new central row in the gap before its tag is allowed.
  533. if inbound.NodeID != nil {
  534. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  535. logger.Warning("allow inbound tag on node failed:", aErr)
  536. }
  537. }
  538. needRestart := false
  539. if inbound.Enable {
  540. rt, push, dirty, perr := s.nodePushPlan(inbound)
  541. if perr != nil {
  542. err = perr
  543. return inbound, false, err
  544. }
  545. if dirty {
  546. markDirty = true
  547. }
  548. if push {
  549. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  550. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  551. } else {
  552. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  553. if inbound.NodeID != nil {
  554. markDirty = true
  555. } else {
  556. needRestart = true
  557. }
  558. }
  559. }
  560. }
  561. return inbound, needRestart, err
  562. }
  563. func (s *InboundService) DelInbound(id int) (bool, error) {
  564. db := database.GetDB()
  565. needRestart := false
  566. markDirty := false
  567. var ib model.Inbound
  568. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  569. if loadErr == nil {
  570. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  571. if shouldPushToRuntime {
  572. rt, push, dirty, perr := s.nodePushPlan(&ib)
  573. if perr != nil {
  574. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  575. markDirty = true
  576. } else if push {
  577. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  578. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  579. } else {
  580. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  581. if ib.NodeID == nil {
  582. needRestart = true
  583. } else {
  584. markDirty = true
  585. }
  586. }
  587. } else if ib.NodeID == nil {
  588. needRestart = true
  589. } else if dirty {
  590. markDirty = true
  591. }
  592. } else {
  593. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  594. }
  595. } else {
  596. logger.Debug("DelInbound: inbound not found, id:", id)
  597. }
  598. if err := s.clientService.DetachInbound(db, id); err != nil {
  599. return false, err
  600. }
  601. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  602. return needRestart, err
  603. }
  604. if markDirty && ib.NodeID != nil {
  605. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  606. logger.Warning("mark node dirty failed:", dErr)
  607. }
  608. }
  609. if !database.IsPostgres() {
  610. var count int64
  611. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  612. return needRestart, err
  613. }
  614. if count == 0 {
  615. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  616. return needRestart, err
  617. }
  618. }
  619. }
  620. return needRestart, nil
  621. }
  622. type BulkDelInboundResult struct {
  623. Deleted int `json:"deleted"`
  624. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  625. }
  626. type BulkDelInboundReport struct {
  627. Id int `json:"id"`
  628. Reason string `json:"reason"`
  629. }
  630. // DelInbounds removes every inbound in the list, reusing the single-delete
  631. // path per id. Failures are recorded in Skipped and processing continues for
  632. // the rest; the aggregated needRestart is returned so the caller restarts
  633. // xray at most once.
  634. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  635. result := BulkDelInboundResult{}
  636. needRestart := false
  637. for _, id := range ids {
  638. r, err := s.DelInbound(id)
  639. if err != nil {
  640. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  641. continue
  642. }
  643. result.Deleted++
  644. if r {
  645. needRestart = true
  646. }
  647. }
  648. return result, needRestart, nil
  649. }
  650. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  651. db := database.GetDB()
  652. inbound := &model.Inbound{}
  653. err := db.Model(model.Inbound{}).First(inbound, id).Error
  654. if err != nil {
  655. return nil, err
  656. }
  657. return inbound, nil
  658. }
  659. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  660. db := database.GetDB()
  661. inbound := &model.Inbound{}
  662. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  663. if err != nil {
  664. return nil, err
  665. }
  666. s.enrichClientStats(db, []*model.Inbound{inbound})
  667. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  668. return inbound, nil
  669. }
  670. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  671. inbound, err := s.GetInbound(id)
  672. if err != nil {
  673. return false, err
  674. }
  675. if inbound.Enable == enable {
  676. return false, nil
  677. }
  678. db := database.GetDB()
  679. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  680. Update("enable", enable).Error; err != nil {
  681. return false, err
  682. }
  683. inbound.Enable = enable
  684. needRestart := false
  685. rt, push, dirty, perr := s.nodePushPlan(inbound)
  686. if perr != nil {
  687. return false, perr
  688. }
  689. // Remote nodes interpret DelInbound as a real row delete (it hits
  690. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  691. // switch on a remote inbound used to wipe the row entirely (#4402).
  692. // PATCH the remote row via UpdateInbound instead — preserves the
  693. // settings/client history and just flips the enable flag.
  694. if inbound.NodeID != nil {
  695. if push {
  696. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  697. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  698. dirty = true
  699. }
  700. }
  701. if dirty {
  702. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  703. logger.Warning("mark node dirty failed:", dErr)
  704. }
  705. }
  706. return false, nil
  707. }
  708. if !push {
  709. return true, nil
  710. }
  711. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  712. !strings.Contains(err.Error(), "not found") {
  713. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  714. needRestart = true
  715. }
  716. if !enable {
  717. return needRestart, nil
  718. }
  719. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  720. if err != nil {
  721. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  722. return true, nil
  723. }
  724. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  725. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  726. needRestart = true
  727. }
  728. return needRestart, nil
  729. }
  730. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  731. // Normalize streamSettings based on protocol
  732. s.normalizeStreamSettings(inbound)
  733. s.normalizeMtprotoSecret(inbound)
  734. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  735. if err != nil {
  736. return inbound, false, err
  737. }
  738. if conflict != nil {
  739. return inbound, false, common.NewError(conflict.String())
  740. }
  741. oldInbound, err := s.GetInbound(inbound.Id)
  742. if err != nil {
  743. return inbound, false, err
  744. }
  745. inbound.NodeID = oldInbound.NodeID
  746. tag := oldInbound.Tag
  747. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  748. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  749. db := database.GetDB()
  750. tx := db.Begin()
  751. markDirty := false
  752. defer func() {
  753. if err != nil {
  754. tx.Rollback()
  755. return
  756. }
  757. tx.Commit()
  758. if markDirty && oldInbound.NodeID != nil {
  759. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  760. logger.Warning("mark node dirty failed:", dErr)
  761. }
  762. }
  763. }()
  764. err = s.updateClientTraffics(tx, oldInbound, inbound)
  765. if err != nil {
  766. return inbound, false, err
  767. }
  768. // Ensure created_at and updated_at exist in inbound.Settings clients
  769. {
  770. var oldSettings map[string]any
  771. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  772. emailToCreated := map[string]int64{}
  773. emailToUpdated := map[string]int64{}
  774. if oldSettings != nil {
  775. if oc, ok := oldSettings["clients"].([]any); ok {
  776. for _, it := range oc {
  777. if m, ok2 := it.(map[string]any); ok2 {
  778. if email, ok3 := m["email"].(string); ok3 {
  779. switch v := m["created_at"].(type) {
  780. case float64:
  781. emailToCreated[email] = int64(v)
  782. case int64:
  783. emailToCreated[email] = v
  784. }
  785. switch v := m["updated_at"].(type) {
  786. case float64:
  787. emailToUpdated[email] = int64(v)
  788. case int64:
  789. emailToUpdated[email] = v
  790. }
  791. }
  792. }
  793. }
  794. }
  795. }
  796. var newSettings map[string]any
  797. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  798. now := time.Now().Unix() * 1000
  799. if nSlice, ok := newSettings["clients"].([]any); ok {
  800. for i := range nSlice {
  801. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  802. email, _ := m["email"].(string)
  803. if _, ok3 := m["created_at"]; !ok3 {
  804. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  805. m["created_at"] = v
  806. } else {
  807. m["created_at"] = now
  808. }
  809. }
  810. // Preserve client's updated_at if present; do not bump on parent inbound update
  811. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  812. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  813. m["updated_at"] = v
  814. }
  815. }
  816. nSlice[i] = m
  817. }
  818. }
  819. newSettings["clients"] = nSlice
  820. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  821. inbound.Settings = string(bs)
  822. }
  823. }
  824. }
  825. }
  826. oldInbound.Total = inbound.Total
  827. oldInbound.Remark = inbound.Remark
  828. oldInbound.Enable = inbound.Enable
  829. oldInbound.ExpiryTime = inbound.ExpiryTime
  830. oldInbound.TrafficReset = inbound.TrafficReset
  831. oldInbound.Listen = inbound.Listen
  832. oldInbound.Port = inbound.Port
  833. oldInbound.Protocol = inbound.Protocol
  834. oldInbound.Settings = inbound.Settings
  835. oldInbound.StreamSettings = inbound.StreamSettings
  836. oldInbound.Sniffing = inbound.Sniffing
  837. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  838. normalizeInboundShareAddress(oldInbound)
  839. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  840. inbound.ShareAddr = oldInbound.ShareAddr
  841. } else {
  842. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  843. return inbound, false, err
  844. }
  845. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  846. oldInbound.ShareAddr = inbound.ShareAddr
  847. }
  848. if oldTagWasAuto && inbound.Tag == tag {
  849. inbound.Tag = ""
  850. }
  851. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  852. if err != nil {
  853. return inbound, false, err
  854. }
  855. inbound.Tag = oldInbound.Tag
  856. needRestart := false
  857. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  858. if perr != nil {
  859. err = perr
  860. return inbound, false, err
  861. }
  862. if dirty {
  863. markDirty = true
  864. }
  865. if oldInbound.NodeID == nil {
  866. if !push {
  867. needRestart = true
  868. } else {
  869. oldSnapshot := *oldInbound
  870. oldSnapshot.Tag = tag
  871. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  872. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  873. }
  874. if inbound.Enable {
  875. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  876. if err2 != nil {
  877. logger.Debug("Unable to prepare runtime inbound config:", err2)
  878. needRestart = true
  879. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  880. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  881. } else {
  882. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  883. needRestart = true
  884. }
  885. }
  886. }
  887. } else if push {
  888. oldSnapshot := *oldInbound
  889. oldSnapshot.Tag = tag
  890. if !inbound.Enable {
  891. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  892. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  893. markDirty = true
  894. }
  895. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  896. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  897. markDirty = true
  898. }
  899. }
  900. // A rename must allow the new tag before the deferred commit, or a node in
  901. // "selected" sync mode would sweep the renamed central row on the next pull.
  902. if oldInbound.NodeID != nil {
  903. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  904. logger.Warning("allow inbound tag on node failed:", aErr)
  905. }
  906. }
  907. if err = tx.Save(oldInbound).Error; err != nil {
  908. return inbound, false, err
  909. }
  910. newClients, gcErr := s.GetClients(oldInbound)
  911. if gcErr != nil {
  912. err = gcErr
  913. return inbound, false, err
  914. }
  915. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  916. return inbound, false, err
  917. }
  918. return inbound, needRestart, nil
  919. }
  920. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  921. if inbound == nil {
  922. return nil, fmt.Errorf("inbound is nil")
  923. }
  924. runtimeInbound := *inbound
  925. settings := map[string]any{}
  926. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  927. return nil, err
  928. }
  929. clients, ok := settings["clients"].([]any)
  930. if !ok {
  931. return &runtimeInbound, nil
  932. }
  933. var clientStats []xray.ClientTraffic
  934. err := tx.Model(xray.ClientTraffic{}).
  935. Where("inbound_id = ?", inbound.Id).
  936. Select("email", "enable").
  937. Find(&clientStats).Error
  938. if err != nil {
  939. return nil, err
  940. }
  941. enableMap := make(map[string]bool, len(clientStats))
  942. for _, clientTraffic := range clientStats {
  943. enableMap[clientTraffic.Email] = clientTraffic.Enable
  944. }
  945. finalClients := make([]any, 0, len(clients))
  946. for _, client := range clients {
  947. c, ok := client.(map[string]any)
  948. if !ok {
  949. continue
  950. }
  951. email, _ := c["email"].(string)
  952. if enable, exists := enableMap[email]; exists && !enable {
  953. continue
  954. }
  955. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  956. continue
  957. }
  958. finalClients = append(finalClients, c)
  959. }
  960. settings["clients"] = finalClients
  961. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  962. if err != nil {
  963. return nil, err
  964. }
  965. runtimeInbound.Settings = string(modifiedSettings)
  966. return &runtimeInbound, nil
  967. }
  968. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  969. // list: removes rows for emails that disappeared, inserts rows for newly-added
  970. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  971. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  972. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  973. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  974. oldClients, err := s.GetClients(oldInbound)
  975. if err != nil {
  976. return err
  977. }
  978. newClients, err := s.GetClients(newInbound)
  979. if err != nil {
  980. return err
  981. }
  982. // Email is the unique key for ClientTraffic rows. Clients without an
  983. // email have no stats row to sync — skip them on both sides instead of
  984. // risking a unique-constraint hit or accidental delete of an unrelated row.
  985. oldEmails := make(map[string]struct{}, len(oldClients))
  986. for i := range oldClients {
  987. if oldClients[i].Email == "" {
  988. continue
  989. }
  990. oldEmails[oldClients[i].Email] = struct{}{}
  991. }
  992. newEmails := make(map[string]struct{}, len(newClients))
  993. for i := range newClients {
  994. if newClients[i].Email == "" {
  995. continue
  996. }
  997. newEmails[newClients[i].Email] = struct{}{}
  998. }
  999. // Drop stats rows for removed emails — but not when a sibling inbound
  1000. // still references the email, since the row is the shared accumulator.
  1001. for i := range oldClients {
  1002. email := oldClients[i].Email
  1003. if email == "" {
  1004. continue
  1005. }
  1006. if _, kept := newEmails[email]; kept {
  1007. continue
  1008. }
  1009. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1010. if err != nil {
  1011. return err
  1012. }
  1013. if stillUsed {
  1014. continue
  1015. }
  1016. if err := s.DelClientStat(tx, email); err != nil {
  1017. return err
  1018. }
  1019. // Keep inbound_client_ips in sync when the inbound edit drops an
  1020. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1021. if err := s.DelClientIPs(tx, email); err != nil {
  1022. return err
  1023. }
  1024. }
  1025. for i := range newClients {
  1026. email := newClients[i].Email
  1027. if email == "" {
  1028. continue
  1029. }
  1030. if _, existed := oldEmails[email]; existed {
  1031. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1032. return err
  1033. }
  1034. continue
  1035. }
  1036. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1037. return err
  1038. }
  1039. }
  1040. return nil
  1041. }
  1042. func (s *InboundService) GetInboundTags() (string, error) {
  1043. db := database.GetDB()
  1044. var inboundTags []string
  1045. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1046. if err != nil && err != gorm.ErrRecordNotFound {
  1047. return "", err
  1048. }
  1049. tags, _ := json.Marshal(inboundTags)
  1050. return string(tags), nil
  1051. }
  1052. func (s *InboundService) GetClientReverseTags() (string, error) {
  1053. db := database.GetDB()
  1054. var inbounds []model.Inbound
  1055. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1056. if err != nil && err != gorm.ErrRecordNotFound {
  1057. return "[]", err
  1058. }
  1059. tagSet := make(map[string]struct{})
  1060. for _, inbound := range inbounds {
  1061. var settings map[string]any
  1062. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1063. continue
  1064. }
  1065. clients, ok := settings["clients"].([]any)
  1066. if !ok {
  1067. continue
  1068. }
  1069. for _, client := range clients {
  1070. clientMap, ok := client.(map[string]any)
  1071. if !ok {
  1072. continue
  1073. }
  1074. reverse, ok := clientMap["reverse"].(map[string]any)
  1075. if !ok {
  1076. continue
  1077. }
  1078. tag, _ := reverse["tag"].(string)
  1079. tag = strings.TrimSpace(tag)
  1080. if tag != "" {
  1081. tagSet[tag] = struct{}{}
  1082. }
  1083. }
  1084. }
  1085. rawTags := make([]string, 0, len(tagSet))
  1086. for tag := range tagSet {
  1087. rawTags = append(rawTags, tag)
  1088. }
  1089. sort.Strings(rawTags)
  1090. result, _ := json.Marshal(rawTags)
  1091. return string(result), nil
  1092. }
  1093. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1094. db := database.GetDB()
  1095. var inbounds []*model.Inbound
  1096. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1097. if err != nil && err != gorm.ErrRecordNotFound {
  1098. return nil, err
  1099. }
  1100. return inbounds, nil
  1101. }