inbound.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  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). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  481. // "network" — are canonicalized to "network", which every panel reader (link
  482. // generation, port-conflict detection, flow eligibility) keys on.
  483. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  484. protocolsWithStream := map[model.Protocol]bool{
  485. model.VMESS: true,
  486. model.VLESS: true,
  487. model.Trojan: true,
  488. model.Shadowsocks: true,
  489. model.Hysteria: true,
  490. model.WireGuard: true,
  491. model.Tunnel: true,
  492. }
  493. if !protocolsWithStream[inbound.Protocol] {
  494. inbound.StreamSettings = ""
  495. return
  496. }
  497. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  498. }
  499. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  500. // transport under "method" to the panel-canonical "network" key. When both
  501. // keys are present, "method" wins — matching xray-core's own precedence.
  502. func canonicalizeStreamNetworkKey(streamSettings string) string {
  503. if streamSettings == "" {
  504. return streamSettings
  505. }
  506. var stream map[string]any
  507. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  508. return streamSettings
  509. }
  510. method, ok := stream["method"].(string)
  511. if !ok || method == "" {
  512. return streamSettings
  513. }
  514. stream["network"] = method
  515. delete(stream, "method")
  516. out, err := json.MarshalIndent(stream, "", " ")
  517. if err != nil {
  518. return streamSettings
  519. }
  520. return string(out)
  521. }
  522. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  523. // stream uses REALITY security, or nil otherwise. A non-empty result means
  524. // this stream carries the finalmask+REALITY combination that panics
  525. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  526. // wraps the connection before REALITY's handshake ever sees it, and
  527. // reality.Server() does an unchecked type assertion assuming a raw
  528. // *net.TCPConn, which panics once finalmask is in front of it.
  529. //
  530. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  531. // listener ahead of REALITY's handshake, in xray-core's own
  532. // transport/internet/memory_settings.go) is only constructed when tcp masks
  533. // are present; a finalmask.udp-only config never touches the TCP accept path
  534. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  535. // rejected.
  536. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  537. if stream["security"] != "reality" {
  538. return nil
  539. }
  540. finalmask, ok := stream["finalmask"].(map[string]any)
  541. if !ok {
  542. return nil
  543. }
  544. tcp, _ := finalmask["tcp"].([]any)
  545. return tcp
  546. }
  547. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  548. // with REALITY security at save time. Upstream has confirmed this
  549. // combination will be documented as unsupported rather than made graceful,
  550. // so the panel must not let it be saved.
  551. func validateFinalMaskRealityCombo(streamSettings string) error {
  552. if streamSettings == "" {
  553. return nil
  554. }
  555. var stream map[string]any
  556. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  557. return nil
  558. }
  559. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  560. return nil
  561. }
  562. 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.")
  563. }
  564. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  565. // always valid before the row is persisted, and drops the vestigial inbound-level
  566. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  567. // only the per-client values. Leaving an inbound-level secret behind is what
  568. // produced stale links that failed with "incorrect client random".
  569. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  570. if inbound.Protocol != model.MTProto {
  571. return
  572. }
  573. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  574. inbound.Settings = stripped
  575. }
  576. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  577. inbound.Settings = stripped
  578. }
  579. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  580. inbound.Settings = healed
  581. }
  582. }
  583. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  584. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  585. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  586. if inbound == nil || inbound.Protocol != model.MTProto {
  587. return false
  588. }
  589. var parsed struct {
  590. RouteThroughXray bool `json:"routeThroughXray"`
  591. }
  592. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  593. return false
  594. }
  595. return parsed.RouteThroughXray
  596. }
  597. func settingsRouteXrayPort(parsed map[string]any) int {
  598. switch v := parsed["routeXrayPort"].(type) {
  599. case float64:
  600. return int(v)
  601. case int:
  602. return v
  603. case json.Number:
  604. if n, err := v.Int64(); err == nil {
  605. return int(n)
  606. }
  607. }
  608. return 0
  609. }
  610. func parseRouteXrayPort(settings string) int {
  611. if settings == "" {
  612. return 0
  613. }
  614. var parsed map[string]any
  615. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  616. return 0
  617. }
  618. return settingsRouteXrayPort(parsed)
  619. }
  620. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  621. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  622. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  623. // allocated once when routing is first enabled and preserved across edits
  624. // (carried over from oldSettings, which wins over any value the client echoed
  625. // back). When routing is off it — together with the now-inert outbound
  626. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  627. //
  628. // It returns an error when an egress port cannot be allocated or persisted, so
  629. // the caller refuses the save rather than storing a routed-but-portless inbound,
  630. // which would otherwise route no traffic and have its mtg metrics skipped (see
  631. // mtproto_job) — silently losing its accounting.
  632. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  633. if inbound.Protocol != model.MTProto {
  634. return nil
  635. }
  636. var parsed map[string]any
  637. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  638. return nil
  639. }
  640. routed, _ := parsed["routeThroughXray"].(bool)
  641. if !routed {
  642. _, hadPort := parsed["routeXrayPort"]
  643. _, hadTag := parsed["outboundTag"]
  644. if !hadPort && !hadTag {
  645. return nil
  646. }
  647. delete(parsed, "routeXrayPort")
  648. delete(parsed, "outboundTag")
  649. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  650. inbound.Settings = string(bs)
  651. } else {
  652. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  653. }
  654. return nil
  655. }
  656. // Prefer the already-stored port (carried across edits), then any value the
  657. // client sent, then allocate a fresh one.
  658. port := parseRouteXrayPort(oldSettings)
  659. if port <= 0 {
  660. port = settingsRouteXrayPort(parsed)
  661. }
  662. if port <= 0 {
  663. allocated, err := mtproto.FreeLocalPort()
  664. if err != nil {
  665. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  666. }
  667. port = allocated
  668. }
  669. if settingsRouteXrayPort(parsed) == port {
  670. return nil
  671. }
  672. parsed["routeXrayPort"] = port
  673. bs, err := json.MarshalIndent(parsed, "", " ")
  674. if err != nil {
  675. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  676. }
  677. inbound.Settings = string(bs)
  678. return nil
  679. }
  680. // AddInbound creates a new inbound configuration.
  681. // It validates port uniqueness, client email uniqueness, and required fields,
  682. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  683. // Returns the created inbound, whether Xray needs restart, and any error.
  684. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  685. // Normalize streamSettings based on protocol
  686. s.normalizeStreamSettings(inbound)
  687. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  688. return inbound, false, err
  689. }
  690. s.normalizeMtprotoSecret(inbound)
  691. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  692. return inbound, false, err
  693. }
  694. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  695. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  696. return inbound, false, err
  697. }
  698. conflict, err := s.checkPortConflict(inbound, 0)
  699. if err != nil {
  700. return inbound, false, err
  701. }
  702. if conflict != nil {
  703. return inbound, false, common.NewError(conflict.String())
  704. }
  705. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  706. if err != nil {
  707. return inbound, false, err
  708. }
  709. clients, err := s.GetClients(inbound)
  710. if err != nil {
  711. return inbound, false, err
  712. }
  713. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  714. if err != nil {
  715. return inbound, false, err
  716. }
  717. if existEmail != "" {
  718. return inbound, false, common.NewError("Duplicate email:", existEmail)
  719. }
  720. // Ensure created_at and updated_at on clients in settings
  721. if len(clients) > 0 {
  722. var settings map[string]any
  723. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  724. now := time.Now().Unix() * 1000
  725. updatedClients := make([]model.Client, 0, len(clients))
  726. for _, c := range clients {
  727. if c.CreatedAt == 0 {
  728. c.CreatedAt = now
  729. }
  730. c.UpdatedAt = now
  731. updatedClients = append(updatedClients, c)
  732. }
  733. settings["clients"] = updatedClients
  734. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  735. inbound.Settings = string(bs)
  736. } else {
  737. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  738. }
  739. } else if err2 != nil {
  740. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  741. }
  742. }
  743. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  744. // the inbound method (e.g. an API caller supplied a wrong-size key).
  745. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  746. inbound.Settings = normalized
  747. }
  748. // Secure client ID
  749. for _, client := range clients {
  750. switch inbound.Protocol {
  751. case "trojan":
  752. if client.Password == "" {
  753. return inbound, false, common.NewError("empty client ID")
  754. }
  755. case "shadowsocks":
  756. if client.Email == "" {
  757. return inbound, false, common.NewError("empty client ID")
  758. }
  759. case "hysteria":
  760. if client.Auth == "" {
  761. return inbound, false, common.NewError("empty client ID")
  762. }
  763. case "mtproto":
  764. if client.Secret == "" {
  765. return inbound, false, common.NewError("mtproto client requires a secret")
  766. }
  767. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  768. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  769. }
  770. default:
  771. if client.ID == "" {
  772. return inbound, false, common.NewError("empty client ID")
  773. }
  774. }
  775. }
  776. db := database.GetDB()
  777. needRestart := false
  778. var postCommitApply func()
  779. err = db.Transaction(func(tx *gorm.DB) error {
  780. markDirty := false
  781. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  782. return err
  783. }
  784. for i := range inbound.ClientStats {
  785. if inbound.ClientStats[i].Email == "" {
  786. continue
  787. }
  788. inbound.ClientStats[i].Id = 0
  789. inbound.ClientStats[i].InboundId = inbound.Id
  790. if err := tx.Clauses(clause.OnConflict{
  791. Columns: []clause.Column{{Name: "email"}},
  792. DoNothing: true,
  793. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  794. return err
  795. }
  796. }
  797. for _, client := range clients {
  798. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  799. return err
  800. }
  801. }
  802. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  803. return err
  804. }
  805. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  806. return err
  807. }
  808. if inbound.NodeID != nil {
  809. nodeID := *inbound.NodeID
  810. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  811. return err
  812. }
  813. }
  814. if inbound.Enable {
  815. if inbound.NodeID != nil {
  816. markDirty = true
  817. } else {
  818. rt, push, _, perr := s.nodePushPlan(inbound)
  819. if perr != nil {
  820. return perr
  821. }
  822. if push {
  823. payload := inbound
  824. pushable := true
  825. if inbound.Protocol == model.MTProto {
  826. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  827. payload = built
  828. } else {
  829. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  830. pushable = false
  831. }
  832. }
  833. if pushable {
  834. postCommitApply = func() {
  835. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  836. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  837. } else {
  838. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  839. needRestart = true
  840. }
  841. }
  842. }
  843. }
  844. }
  845. }
  846. if markDirty && inbound.NodeID != nil {
  847. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  848. }
  849. return nil
  850. })
  851. if err != nil {
  852. return inbound, false, err
  853. }
  854. if postCommitApply != nil {
  855. postCommitApply()
  856. }
  857. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  858. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  859. // in the generated config, so force a regen to wire it in.
  860. if mtprotoRoutesThroughXray(inbound) {
  861. needRestart = true
  862. }
  863. return inbound, needRestart, err
  864. }
  865. func (s *InboundService) DelInbound(id int) (bool, error) {
  866. db := database.GetDB()
  867. needRestart := false
  868. var postCommitApply func()
  869. var ib model.Inbound
  870. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  871. if loadErr == nil {
  872. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  873. if shouldPushToRuntime {
  874. if ib.NodeID != nil {
  875. rt, push, _, perr := s.nodePushPlan(&ib)
  876. if perr != nil {
  877. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  878. } else if push {
  879. postCommitApply = func() {
  880. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  881. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  882. } else {
  883. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  884. }
  885. }
  886. }
  887. } else {
  888. rt, push, _, perr := s.nodePushPlan(&ib)
  889. if perr != nil {
  890. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  891. } else if push {
  892. postCommitApply = func() {
  893. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  894. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  895. } else {
  896. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  897. needRestart = true
  898. }
  899. }
  900. } else {
  901. needRestart = true
  902. }
  903. }
  904. } else {
  905. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  906. }
  907. } else {
  908. logger.Debug("DelInbound: inbound not found, id:", id)
  909. }
  910. if err := db.Transaction(func(tx *gorm.DB) error {
  911. if err := s.clientService.DetachInbound(tx, id); err != nil {
  912. return err
  913. }
  914. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  915. return err
  916. }
  917. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  918. return err
  919. }
  920. if loadErr == nil && ib.NodeID != nil {
  921. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  922. }
  923. return nil
  924. }); err != nil {
  925. return needRestart, err
  926. }
  927. if postCommitApply != nil {
  928. postCommitApply()
  929. }
  930. if loadErr == nil && ib.Tag != "" {
  931. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  932. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  933. } else if routingChanged {
  934. needRestart = true
  935. }
  936. }
  937. if !database.IsPostgres() {
  938. var count int64
  939. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  940. return needRestart, err
  941. }
  942. if count == 0 {
  943. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  944. return needRestart, err
  945. }
  946. }
  947. }
  948. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  949. if mtprotoRoutesThroughXray(&ib) {
  950. needRestart = true
  951. }
  952. return needRestart, nil
  953. }
  954. type BulkDelInboundResult struct {
  955. Deleted int `json:"deleted"`
  956. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  957. }
  958. type BulkDelInboundReport struct {
  959. Id int `json:"id"`
  960. Reason string `json:"reason"`
  961. }
  962. // DelInbounds removes every inbound in the list, reusing the single-delete
  963. // path per id. Failures are recorded in Skipped and processing continues for
  964. // the rest; the aggregated needRestart is returned so the caller restarts
  965. // xray at most once.
  966. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  967. result := BulkDelInboundResult{}
  968. needRestart := false
  969. for _, id := range ids {
  970. r, err := s.DelInbound(id)
  971. if err != nil {
  972. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  973. continue
  974. }
  975. result.Deleted++
  976. if r {
  977. needRestart = true
  978. }
  979. }
  980. return result, needRestart, nil
  981. }
  982. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  983. db := database.GetDB()
  984. inbound := &model.Inbound{}
  985. err := db.Model(model.Inbound{}).First(inbound, id).Error
  986. if err != nil {
  987. return nil, err
  988. }
  989. return inbound, nil
  990. }
  991. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  992. db := database.GetDB()
  993. inbound := &model.Inbound{}
  994. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  995. if err != nil {
  996. return nil, err
  997. }
  998. s.enrichClientStats(db, []*model.Inbound{inbound})
  999. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1000. return inbound, nil
  1001. }
  1002. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1003. inbound, err := s.GetInbound(id)
  1004. if err != nil {
  1005. return false, err
  1006. }
  1007. if inbound.Enable == enable {
  1008. return false, nil
  1009. }
  1010. db := database.GetDB()
  1011. if err := db.Transaction(func(tx *gorm.DB) error {
  1012. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1013. Update("enable", enable).Error; err != nil {
  1014. return err
  1015. }
  1016. if inbound.NodeID != nil {
  1017. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1018. }
  1019. return nil
  1020. }); err != nil {
  1021. return false, err
  1022. }
  1023. inbound.Enable = enable
  1024. needRestart := false
  1025. rt, push, _, perr := s.nodePushPlan(inbound)
  1026. if perr != nil {
  1027. return false, perr
  1028. }
  1029. // Remote nodes interpret DelInbound as a real row delete (it hits
  1030. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1031. // switch on a remote inbound used to wipe the row entirely (#4402).
  1032. // PATCH the remote row via UpdateInbound instead — preserves the
  1033. // settings/client history and just flips the enable flag.
  1034. if inbound.NodeID != nil {
  1035. if push {
  1036. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1037. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1038. }
  1039. }
  1040. return false, nil
  1041. }
  1042. if !push {
  1043. return true, nil
  1044. }
  1045. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1046. !strings.Contains(err.Error(), "not found") {
  1047. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1048. needRestart = true
  1049. }
  1050. if !enable {
  1051. return needRestart, nil
  1052. }
  1053. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  1054. if err != nil {
  1055. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1056. return true, nil
  1057. }
  1058. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1059. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1060. needRestart = true
  1061. }
  1062. return needRestart, nil
  1063. }
  1064. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1065. // Normalize streamSettings based on protocol
  1066. s.normalizeStreamSettings(inbound)
  1067. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1068. return inbound, false, err
  1069. }
  1070. s.normalizeMtprotoSecret(inbound)
  1071. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1072. oldInbound, err := s.GetInbound(inbound.Id)
  1073. if err != nil {
  1074. return inbound, false, err
  1075. }
  1076. // Restore the stored NodeID before the port-conflict check so a node inbound
  1077. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1078. inbound.NodeID = oldInbound.NodeID
  1079. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1080. if err != nil {
  1081. return inbound, false, err
  1082. }
  1083. if conflict != nil {
  1084. return inbound, false, common.NewError(conflict.String())
  1085. }
  1086. // Capture the pre-edit protocol and routing state before oldInbound is
  1087. // overwritten with the new values further down, then ensure a routed
  1088. // inbound keeps a stable egress port (reusing the one already stored).
  1089. oldProtocol := oldInbound.Protocol
  1090. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1091. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1092. return inbound, false, err
  1093. }
  1094. tag := oldInbound.Tag
  1095. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1096. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1097. needRestart := false
  1098. var postCommitApply func()
  1099. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1100. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1101. return err
  1102. }
  1103. // Ensure created_at and updated_at exist in inbound.Settings clients
  1104. {
  1105. var oldSettings map[string]any
  1106. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1107. emailToCreated := map[string]int64{}
  1108. emailToUpdated := map[string]int64{}
  1109. if oldSettings != nil {
  1110. if oc, ok := oldSettings["clients"].([]any); ok {
  1111. for _, it := range oc {
  1112. if m, ok2 := it.(map[string]any); ok2 {
  1113. if email, ok3 := m["email"].(string); ok3 {
  1114. switch v := m["created_at"].(type) {
  1115. case float64:
  1116. emailToCreated[email] = int64(v)
  1117. case int64:
  1118. emailToCreated[email] = v
  1119. }
  1120. switch v := m["updated_at"].(type) {
  1121. case float64:
  1122. emailToUpdated[email] = int64(v)
  1123. case int64:
  1124. emailToUpdated[email] = v
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. var newSettings map[string]any
  1132. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1133. now := time.Now().Unix() * 1000
  1134. if nSlice, ok := newSettings["clients"].([]any); ok {
  1135. for i := range nSlice {
  1136. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1137. email, _ := m["email"].(string)
  1138. if _, ok3 := m["created_at"]; !ok3 {
  1139. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1140. m["created_at"] = v
  1141. } else {
  1142. m["created_at"] = now
  1143. }
  1144. }
  1145. // Preserve client's updated_at if present; do not bump on parent inbound update
  1146. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1147. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1148. m["updated_at"] = v
  1149. }
  1150. }
  1151. nSlice[i] = m
  1152. }
  1153. }
  1154. newSettings["clients"] = nSlice
  1155. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1156. inbound.Settings = string(bs)
  1157. }
  1158. }
  1159. }
  1160. }
  1161. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1162. // keep their old length and would be rejected by xray. Regenerate mismatched
  1163. // client keys so the inbound stays connectable.
  1164. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1165. inbound.Settings = normalized
  1166. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1167. }
  1168. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1169. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1170. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1171. // but was stripped while the inbound was ineligible.
  1172. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1173. inbound.Settings = restored
  1174. }
  1175. oldInbound.Total = inbound.Total
  1176. oldInbound.Remark = inbound.Remark
  1177. oldInbound.SubSortIndex = inbound.SubSortIndex
  1178. oldInbound.Enable = inbound.Enable
  1179. oldInbound.ExpiryTime = inbound.ExpiryTime
  1180. oldInbound.TrafficReset = inbound.TrafficReset
  1181. oldInbound.Listen = inbound.Listen
  1182. oldInbound.Port = inbound.Port
  1183. oldInbound.Protocol = inbound.Protocol
  1184. oldInbound.Settings = inbound.Settings
  1185. oldInbound.StreamSettings = inbound.StreamSettings
  1186. oldInbound.Sniffing = inbound.Sniffing
  1187. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1188. normalizeInboundShareAddress(oldInbound)
  1189. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1190. inbound.ShareAddr = oldInbound.ShareAddr
  1191. } else {
  1192. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1193. return err
  1194. }
  1195. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1196. oldInbound.ShareAddr = inbound.ShareAddr
  1197. }
  1198. if oldTagWasAuto && inbound.Tag == tag {
  1199. inbound.Tag = ""
  1200. }
  1201. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1202. if err != nil {
  1203. return err
  1204. }
  1205. oldInbound.Tag = resolvedTag
  1206. inbound.Tag = oldInbound.Tag
  1207. if oldInbound.NodeID == nil {
  1208. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1209. if perr != nil {
  1210. return perr
  1211. }
  1212. if !push {
  1213. needRestart = true
  1214. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1215. oldSnapshot := *oldInbound
  1216. oldSnapshot.Tag = tag
  1217. oldSnapshot.Protocol = oldProtocol
  1218. payload := oldInbound
  1219. pushable := true
  1220. if inbound.Enable {
  1221. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1222. payload = built
  1223. } else {
  1224. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1225. pushable = false
  1226. }
  1227. }
  1228. if pushable {
  1229. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1230. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1231. } else {
  1232. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1233. if oldInbound.Protocol != model.MTProto {
  1234. needRestart = true
  1235. }
  1236. }
  1237. }
  1238. } else {
  1239. oldSnapshot := *oldInbound
  1240. oldSnapshot.Tag = tag
  1241. var runtimeInbound *model.Inbound
  1242. if inbound.Enable {
  1243. var err2 error
  1244. runtimeInbound, err2 = s.buildRuntimeInboundForAPI(tx, oldInbound)
  1245. if err2 != nil {
  1246. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1247. needRestart = true
  1248. }
  1249. }
  1250. postCommitApply = func() {
  1251. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1252. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1253. }
  1254. if runtimeInbound == nil {
  1255. return
  1256. }
  1257. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1258. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1259. } else {
  1260. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1261. needRestart = true
  1262. }
  1263. }
  1264. }
  1265. } else {
  1266. nodeID := *oldInbound.NodeID
  1267. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1268. return err
  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. if postCommitApply != nil {
  1298. postCommitApply()
  1299. }
  1300. // After the rename is committed, point any routing rules / loopback outbounds
  1301. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1302. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1303. // can't roll back the inbound edit.
  1304. if tag != oldInbound.Tag {
  1305. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1306. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1307. } else if routingChanged {
  1308. needRestart = true
  1309. }
  1310. }
  1311. return inbound, needRestart, nil
  1312. }
  1313. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1314. if inbound == nil {
  1315. return nil, fmt.Errorf("inbound is nil")
  1316. }
  1317. runtimeInbound := *inbound
  1318. settings := map[string]any{}
  1319. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1320. return nil, err
  1321. }
  1322. clients, ok := settings["clients"].([]any)
  1323. if !ok {
  1324. return &runtimeInbound, nil
  1325. }
  1326. var clientStats []xray.ClientTraffic
  1327. err := tx.Model(xray.ClientTraffic{}).
  1328. Where("inbound_id = ?", inbound.Id).
  1329. Select("email", "enable").
  1330. Find(&clientStats).Error
  1331. if err != nil {
  1332. return nil, err
  1333. }
  1334. enableMap := make(map[string]bool, len(clientStats))
  1335. for _, clientTraffic := range clientStats {
  1336. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1337. }
  1338. finalClients := make([]any, 0, len(clients))
  1339. for _, client := range clients {
  1340. c, ok := client.(map[string]any)
  1341. if !ok {
  1342. continue
  1343. }
  1344. email, _ := c["email"].(string)
  1345. if enable, exists := enableMap[email]; exists && !enable {
  1346. continue
  1347. }
  1348. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1349. continue
  1350. }
  1351. finalClients = append(finalClients, c)
  1352. }
  1353. settings["clients"] = finalClients
  1354. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1355. if err != nil {
  1356. return nil, err
  1357. }
  1358. runtimeInbound.Settings = string(modifiedSettings)
  1359. return &runtimeInbound, nil
  1360. }
  1361. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1362. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1363. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1364. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1365. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1366. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1367. oldClients, err := s.GetClients(oldInbound)
  1368. if err != nil {
  1369. return err
  1370. }
  1371. newClients, err := s.GetClients(newInbound)
  1372. if err != nil {
  1373. return err
  1374. }
  1375. // Email is the unique key for ClientTraffic rows. Clients without an
  1376. // email have no stats row to sync — skip them on both sides instead of
  1377. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1378. oldEmails := make(map[string]struct{}, len(oldClients))
  1379. for i := range oldClients {
  1380. if oldClients[i].Email == "" {
  1381. continue
  1382. }
  1383. oldEmails[oldClients[i].Email] = struct{}{}
  1384. }
  1385. newEmails := make(map[string]struct{}, len(newClients))
  1386. for i := range newClients {
  1387. if newClients[i].Email == "" {
  1388. continue
  1389. }
  1390. newEmails[newClients[i].Email] = struct{}{}
  1391. }
  1392. // Drop stats rows for removed emails — but not when a sibling inbound
  1393. // still references the email, since the row is the shared accumulator.
  1394. for i := range oldClients {
  1395. email := oldClients[i].Email
  1396. if email == "" {
  1397. continue
  1398. }
  1399. if _, kept := newEmails[email]; kept {
  1400. continue
  1401. }
  1402. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1403. if err != nil {
  1404. return err
  1405. }
  1406. if stillUsed {
  1407. continue
  1408. }
  1409. if err := s.DelClientStat(tx, email); err != nil {
  1410. return err
  1411. }
  1412. // Keep inbound_client_ips in sync when the inbound edit drops an
  1413. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1414. if err := s.DelClientIPs(tx, email); err != nil {
  1415. return err
  1416. }
  1417. }
  1418. for i := range newClients {
  1419. email := newClients[i].Email
  1420. if email == "" {
  1421. continue
  1422. }
  1423. if _, existed := oldEmails[email]; existed {
  1424. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1425. return err
  1426. }
  1427. continue
  1428. }
  1429. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1430. return err
  1431. }
  1432. }
  1433. return nil
  1434. }
  1435. func (s *InboundService) GetInboundTags() (string, error) {
  1436. db := database.GetDB()
  1437. var inboundTags []string
  1438. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1439. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1440. return "", err
  1441. }
  1442. tags, _ := json.Marshal(inboundTags)
  1443. return string(tags), nil
  1444. }
  1445. func (s *InboundService) GetClientReverseTags() (string, error) {
  1446. db := database.GetDB()
  1447. var inbounds []model.Inbound
  1448. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1449. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1450. return "[]", err
  1451. }
  1452. tagSet := make(map[string]struct{})
  1453. for _, inbound := range inbounds {
  1454. var settings map[string]any
  1455. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1456. continue
  1457. }
  1458. clients, ok := settings["clients"].([]any)
  1459. if !ok {
  1460. continue
  1461. }
  1462. for _, client := range clients {
  1463. clientMap, ok := client.(map[string]any)
  1464. if !ok {
  1465. continue
  1466. }
  1467. reverse, ok := clientMap["reverse"].(map[string]any)
  1468. if !ok {
  1469. continue
  1470. }
  1471. tag, _ := reverse["tag"].(string)
  1472. tag = strings.TrimSpace(tag)
  1473. if tag != "" {
  1474. tagSet[tag] = struct{}{}
  1475. }
  1476. }
  1477. }
  1478. rawTags := make([]string, 0, len(tagSet))
  1479. for tag := range tagSet {
  1480. rawTags = append(rawTags, tag)
  1481. }
  1482. sort.Strings(rawTags)
  1483. result, _ := json.Marshal(rawTags)
  1484. return string(result), nil
  1485. }
  1486. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1487. db := database.GetDB()
  1488. var inbounds []*model.Inbound
  1489. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1490. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1491. return nil, err
  1492. }
  1493. return inbounds, nil
  1494. }