inbound.go 45 KB

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