inbound.go 34 KB

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