inbound.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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. Enable bool `json:"enable" example:"true"`
  285. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  286. SsMethod string `json:"ssMethod"`
  287. WgPublicKey string `json:"wgPublicKey,omitempty"`
  288. WgMtu int `json:"wgMtu,omitempty"`
  289. WgDns string `json:"wgDns,omitempty"`
  290. MtprotoDomain string `json:"mtprotoDomain,omitempty"`
  291. // Hosting node; nil for this panel's own inbounds. Lets the clients
  292. // page map a node filter onto inbound IDs (#4997).
  293. NodeId *int `json:"nodeId,omitempty"`
  294. // Share-host resolution inputs, mirroring the subscription's
  295. // resolveInboundAddress so the clients page renders a node-managed WireGuard
  296. // Endpoint that points at the node, not the master panel. NodeAddress is the
  297. // hosting node's externally reachable address (empty for this panel's own
  298. // inbounds); Listen and ShareAddrStrategy/ShareAddr feed the same
  299. // node→listen→custom fallback the share/QR links already use.
  300. NodeAddress string `json:"nodeAddress,omitempty"`
  301. Listen string `json:"listen,omitempty"`
  302. ShareAddr string `json:"shareAddr,omitempty"`
  303. ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
  304. }
  305. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  306. db := database.GetDB()
  307. var rows []struct {
  308. Id int `gorm:"column:id"`
  309. Remark string `gorm:"column:remark"`
  310. Tag string `gorm:"column:tag"`
  311. Protocol string `gorm:"column:protocol"`
  312. Port int `gorm:"column:port"`
  313. Enable bool `gorm:"column:enable"`
  314. StreamSettings string `gorm:"column:stream_settings"`
  315. Settings string `gorm:"column:settings"`
  316. Listen string `gorm:"column:listen"`
  317. ShareAddr string `gorm:"column:share_addr"`
  318. ShareAddrStrategy string `gorm:"column:share_addr_strategy"`
  319. NodeId *int `gorm:"column:node_id"`
  320. NodeAddress string `gorm:"column:node_address"`
  321. }
  322. err := db.Table("inbounds").
  323. Select("inbounds.id, inbounds.remark, inbounds.tag, inbounds.protocol, inbounds.port, inbounds.enable, inbounds.stream_settings, inbounds.settings, inbounds.listen, inbounds.share_addr, inbounds.share_addr_strategy, inbounds.node_id, COALESCE(nodes.address, '') AS node_address").
  324. Joins("LEFT JOIN nodes ON nodes.id = inbounds.node_id").
  325. Where("inbounds.user_id = ?", userId).
  326. Order("inbounds.id ASC").
  327. Scan(&rows).Error
  328. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  329. return nil, err
  330. }
  331. out := make([]InboundOption, 0, len(rows))
  332. for _, r := range rows {
  333. wgPublicKey, wgMtu, wgDns := inboundWireguardHints(r.Protocol, r.Settings)
  334. shareAddrStrategy := r.ShareAddrStrategy
  335. if shareAddrStrategy == "node" {
  336. shareAddrStrategy = ""
  337. }
  338. out = append(out, InboundOption{
  339. Id: r.Id,
  340. Remark: r.Remark,
  341. Tag: r.Tag,
  342. Protocol: r.Protocol,
  343. Port: r.Port,
  344. Enable: r.Enable,
  345. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  346. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  347. WgPublicKey: wgPublicKey,
  348. WgMtu: wgMtu,
  349. WgDns: wgDns,
  350. MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
  351. NodeId: r.NodeId,
  352. NodeAddress: r.NodeAddress,
  353. Listen: r.Listen,
  354. ShareAddr: r.ShareAddr,
  355. ShareAddrStrategy: shareAddrStrategy,
  356. })
  357. }
  358. return out, nil
  359. }
  360. func inboundWireguardHints(protocol string, settings string) (string, int, string) {
  361. if protocol != string(model.WireGuard) || strings.TrimSpace(settings) == "" {
  362. return "", 0, ""
  363. }
  364. var parsed struct {
  365. PublicKey string `json:"publicKey"`
  366. PubKey string `json:"pubKey"`
  367. SecretKey string `json:"secretKey"`
  368. MTU int `json:"mtu"`
  369. DNS string `json:"dns"`
  370. }
  371. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  372. return "", 0, ""
  373. }
  374. publicKey := parsed.PublicKey
  375. if publicKey == "" {
  376. publicKey = parsed.PubKey
  377. }
  378. if publicKey == "" && parsed.SecretKey != "" {
  379. if derived, err := wgutil.PublicKeyFromPrivate(parsed.SecretKey); err == nil {
  380. publicKey = derived
  381. }
  382. }
  383. return publicKey, parsed.MTU, parsed.DNS
  384. }
  385. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  386. // the clients UI to seed a new mtproto client's secret with the right fronting
  387. // hostname.
  388. func inboundMtprotoDomain(protocol string, settings string) string {
  389. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  390. return ""
  391. }
  392. var parsed struct {
  393. FakeTLSDomain string `json:"fakeTlsDomain"`
  394. }
  395. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  396. return ""
  397. }
  398. return strings.TrimSpace(parsed.FakeTLSDomain)
  399. }
  400. // GetAllInbounds retrieves all inbounds with client stats.
  401. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  402. db := database.GetDB()
  403. var inbounds []*model.Inbound
  404. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  405. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  406. return nil, err
  407. }
  408. s.enrichClientStats(db, inbounds)
  409. return inbounds, nil
  410. }
  411. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  412. db := database.GetDB()
  413. var inbounds []*model.Inbound
  414. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  415. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  416. return nil, err
  417. }
  418. return inbounds, nil
  419. }
  420. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  421. return ParseInboundSettingsClients(inbound.Settings)
  422. }
  423. // GetClientsBySubId returns the inbound's clients with the given subscription
  424. // id, resolved from the normalized clients tables (the same source the running
  425. // Xray users are built from) instead of parsing the settings JSON blob.
  426. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  427. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  428. }
  429. func (s *InboundService) GetAllEmails() ([]string, error) {
  430. db := database.GetDB()
  431. var emails []string
  432. query := fmt.Sprintf(
  433. "SELECT DISTINCT %s %s",
  434. database.JSONFieldText("client.value", "email"),
  435. database.JSONClientsFromInbound(),
  436. )
  437. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  438. return nil, err
  439. }
  440. return emails, nil
  441. }
  442. // getAllEmailSubIDs returns email→subId. An email seen with two different
  443. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  444. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  445. db := database.GetDB()
  446. var rows []struct {
  447. Email string
  448. SubID string
  449. }
  450. query := fmt.Sprintf(
  451. "SELECT %s AS email, %s AS sub_id %s",
  452. database.JSONFieldText("client.value", "email"),
  453. database.JSONFieldText("client.value", "subId"),
  454. database.JSONClientsFromInbound(),
  455. )
  456. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  457. return nil, err
  458. }
  459. result := make(map[string]string, len(rows))
  460. for _, r := range rows {
  461. email := strings.ToLower(r.Email)
  462. if email == "" {
  463. continue
  464. }
  465. subID := r.SubID
  466. if existing, ok := result[email]; ok {
  467. if existing != subID {
  468. result[email] = ""
  469. }
  470. continue
  471. }
  472. result[email] = subID
  473. }
  474. return result, nil
  475. }
  476. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  477. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  478. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  479. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  480. // mode).
  481. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  482. protocolsWithStream := map[model.Protocol]bool{
  483. model.VMESS: true,
  484. model.VLESS: true,
  485. model.Trojan: true,
  486. model.Shadowsocks: true,
  487. model.Hysteria: true,
  488. model.WireGuard: true,
  489. model.Tunnel: true,
  490. }
  491. if !protocolsWithStream[inbound.Protocol] {
  492. inbound.StreamSettings = ""
  493. }
  494. }
  495. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  496. // stream uses REALITY security, or nil otherwise. A non-empty result means
  497. // this stream carries the finalmask+REALITY combination that panics
  498. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  499. // wraps the connection before REALITY's handshake ever sees it, and
  500. // reality.Server() does an unchecked type assertion assuming a raw
  501. // *net.TCPConn, which panics once finalmask is in front of it.
  502. //
  503. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  504. // listener ahead of REALITY's handshake, in xray-core's own
  505. // transport/internet/memory_settings.go) is only constructed when tcp masks
  506. // are present; a finalmask.udp-only config never touches the TCP accept path
  507. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  508. // rejected.
  509. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  510. if stream["security"] != "reality" {
  511. return nil
  512. }
  513. finalmask, ok := stream["finalmask"].(map[string]any)
  514. if !ok {
  515. return nil
  516. }
  517. tcp, _ := finalmask["tcp"].([]any)
  518. return tcp
  519. }
  520. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  521. // with REALITY security at save time. Upstream has confirmed this
  522. // combination will be documented as unsupported rather than made graceful,
  523. // so the panel must not let it be saved.
  524. func validateFinalMaskRealityCombo(streamSettings string) error {
  525. if streamSettings == "" {
  526. return nil
  527. }
  528. var stream map[string]any
  529. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  530. return nil
  531. }
  532. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  533. return nil
  534. }
  535. return common.NewError("Finalmask is not supported with REALITY security — it crashes Xray-core on the first connection (see XTLS/Xray-core#6453). Remove the finalmask configuration or switch security to tls/none.")
  536. }
  537. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  538. // always valid before the row is persisted, and drops the vestigial inbound-level
  539. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  540. // only the per-client values. Leaving an inbound-level secret behind is what
  541. // produced stale links that failed with "incorrect client random".
  542. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  543. if inbound.Protocol != model.MTProto {
  544. return
  545. }
  546. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  547. inbound.Settings = stripped
  548. }
  549. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  550. inbound.Settings = stripped
  551. }
  552. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  553. inbound.Settings = healed
  554. }
  555. }
  556. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  557. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  558. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  559. if inbound == nil || inbound.Protocol != model.MTProto {
  560. return false
  561. }
  562. var parsed struct {
  563. RouteThroughXray bool `json:"routeThroughXray"`
  564. }
  565. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  566. return false
  567. }
  568. return parsed.RouteThroughXray
  569. }
  570. func settingsRouteXrayPort(parsed map[string]any) int {
  571. switch v := parsed["routeXrayPort"].(type) {
  572. case float64:
  573. return int(v)
  574. case int:
  575. return v
  576. case json.Number:
  577. if n, err := v.Int64(); err == nil {
  578. return int(n)
  579. }
  580. }
  581. return 0
  582. }
  583. func parseRouteXrayPort(settings string) int {
  584. if settings == "" {
  585. return 0
  586. }
  587. var parsed map[string]any
  588. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  589. return 0
  590. }
  591. return settingsRouteXrayPort(parsed)
  592. }
  593. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  594. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  595. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  596. // allocated once when routing is first enabled and preserved across edits
  597. // (carried over from oldSettings, which wins over any value the client echoed
  598. // back). When routing is off it — together with the now-inert outbound
  599. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  600. //
  601. // It returns an error when an egress port cannot be allocated or persisted, so
  602. // the caller refuses the save rather than storing a routed-but-portless inbound,
  603. // which would otherwise route no traffic and have its mtg metrics skipped (see
  604. // mtproto_job) — silently losing its accounting.
  605. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  606. if inbound.Protocol != model.MTProto {
  607. return nil
  608. }
  609. var parsed map[string]any
  610. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  611. return nil
  612. }
  613. routed, _ := parsed["routeThroughXray"].(bool)
  614. if !routed {
  615. _, hadPort := parsed["routeXrayPort"]
  616. _, hadTag := parsed["outboundTag"]
  617. if !hadPort && !hadTag {
  618. return nil
  619. }
  620. delete(parsed, "routeXrayPort")
  621. delete(parsed, "outboundTag")
  622. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  623. inbound.Settings = string(bs)
  624. } else {
  625. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  626. }
  627. return nil
  628. }
  629. // Prefer the already-stored port (carried across edits), then any value the
  630. // client sent, then allocate a fresh one.
  631. port := parseRouteXrayPort(oldSettings)
  632. if port <= 0 {
  633. port = settingsRouteXrayPort(parsed)
  634. }
  635. if port <= 0 {
  636. allocated, err := mtproto.FreeLocalPort()
  637. if err != nil {
  638. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  639. }
  640. port = allocated
  641. }
  642. if settingsRouteXrayPort(parsed) == port {
  643. return nil
  644. }
  645. parsed["routeXrayPort"] = port
  646. bs, err := json.MarshalIndent(parsed, "", " ")
  647. if err != nil {
  648. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  649. }
  650. inbound.Settings = string(bs)
  651. return nil
  652. }
  653. // AddInbound creates a new inbound configuration.
  654. // It validates port uniqueness, client email uniqueness, and required fields,
  655. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  656. // Returns the created inbound, whether Xray needs restart, and any error.
  657. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  658. // Normalize streamSettings based on protocol
  659. s.normalizeStreamSettings(inbound)
  660. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  661. return inbound, false, err
  662. }
  663. s.normalizeMtprotoSecret(inbound)
  664. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  665. return inbound, false, err
  666. }
  667. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  668. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  669. return inbound, false, err
  670. }
  671. conflict, err := s.checkPortConflict(inbound, 0)
  672. if err != nil {
  673. return inbound, false, err
  674. }
  675. if conflict != nil {
  676. return inbound, false, common.NewError(conflict.String())
  677. }
  678. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  679. if err != nil {
  680. return inbound, false, err
  681. }
  682. clients, err := s.GetClients(inbound)
  683. if err != nil {
  684. return inbound, false, err
  685. }
  686. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  687. if err != nil {
  688. return inbound, false, err
  689. }
  690. if existEmail != "" {
  691. return inbound, false, common.NewError("Duplicate email:", existEmail)
  692. }
  693. // Ensure created_at and updated_at on clients in settings
  694. if len(clients) > 0 {
  695. var settings map[string]any
  696. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  697. now := time.Now().Unix() * 1000
  698. updatedClients := make([]model.Client, 0, len(clients))
  699. for _, c := range clients {
  700. if c.CreatedAt == 0 {
  701. c.CreatedAt = now
  702. }
  703. c.UpdatedAt = now
  704. updatedClients = append(updatedClients, c)
  705. }
  706. settings["clients"] = updatedClients
  707. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  708. inbound.Settings = string(bs)
  709. } else {
  710. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  711. }
  712. } else if err2 != nil {
  713. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  714. }
  715. }
  716. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  717. // the inbound method (e.g. an API caller supplied a wrong-size key).
  718. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  719. inbound.Settings = normalized
  720. }
  721. // Secure client ID
  722. for _, client := range clients {
  723. switch inbound.Protocol {
  724. case "trojan":
  725. if client.Password == "" {
  726. return inbound, false, common.NewError("empty client ID")
  727. }
  728. case "shadowsocks":
  729. if client.Email == "" {
  730. return inbound, false, common.NewError("empty client ID")
  731. }
  732. case "hysteria":
  733. if client.Auth == "" {
  734. return inbound, false, common.NewError("empty client ID")
  735. }
  736. case "mtproto":
  737. if client.Secret == "" {
  738. return inbound, false, common.NewError("mtproto client requires a secret")
  739. }
  740. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  741. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  742. }
  743. default:
  744. if client.ID == "" {
  745. return inbound, false, common.NewError("empty client ID")
  746. }
  747. }
  748. }
  749. db := database.GetDB()
  750. tx := db.Begin()
  751. markDirty := false
  752. defer func() {
  753. if err != nil {
  754. tx.Rollback()
  755. return
  756. }
  757. if markDirty && inbound.NodeID != nil {
  758. if dErr := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); dErr != nil {
  759. err = dErr
  760. tx.Rollback()
  761. return
  762. }
  763. }
  764. tx.Commit()
  765. }()
  766. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  767. // those rows with an ON CONFLICT target on the primary key only, which
  768. // collides with the globally-unique client_traffics.email when an imported
  769. // inbound carries clients that another inbound already created (e.g.
  770. // importing two inbounds that share the same clients). We insert the stats
  771. // ourselves below with the same email-conflict guard AddClientStat uses.
  772. err = tx.Omit("ClientStats").Save(inbound).Error
  773. if err != nil {
  774. return inbound, false, err
  775. }
  776. // Imported stats first, so their traffic counters survive; emails that
  777. // already own a (shared) row are skipped instead of tripping the unique
  778. // constraint.
  779. for i := range inbound.ClientStats {
  780. if inbound.ClientStats[i].Email == "" {
  781. continue
  782. }
  783. inbound.ClientStats[i].Id = 0
  784. inbound.ClientStats[i].InboundId = inbound.Id
  785. if err = tx.Clauses(clause.OnConflict{
  786. Columns: []clause.Column{{Name: "email"}},
  787. DoNothing: true,
  788. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  789. return inbound, false, err
  790. }
  791. }
  792. // Then make sure every client has a stats row. AddClientStat is a no-op
  793. // where one exists (including the rows just inserted), and fills the gap
  794. // for clients an import payload didn't carry stats for.
  795. for _, client := range clients {
  796. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  797. return inbound, false, err
  798. }
  799. }
  800. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  801. return inbound, false, err
  802. }
  803. // Legacy import: an inbound exported from a build that predated the hosts
  804. // table carries its external proxies inline in streamSettings.externalProxy.
  805. // The startup migration that converts those to host rows runs once and is
  806. // gated off afterwards, so it never sees a freshly imported inbound —
  807. // reproduce it here. No-op for inbounds without externalProxy (everything the
  808. // current UI builds), so this only fires on such imports.
  809. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  810. return inbound, false, err
  811. }
  812. // Before the deferred commit, so a node in "selected" sync mode cannot
  813. // sweep the new central row in the gap before its tag is allowed.
  814. if inbound.NodeID != nil {
  815. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  816. logger.Warning("allow inbound tag on node failed:", aErr)
  817. }
  818. }
  819. needRestart := false
  820. if inbound.Enable {
  821. rt, push, dirty, perr := s.nodePushPlan(inbound)
  822. if perr != nil {
  823. err = perr
  824. return inbound, false, err
  825. }
  826. if dirty {
  827. markDirty = true
  828. }
  829. if push {
  830. payload := inbound
  831. pushable := true
  832. if inbound.NodeID == nil && inbound.Protocol == model.MTProto {
  833. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  834. payload = built
  835. } else {
  836. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  837. pushable = false
  838. }
  839. }
  840. if pushable {
  841. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  842. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  843. } else {
  844. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  845. if inbound.NodeID != nil {
  846. markDirty = true
  847. } else if inbound.Protocol != model.MTProto {
  848. needRestart = true
  849. }
  850. }
  851. }
  852. }
  853. }
  854. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  855. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  856. // in the generated config, so force a regen to wire it in.
  857. if mtprotoRoutesThroughXray(inbound) {
  858. needRestart = true
  859. }
  860. return inbound, needRestart, err
  861. }
  862. func (s *InboundService) DelInbound(id int) (bool, error) {
  863. db := database.GetDB()
  864. needRestart := false
  865. markDirty := false
  866. var ib model.Inbound
  867. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  868. if loadErr == nil {
  869. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  870. if shouldPushToRuntime {
  871. rt, push, dirty, perr := s.nodePushPlan(&ib)
  872. if perr != nil {
  873. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  874. markDirty = true
  875. } else if push {
  876. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  877. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  878. } else {
  879. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  880. if ib.NodeID == nil {
  881. needRestart = true
  882. } else {
  883. markDirty = true
  884. }
  885. }
  886. } else if ib.NodeID == nil {
  887. needRestart = true
  888. } else if dirty {
  889. markDirty = true
  890. }
  891. } else {
  892. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  893. }
  894. } else {
  895. logger.Debug("DelInbound: inbound not found, id:", id)
  896. }
  897. if err := s.clientService.DetachInbound(db, id); err != nil {
  898. return false, err
  899. }
  900. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  901. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  902. if loadErr == nil && ib.Tag != "" {
  903. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  904. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  905. } else if routingChanged {
  906. needRestart = true
  907. }
  908. }
  909. if err := db.Transaction(func(tx *gorm.DB) error {
  910. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  911. return err
  912. }
  913. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  914. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  915. return err
  916. }
  917. if markDirty && ib.NodeID != nil {
  918. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  919. }
  920. return nil
  921. }); err != nil {
  922. return needRestart, err
  923. }
  924. if !database.IsPostgres() {
  925. var count int64
  926. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  927. return needRestart, err
  928. }
  929. if count == 0 {
  930. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  931. return needRestart, err
  932. }
  933. }
  934. }
  935. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  936. if mtprotoRoutesThroughXray(&ib) {
  937. needRestart = true
  938. }
  939. return needRestart, nil
  940. }
  941. type BulkDelInboundResult struct {
  942. Deleted int `json:"deleted"`
  943. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  944. }
  945. type BulkDelInboundReport struct {
  946. Id int `json:"id"`
  947. Reason string `json:"reason"`
  948. }
  949. // DelInbounds removes every inbound in the list, reusing the single-delete
  950. // path per id. Failures are recorded in Skipped and processing continues for
  951. // the rest; the aggregated needRestart is returned so the caller restarts
  952. // xray at most once.
  953. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  954. result := BulkDelInboundResult{}
  955. needRestart := false
  956. for _, id := range ids {
  957. r, err := s.DelInbound(id)
  958. if err != nil {
  959. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  960. continue
  961. }
  962. result.Deleted++
  963. if r {
  964. needRestart = true
  965. }
  966. }
  967. return result, needRestart, nil
  968. }
  969. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  970. db := database.GetDB()
  971. inbound := &model.Inbound{}
  972. err := db.Model(model.Inbound{}).First(inbound, id).Error
  973. if err != nil {
  974. return nil, err
  975. }
  976. return inbound, nil
  977. }
  978. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  979. db := database.GetDB()
  980. inbound := &model.Inbound{}
  981. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  982. if err != nil {
  983. return nil, err
  984. }
  985. s.enrichClientStats(db, []*model.Inbound{inbound})
  986. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  987. return inbound, nil
  988. }
  989. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  990. inbound, err := s.GetInbound(id)
  991. if err != nil {
  992. return false, err
  993. }
  994. if inbound.Enable == enable {
  995. return false, nil
  996. }
  997. db := database.GetDB()
  998. if err := db.Transaction(func(tx *gorm.DB) error {
  999. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1000. Update("enable", enable).Error; err != nil {
  1001. return err
  1002. }
  1003. if inbound.NodeID != nil {
  1004. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1005. }
  1006. return nil
  1007. }); err != nil {
  1008. return false, err
  1009. }
  1010. inbound.Enable = enable
  1011. needRestart := false
  1012. rt, push, _, perr := s.nodePushPlan(inbound)
  1013. if perr != nil {
  1014. return false, perr
  1015. }
  1016. // Remote nodes interpret DelInbound as a real row delete (it hits
  1017. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1018. // switch on a remote inbound used to wipe the row entirely (#4402).
  1019. // PATCH the remote row via UpdateInbound instead — preserves the
  1020. // settings/client history and just flips the enable flag.
  1021. if inbound.NodeID != nil {
  1022. if push {
  1023. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1024. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1025. }
  1026. }
  1027. return false, nil
  1028. }
  1029. if !push {
  1030. return true, nil
  1031. }
  1032. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1033. !strings.Contains(err.Error(), "not found") {
  1034. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1035. needRestart = true
  1036. }
  1037. if !enable {
  1038. return needRestart, nil
  1039. }
  1040. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  1041. if err != nil {
  1042. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1043. return true, nil
  1044. }
  1045. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1046. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1047. needRestart = true
  1048. }
  1049. return needRestart, nil
  1050. }
  1051. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1052. // Normalize streamSettings based on protocol
  1053. s.normalizeStreamSettings(inbound)
  1054. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1055. return inbound, false, err
  1056. }
  1057. s.normalizeMtprotoSecret(inbound)
  1058. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1059. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1060. if err != nil {
  1061. return inbound, false, err
  1062. }
  1063. if conflict != nil {
  1064. return inbound, false, common.NewError(conflict.String())
  1065. }
  1066. oldInbound, err := s.GetInbound(inbound.Id)
  1067. if err != nil {
  1068. return inbound, false, err
  1069. }
  1070. inbound.NodeID = oldInbound.NodeID
  1071. // Capture the pre-edit protocol and routing state before oldInbound is
  1072. // overwritten with the new values further down, then ensure a routed
  1073. // inbound keeps a stable egress port (reusing the one already stored).
  1074. oldProtocol := oldInbound.Protocol
  1075. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1076. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1077. return inbound, false, err
  1078. }
  1079. tag := oldInbound.Tag
  1080. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1081. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1082. needRestart := false
  1083. // Persist the client-stat sync, settings munging, runtime push and inbound
  1084. // save as one transaction routed through the serial traffic writer, so it
  1085. // never runs concurrently with the @every 5s traffic poll. Both touch
  1086. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  1087. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  1088. //
  1089. // The runtime push stays inside the transaction here (unlike the client-edit
  1090. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  1091. // node before the central row is committed, or a "selected"-mode node would
  1092. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  1093. // holding the writer across the node call is an acceptable trade.
  1094. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1095. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1096. return err
  1097. }
  1098. // Ensure created_at and updated_at exist in inbound.Settings clients
  1099. {
  1100. var oldSettings map[string]any
  1101. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1102. emailToCreated := map[string]int64{}
  1103. emailToUpdated := map[string]int64{}
  1104. if oldSettings != nil {
  1105. if oc, ok := oldSettings["clients"].([]any); ok {
  1106. for _, it := range oc {
  1107. if m, ok2 := it.(map[string]any); ok2 {
  1108. if email, ok3 := m["email"].(string); ok3 {
  1109. switch v := m["created_at"].(type) {
  1110. case float64:
  1111. emailToCreated[email] = int64(v)
  1112. case int64:
  1113. emailToCreated[email] = v
  1114. }
  1115. switch v := m["updated_at"].(type) {
  1116. case float64:
  1117. emailToUpdated[email] = int64(v)
  1118. case int64:
  1119. emailToUpdated[email] = v
  1120. }
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. var newSettings map[string]any
  1127. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1128. now := time.Now().Unix() * 1000
  1129. if nSlice, ok := newSettings["clients"].([]any); ok {
  1130. for i := range nSlice {
  1131. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1132. email, _ := m["email"].(string)
  1133. if _, ok3 := m["created_at"]; !ok3 {
  1134. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1135. m["created_at"] = v
  1136. } else {
  1137. m["created_at"] = now
  1138. }
  1139. }
  1140. // Preserve client's updated_at if present; do not bump on parent inbound update
  1141. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1142. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1143. m["updated_at"] = v
  1144. }
  1145. }
  1146. nSlice[i] = m
  1147. }
  1148. }
  1149. newSettings["clients"] = nSlice
  1150. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1151. inbound.Settings = string(bs)
  1152. }
  1153. }
  1154. }
  1155. }
  1156. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1157. // keep their old length and would be rejected by xray. Regenerate mismatched
  1158. // client keys so the inbound stays connectable.
  1159. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1160. inbound.Settings = normalized
  1161. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1162. }
  1163. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1164. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1165. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1166. // but was stripped while the inbound was ineligible.
  1167. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1168. inbound.Settings = restored
  1169. }
  1170. oldInbound.Total = inbound.Total
  1171. oldInbound.Remark = inbound.Remark
  1172. oldInbound.SubSortIndex = inbound.SubSortIndex
  1173. oldInbound.Enable = inbound.Enable
  1174. oldInbound.ExpiryTime = inbound.ExpiryTime
  1175. oldInbound.TrafficReset = inbound.TrafficReset
  1176. oldInbound.Listen = inbound.Listen
  1177. oldInbound.Port = inbound.Port
  1178. oldInbound.Protocol = inbound.Protocol
  1179. oldInbound.Settings = inbound.Settings
  1180. oldInbound.StreamSettings = inbound.StreamSettings
  1181. oldInbound.Sniffing = inbound.Sniffing
  1182. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1183. normalizeInboundShareAddress(oldInbound)
  1184. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1185. inbound.ShareAddr = oldInbound.ShareAddr
  1186. } else {
  1187. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1188. return err
  1189. }
  1190. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1191. oldInbound.ShareAddr = inbound.ShareAddr
  1192. }
  1193. if oldTagWasAuto && inbound.Tag == tag {
  1194. inbound.Tag = ""
  1195. }
  1196. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1197. if err != nil {
  1198. return err
  1199. }
  1200. oldInbound.Tag = resolvedTag
  1201. inbound.Tag = oldInbound.Tag
  1202. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1203. if perr != nil {
  1204. return perr
  1205. }
  1206. if oldInbound.NodeID == nil {
  1207. if !push {
  1208. needRestart = true
  1209. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1210. oldSnapshot := *oldInbound
  1211. oldSnapshot.Tag = tag
  1212. oldSnapshot.Protocol = oldProtocol
  1213. payload := oldInbound
  1214. pushable := true
  1215. if inbound.Enable {
  1216. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1217. payload = built
  1218. } else {
  1219. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1220. pushable = false
  1221. }
  1222. }
  1223. if pushable {
  1224. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1225. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1226. } else {
  1227. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1228. if oldInbound.Protocol != model.MTProto {
  1229. needRestart = true
  1230. }
  1231. }
  1232. }
  1233. } else {
  1234. oldSnapshot := *oldInbound
  1235. oldSnapshot.Tag = tag
  1236. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1237. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1238. }
  1239. if inbound.Enable {
  1240. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1241. if err2 != nil {
  1242. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1243. needRestart = true
  1244. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1245. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1246. } else {
  1247. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1248. needRestart = true
  1249. }
  1250. }
  1251. }
  1252. } else if push {
  1253. oldSnapshot := *oldInbound
  1254. oldSnapshot.Tag = tag
  1255. if !inbound.Enable {
  1256. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1257. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1258. }
  1259. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1260. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1261. }
  1262. }
  1263. // A rename must allow the new tag before the inbound row is committed, or a
  1264. // node in "selected" sync mode would sweep the renamed central row on the
  1265. // next pull.
  1266. if oldInbound.NodeID != nil {
  1267. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1268. logger.Warning("allow inbound tag on node failed:", aErr)
  1269. }
  1270. }
  1271. if err := tx.Save(oldInbound).Error; err != nil {
  1272. return err
  1273. }
  1274. newClients, gcErr := s.GetClients(oldInbound)
  1275. if gcErr != nil {
  1276. return gcErr
  1277. }
  1278. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1279. return err
  1280. }
  1281. if oldInbound.NodeID != nil {
  1282. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1283. return err
  1284. }
  1285. }
  1286. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1287. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1288. // settings.
  1289. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1290. needRestart = true
  1291. }
  1292. return nil
  1293. })
  1294. if txErr != nil {
  1295. return inbound, false, txErr
  1296. }
  1297. // After the rename is committed, point any routing rules / loopback outbounds
  1298. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1299. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1300. // can't roll back the inbound edit.
  1301. if tag != oldInbound.Tag {
  1302. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1303. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1304. } else if routingChanged {
  1305. needRestart = true
  1306. }
  1307. }
  1308. return inbound, needRestart, nil
  1309. }
  1310. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1311. if inbound == nil {
  1312. return nil, fmt.Errorf("inbound is nil")
  1313. }
  1314. runtimeInbound := *inbound
  1315. settings := map[string]any{}
  1316. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1317. return nil, err
  1318. }
  1319. clients, ok := settings["clients"].([]any)
  1320. if !ok {
  1321. return &runtimeInbound, nil
  1322. }
  1323. var clientStats []xray.ClientTraffic
  1324. err := tx.Model(xray.ClientTraffic{}).
  1325. Where("inbound_id = ?", inbound.Id).
  1326. Select("email", "enable").
  1327. Find(&clientStats).Error
  1328. if err != nil {
  1329. return nil, err
  1330. }
  1331. enableMap := make(map[string]bool, len(clientStats))
  1332. for _, clientTraffic := range clientStats {
  1333. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1334. }
  1335. finalClients := make([]any, 0, len(clients))
  1336. for _, client := range clients {
  1337. c, ok := client.(map[string]any)
  1338. if !ok {
  1339. continue
  1340. }
  1341. email, _ := c["email"].(string)
  1342. if enable, exists := enableMap[email]; exists && !enable {
  1343. continue
  1344. }
  1345. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1346. continue
  1347. }
  1348. finalClients = append(finalClients, c)
  1349. }
  1350. settings["clients"] = finalClients
  1351. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1352. if err != nil {
  1353. return nil, err
  1354. }
  1355. runtimeInbound.Settings = string(modifiedSettings)
  1356. return &runtimeInbound, nil
  1357. }
  1358. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1359. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1360. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1361. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1362. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1363. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1364. oldClients, err := s.GetClients(oldInbound)
  1365. if err != nil {
  1366. return err
  1367. }
  1368. newClients, err := s.GetClients(newInbound)
  1369. if err != nil {
  1370. return err
  1371. }
  1372. // Email is the unique key for ClientTraffic rows. Clients without an
  1373. // email have no stats row to sync — skip them on both sides instead of
  1374. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1375. oldEmails := make(map[string]struct{}, len(oldClients))
  1376. for i := range oldClients {
  1377. if oldClients[i].Email == "" {
  1378. continue
  1379. }
  1380. oldEmails[oldClients[i].Email] = struct{}{}
  1381. }
  1382. newEmails := make(map[string]struct{}, len(newClients))
  1383. for i := range newClients {
  1384. if newClients[i].Email == "" {
  1385. continue
  1386. }
  1387. newEmails[newClients[i].Email] = struct{}{}
  1388. }
  1389. // Drop stats rows for removed emails — but not when a sibling inbound
  1390. // still references the email, since the row is the shared accumulator.
  1391. for i := range oldClients {
  1392. email := oldClients[i].Email
  1393. if email == "" {
  1394. continue
  1395. }
  1396. if _, kept := newEmails[email]; kept {
  1397. continue
  1398. }
  1399. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1400. if err != nil {
  1401. return err
  1402. }
  1403. if stillUsed {
  1404. continue
  1405. }
  1406. if err := s.DelClientStat(tx, email); err != nil {
  1407. return err
  1408. }
  1409. // Keep inbound_client_ips in sync when the inbound edit drops an
  1410. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1411. if err := s.DelClientIPs(tx, email); err != nil {
  1412. return err
  1413. }
  1414. }
  1415. for i := range newClients {
  1416. email := newClients[i].Email
  1417. if email == "" {
  1418. continue
  1419. }
  1420. if _, existed := oldEmails[email]; existed {
  1421. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1422. return err
  1423. }
  1424. continue
  1425. }
  1426. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1427. return err
  1428. }
  1429. }
  1430. return nil
  1431. }
  1432. func (s *InboundService) GetInboundTags() (string, error) {
  1433. db := database.GetDB()
  1434. var inboundTags []string
  1435. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1436. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1437. return "", err
  1438. }
  1439. tags, _ := json.Marshal(inboundTags)
  1440. return string(tags), nil
  1441. }
  1442. func (s *InboundService) GetClientReverseTags() (string, error) {
  1443. db := database.GetDB()
  1444. var inbounds []model.Inbound
  1445. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1446. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1447. return "[]", err
  1448. }
  1449. tagSet := make(map[string]struct{})
  1450. for _, inbound := range inbounds {
  1451. var settings map[string]any
  1452. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1453. continue
  1454. }
  1455. clients, ok := settings["clients"].([]any)
  1456. if !ok {
  1457. continue
  1458. }
  1459. for _, client := range clients {
  1460. clientMap, ok := client.(map[string]any)
  1461. if !ok {
  1462. continue
  1463. }
  1464. reverse, ok := clientMap["reverse"].(map[string]any)
  1465. if !ok {
  1466. continue
  1467. }
  1468. tag, _ := reverse["tag"].(string)
  1469. tag = strings.TrimSpace(tag)
  1470. if tag != "" {
  1471. tagSet[tag] = struct{}{}
  1472. }
  1473. }
  1474. }
  1475. rawTags := make([]string, 0, len(tagSet))
  1476. for tag := range tagSet {
  1477. rawTags = append(rawTags, tag)
  1478. }
  1479. sort.Strings(rawTags)
  1480. result, _ := json.Marshal(rawTags)
  1481. return string(result), nil
  1482. }
  1483. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1484. db := database.GetDB()
  1485. var inbounds []*model.Inbound
  1486. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1487. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1488. return nil, err
  1489. }
  1490. return inbounds, nil
  1491. }