inbound.go 35 KB

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