inbound.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  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. "regexp"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  21. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  22. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  23. "gorm.io/gorm"
  24. "gorm.io/gorm/clause"
  25. )
  26. type InboundService struct {
  27. clientService ClientService
  28. fallbackService FallbackService
  29. }
  30. func normalizeTrafficResetDay(day int) int {
  31. if day < 1 {
  32. return 1
  33. }
  34. return min(day, 31)
  35. }
  36. func normalizeInboundShareAddrStrategy(strategy string) string {
  37. strategy = strings.TrimSpace(strategy)
  38. switch strategy {
  39. case "listen", "custom":
  40. return strategy
  41. default:
  42. return "node"
  43. }
  44. }
  45. func normalizeInboundShareAddress(inbound *model.Inbound) {
  46. if inbound == nil {
  47. return
  48. }
  49. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  50. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  51. inbound.ShareAddr = addr
  52. } else {
  53. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  54. }
  55. }
  56. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  57. if inbound == nil {
  58. return nil
  59. }
  60. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  61. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  62. if err != nil {
  63. return common.NewError("shareAddr must be a host or IP without scheme or port")
  64. }
  65. inbound.ShareAddr = addr
  66. return nil
  67. }
  68. func normalizeInboundShareHost(raw string) (string, error) {
  69. addr := strings.TrimSpace(raw)
  70. if addr == "" {
  71. return "", nil
  72. }
  73. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  74. return "", fmt.Errorf("invalid share address %q", raw)
  75. }
  76. if strings.HasPrefix(addr, "[") {
  77. if !strings.HasSuffix(addr, "]") {
  78. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  79. }
  80. ip := net.ParseIP(addr[1 : len(addr)-1])
  81. if ip == nil || ip.To4() != nil {
  82. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  83. }
  84. return "[" + ip.String() + "]", nil
  85. }
  86. if strings.Contains(addr, ":") {
  87. if _, _, err := net.SplitHostPort(addr); err == nil {
  88. return "", fmt.Errorf("share address must not include port")
  89. }
  90. ip := net.ParseIP(addr)
  91. if ip == nil || ip.To4() != nil {
  92. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  93. }
  94. return "[" + ip.String() + "]", nil
  95. }
  96. host, err := netsafe.NormalizeHost(addr)
  97. if err != nil {
  98. return "", err
  99. }
  100. return host, nil
  101. }
  102. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  103. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  104. return nil
  105. }
  106. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  107. 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 {
  108. return err
  109. }
  110. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  111. if hasShareAddr {
  112. 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 {
  113. return err
  114. }
  115. }
  116. if !hasShareAddr {
  117. return nil
  118. }
  119. var rows []struct {
  120. Id int
  121. ShareAddrStrategy string
  122. ShareAddr string
  123. }
  124. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  125. return err
  126. }
  127. for _, row := range rows {
  128. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  129. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  130. if addrErr != nil {
  131. strategy = "node"
  132. addr = ""
  133. }
  134. updates := map[string]any{}
  135. if strategy != row.ShareAddrStrategy {
  136. updates["share_addr_strategy"] = strategy
  137. }
  138. if addr != row.ShareAddr {
  139. updates["share_addr"] = addr
  140. }
  141. if len(updates) > 0 {
  142. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  143. return err
  144. }
  145. }
  146. }
  147. return nil
  148. }
  149. // GetInbounds retrieves all inbounds for a specific user with client stats.
  150. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  151. db := database.GetDB()
  152. var inbounds []*model.Inbound
  153. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  154. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  155. return nil, err
  156. }
  157. s.enrichClientStats(db, inbounds)
  158. s.annotateFallbackParents(db, inbounds)
  159. s.annotateLocalOriginGuid(inbounds)
  160. return inbounds, nil
  161. }
  162. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  163. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  164. // already carry the originating node's GUID. Read-time only (not persisted) so
  165. // the per-inbound online view can scope by GUID uniformly across a chain of
  166. // nodes (#4983).
  167. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  168. if len(inbounds) == 0 {
  169. return
  170. }
  171. guid := s.panelGuid()
  172. if guid == "" {
  173. return
  174. }
  175. for _, ib := range inbounds {
  176. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  177. ib.OriginNodeGuid = guid
  178. }
  179. }
  180. }
  181. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  182. // strips every per-client field other than email / enable / comment from
  183. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  184. // inbounds page only needs those three to roll up client counts and
  185. // render badges, so this trims tens of bytes per client (UUID, password,
  186. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  187. // up fast on installs with thousands of clients.
  188. //
  189. // Full client data is still available through GET /panel/api/inbounds/get/:id
  190. // for the edit/info/qr/export/clone flows that need it.
  191. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  192. db := database.GetDB()
  193. var inbounds []*model.Inbound
  194. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  195. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  196. return nil, err
  197. }
  198. s.annotateFallbackParents(db, inbounds)
  199. s.annotateLocalOriginGuid(inbounds)
  200. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  201. // so the list's depleted/expiring badges see every client; the UUID/SubId
  202. // enrichment stays skipped. Must run before slimming strips the settings.
  203. s.backfillClientStats(db, inbounds)
  204. // Slim feeds the panel UI only (masters poll the full list), so the badge
  205. // math may see the cross-panel totals a master pushed.
  206. s.overlayInboundsClientStats(db, inbounds)
  207. for _, ib := range inbounds {
  208. ib.Settings = slimSettingsClients(ib.Settings)
  209. }
  210. return inbounds, nil
  211. }
  212. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  213. // keeps only the fields the list view actually reads. Returns the input
  214. // unchanged when the JSON can't be parsed or has no clients array.
  215. func slimSettingsClients(settings string) string {
  216. if settings == "" {
  217. return settings
  218. }
  219. var raw map[string]any
  220. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  221. return settings
  222. }
  223. clients, ok := raw["clients"].([]any)
  224. if !ok || len(clients) == 0 {
  225. return settings
  226. }
  227. slim := make([]any, 0, len(clients))
  228. for _, entry := range clients {
  229. c, ok := entry.(map[string]any)
  230. if !ok {
  231. continue
  232. }
  233. row := make(map[string]any, 3)
  234. if v, ok := c["email"]; ok {
  235. row["email"] = v
  236. }
  237. if v, ok := c["enable"]; ok {
  238. row["enable"] = v
  239. }
  240. if v, ok := c["comment"]; ok && v != "" {
  241. row["comment"] = v
  242. }
  243. slim = append(slim, row)
  244. }
  245. raw["clients"] = slim
  246. out, err := json.Marshal(raw)
  247. if err != nil {
  248. return settings
  249. }
  250. return string(out)
  251. }
  252. // annotateFallbackParents fills FallbackParent on each inbound that is
  253. // the child side of a fallback rule. One DB round-trip serves the full
  254. // list — the frontend needs this to rewrite the child's client-share
  255. // link so it points at the master's reachable endpoint.
  256. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  257. if len(inbounds) == 0 {
  258. return
  259. }
  260. childIds := make([]int, 0, len(inbounds))
  261. for _, ib := range inbounds {
  262. childIds = append(childIds, ib.Id)
  263. }
  264. var rows []model.InboundFallback
  265. if err := db.Where("child_id IN ?", childIds).
  266. Order("sort_order ASC, id ASC").
  267. Find(&rows).Error; err != nil {
  268. return
  269. }
  270. first := make(map[int]model.InboundFallback, len(rows))
  271. for _, r := range rows {
  272. if _, ok := first[r.ChildId]; !ok {
  273. first[r.ChildId] = r
  274. }
  275. }
  276. for _, ib := range inbounds {
  277. if r, ok := first[ib.Id]; ok {
  278. ib.FallbackParent = &model.FallbackParentInfo{
  279. MasterId: r.MasterId,
  280. Path: r.Path,
  281. }
  282. }
  283. }
  284. }
  285. type InboundOption struct {
  286. Id int `json:"id" example:"1"`
  287. Remark string `json:"remark" example:"VLESS-443"`
  288. Tag string `json:"tag" example:"in-443-tcp"`
  289. Protocol string `json:"protocol" example:"vless"`
  290. Port int `json:"port" example:"443"`
  291. Enable bool `json:"enable" example:"true"`
  292. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  293. SsMethod string `json:"ssMethod"`
  294. WgPublicKey string `json:"wgPublicKey,omitempty"`
  295. WgMtu int `json:"wgMtu,omitempty"`
  296. WgDns string `json:"wgDns,omitempty"`
  297. MtprotoDomain string `json:"mtprotoDomain,omitempty"`
  298. // Hosting node; nil for this panel's own inbounds. Lets the clients
  299. // page map a node filter onto inbound IDs (#4997).
  300. NodeId *int `json:"nodeId,omitempty"`
  301. // Share-host resolution inputs, mirroring the subscription's
  302. // resolveInboundAddress so the clients page renders a node-managed WireGuard
  303. // Endpoint that points at the node, not the master panel. NodeAddress is the
  304. // hosting node's externally reachable address (empty for this panel's own
  305. // inbounds); Listen and ShareAddrStrategy/ShareAddr feed the same
  306. // node→listen→custom fallback the share/QR links already use.
  307. NodeAddress string `json:"nodeAddress,omitempty"`
  308. Listen string `json:"listen,omitempty"`
  309. ShareAddr string `json:"shareAddr,omitempty"`
  310. ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
  311. }
  312. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  313. db := database.GetDB()
  314. var rows []struct {
  315. Id int `gorm:"column:id"`
  316. Remark string `gorm:"column:remark"`
  317. Tag string `gorm:"column:tag"`
  318. Protocol string `gorm:"column:protocol"`
  319. Port int `gorm:"column:port"`
  320. Enable bool `gorm:"column:enable"`
  321. StreamSettings string `gorm:"column:stream_settings"`
  322. Settings string `gorm:"column:settings"`
  323. Listen string `gorm:"column:listen"`
  324. ShareAddr string `gorm:"column:share_addr"`
  325. ShareAddrStrategy string `gorm:"column:share_addr_strategy"`
  326. NodeId *int `gorm:"column:node_id"`
  327. NodeAddress string `gorm:"column:node_address"`
  328. DisableFlow bool `gorm:"column:disable_flow"`
  329. }
  330. err := db.Table("inbounds").
  331. 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, inbounds.disable_flow").
  332. Joins("LEFT JOIN nodes ON nodes.id = inbounds.node_id").
  333. Where("inbounds.user_id = ?", userId).
  334. Order("inbounds.id ASC").
  335. Scan(&rows).Error
  336. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  337. return nil, err
  338. }
  339. out := make([]InboundOption, 0, len(rows))
  340. for _, r := range rows {
  341. wgPublicKey, wgMtu, wgDns := inboundWireguardHints(r.Protocol, r.Settings)
  342. shareAddrStrategy := r.ShareAddrStrategy
  343. if shareAddrStrategy == "node" {
  344. shareAddrStrategy = ""
  345. }
  346. out = append(out, InboundOption{
  347. Id: r.Id,
  348. Remark: r.Remark,
  349. Tag: r.Tag,
  350. Protocol: r.Protocol,
  351. Port: r.Port,
  352. Enable: r.Enable,
  353. TlsFlowCapable: !r.DisableFlow && inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  354. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  355. WgPublicKey: wgPublicKey,
  356. WgMtu: wgMtu,
  357. WgDns: wgDns,
  358. MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
  359. NodeId: r.NodeId,
  360. NodeAddress: r.NodeAddress,
  361. Listen: r.Listen,
  362. ShareAddr: r.ShareAddr,
  363. ShareAddrStrategy: shareAddrStrategy,
  364. })
  365. }
  366. return out, nil
  367. }
  368. func inboundWireguardHints(protocol string, settings string) (string, int, string) {
  369. if protocol != string(model.WireGuard) || strings.TrimSpace(settings) == "" {
  370. return "", 0, ""
  371. }
  372. var parsed struct {
  373. PublicKey string `json:"publicKey"`
  374. PubKey string `json:"pubKey"`
  375. SecretKey string `json:"secretKey"`
  376. MTU int `json:"mtu"`
  377. DNS string `json:"dns"`
  378. }
  379. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  380. return "", 0, ""
  381. }
  382. publicKey := parsed.PublicKey
  383. if publicKey == "" {
  384. publicKey = parsed.PubKey
  385. }
  386. if publicKey == "" && parsed.SecretKey != "" {
  387. if derived, err := wgutil.PublicKeyFromPrivate(parsed.SecretKey); err == nil {
  388. publicKey = derived
  389. }
  390. }
  391. return publicKey, parsed.MTU, parsed.DNS
  392. }
  393. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  394. // the clients UI to seed a new mtproto client's secret with the right fronting
  395. // hostname.
  396. func inboundMtprotoDomain(protocol string, settings string) string {
  397. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  398. return ""
  399. }
  400. var parsed struct {
  401. FakeTLSDomain string `json:"fakeTlsDomain"`
  402. }
  403. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  404. return ""
  405. }
  406. return strings.TrimSpace(parsed.FakeTLSDomain)
  407. }
  408. // GetAllInbounds retrieves all inbounds with client stats.
  409. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  410. db := database.GetDB()
  411. var inbounds []*model.Inbound
  412. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  413. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  414. return nil, err
  415. }
  416. s.enrichClientStats(db, inbounds)
  417. return inbounds, nil
  418. }
  419. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  420. db := database.GetDB()
  421. var inbounds []*model.Inbound
  422. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  423. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  424. return nil, err
  425. }
  426. return inbounds, nil
  427. }
  428. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  429. return ParseInboundSettingsClients(inbound.Settings)
  430. }
  431. // GetClientsBySubId returns the inbound's clients with the given subscription
  432. // id, resolved from the normalized clients tables (the same source the running
  433. // Xray users are built from) instead of parsing the settings JSON blob.
  434. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  435. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  436. }
  437. func (s *InboundService) GetAllEmails() ([]string, error) {
  438. db := database.GetDB()
  439. var emails []string
  440. query := fmt.Sprintf(
  441. "SELECT DISTINCT %s %s",
  442. database.JSONFieldText("client.value", "email"),
  443. database.JSONClientsFromInbound(),
  444. )
  445. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  446. return nil, err
  447. }
  448. return emails, nil
  449. }
  450. // getAllEmailSubIDs returns email→subId. An email seen with two different
  451. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  452. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  453. db := database.GetDB()
  454. var rows []struct {
  455. Email string
  456. SubID string
  457. }
  458. query := fmt.Sprintf(
  459. "SELECT %s AS email, %s AS sub_id %s",
  460. database.JSONFieldText("client.value", "email"),
  461. database.JSONFieldText("client.value", "subId"),
  462. database.JSONClientsFromInbound(),
  463. )
  464. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  465. return nil, err
  466. }
  467. result := make(map[string]string, len(rows))
  468. for _, r := range rows {
  469. email := strings.ToLower(r.Email)
  470. if email == "" {
  471. continue
  472. }
  473. subID := r.SubID
  474. if existing, ok := result[email]; ok {
  475. if existing != subID {
  476. result[email] = ""
  477. }
  478. continue
  479. }
  480. result[email] = subID
  481. }
  482. return result, nil
  483. }
  484. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  485. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  486. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  487. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  488. // mode). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  489. // "network" — are canonicalized to "network", which every panel reader (link
  490. // generation, port-conflict detection, flow eligibility) keys on.
  491. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  492. protocolsWithStream := map[model.Protocol]bool{
  493. model.VMESS: true,
  494. model.VLESS: true,
  495. model.Trojan: true,
  496. model.Shadowsocks: true,
  497. model.Hysteria: true,
  498. model.WireGuard: true,
  499. model.Tunnel: true,
  500. }
  501. if !protocolsWithStream[inbound.Protocol] {
  502. inbound.StreamSettings = ""
  503. return
  504. }
  505. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  506. }
  507. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  508. // transport under "method" to the panel-canonical "network" key. When both
  509. // keys are present, "method" wins — matching xray-core's own precedence.
  510. func canonicalizeStreamNetworkKey(streamSettings string) string {
  511. if streamSettings == "" {
  512. return streamSettings
  513. }
  514. var stream map[string]any
  515. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  516. return streamSettings
  517. }
  518. method, ok := stream["method"].(string)
  519. if !ok || method == "" {
  520. return streamSettings
  521. }
  522. stream["network"] = method
  523. delete(stream, "method")
  524. out, err := json.MarshalIndent(stream, "", " ")
  525. if err != nil {
  526. return streamSettings
  527. }
  528. return string(out)
  529. }
  530. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  531. // stream uses REALITY security, or nil otherwise. A non-empty result means
  532. // this stream carries the finalmask+REALITY combination that panics
  533. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  534. // wraps the connection before REALITY's handshake ever sees it, and
  535. // reality.Server() does an unchecked type assertion assuming a raw
  536. // *net.TCPConn, which panics once finalmask is in front of it.
  537. //
  538. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  539. // listener ahead of REALITY's handshake, in xray-core's own
  540. // transport/internet/memory_settings.go) is only constructed when tcp masks
  541. // are present; a finalmask.udp-only config never touches the TCP accept path
  542. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  543. // rejected.
  544. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  545. if stream["security"] != "reality" {
  546. return nil
  547. }
  548. finalmask, ok := stream["finalmask"].(map[string]any)
  549. if !ok {
  550. return nil
  551. }
  552. tcp, _ := finalmask["tcp"].([]any)
  553. return tcp
  554. }
  555. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  556. // with REALITY security at save time. Upstream has confirmed this
  557. // combination will be documented as unsupported rather than made graceful,
  558. // so the panel must not let it be saved.
  559. func validateFinalMaskRealityCombo(streamSettings string) error {
  560. if streamSettings == "" {
  561. return nil
  562. }
  563. var stream map[string]any
  564. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  565. return nil
  566. }
  567. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  568. return nil
  569. }
  570. 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.")
  571. }
  572. var xmcProfileUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{3,16}$`)
  573. // xmcMaskProfilesComplete reports whether an xmc finalmask carries the signed
  574. // Minecraft session profiles xray-core has required since v26.7.28 (#6487).
  575. // The core replaced the old `usernames` string list with `profiles` objects
  576. // and removed the "default to Dream when empty" fallback, so a mask still on
  577. // the legacy shape — or one whose profiles are incomplete — now fails
  578. // conf.XMC.Build() and takes the entire config down with it rather than
  579. // degrading that one inbound.
  580. //
  581. // The texture fields are a signed blob only Mojang's session server can issue
  582. // (resolve the UUID by username, then fetch the profile with unsigned=false),
  583. // so the panel cannot synthesize a valid profile from a legacy username; an
  584. // incomplete mask can only be reported or dropped.
  585. func xmcMaskProfilesComplete(mask map[string]any) bool {
  586. settings, ok := mask["settings"].(map[string]any)
  587. if !ok {
  588. return false
  589. }
  590. profiles, _ := settings["profiles"].([]any)
  591. if len(profiles) == 0 {
  592. return false
  593. }
  594. for _, entry := range profiles {
  595. profile, ok := entry.(map[string]any)
  596. if !ok {
  597. return false
  598. }
  599. username, _ := profile["username"].(string)
  600. if !xmcProfileUsernamePattern.MatchString(username) {
  601. return false
  602. }
  603. id, _ := profile["uuid"].(string)
  604. if _, err := uuid.Parse(id); err != nil {
  605. return false
  606. }
  607. if value, _ := profile["texturesValue"].(string); value == "" {
  608. return false
  609. }
  610. if signature, _ := profile["texturesSignature"].(string); signature == "" {
  611. return false
  612. }
  613. }
  614. return true
  615. }
  616. // isIncompleteXmcMask reports whether a finalmask.tcp entry is an xmc mask
  617. // xray-core would refuse to build.
  618. func isIncompleteXmcMask(entry any) bool {
  619. mask, ok := entry.(map[string]any)
  620. if !ok {
  621. return false
  622. }
  623. if maskType, _ := mask["type"].(string); maskType != "xmc" {
  624. return false
  625. }
  626. return !xmcMaskProfilesComplete(mask)
  627. }
  628. // incompleteXmcMaskCount counts the stream's xmc finalmask entries that
  629. // xray-core would refuse to build.
  630. func incompleteXmcMaskCount(stream map[string]any) int {
  631. finalmask, ok := stream["finalmask"].(map[string]any)
  632. if !ok {
  633. return 0
  634. }
  635. tcp, _ := finalmask["tcp"].([]any)
  636. count := 0
  637. for _, entry := range tcp {
  638. if isIncompleteXmcMask(entry) {
  639. count++
  640. }
  641. }
  642. return count
  643. }
  644. // stripIncompleteXmcMasks removes every xmc finalmask entry xray-core would
  645. // refuse to build, returning how many were dropped, and clears the finalmask
  646. // object once nothing is left in it.
  647. //
  648. // AddInbound and UpdateInbound reject an incomplete mask at save time, but a
  649. // row that never went through those paths — an upgrade from a panel predating
  650. // v26.7.28, node sync, a restored backup, a direct DB edit — would otherwise
  651. // fail the whole config build and keep every other inbound offline too.
  652. // Dropping only the offending mask degrades that one inbound instead, which
  653. // the accompanying warning tells the admin to reconfigure.
  654. func stripIncompleteXmcMasks(stream map[string]any) int {
  655. finalmask, ok := stream["finalmask"].(map[string]any)
  656. if !ok {
  657. return 0
  658. }
  659. tcp, _ := finalmask["tcp"].([]any)
  660. if len(tcp) == 0 {
  661. return 0
  662. }
  663. kept := make([]any, 0, len(tcp))
  664. dropped := 0
  665. for _, entry := range tcp {
  666. if isIncompleteXmcMask(entry) {
  667. dropped++
  668. continue
  669. }
  670. kept = append(kept, entry)
  671. }
  672. if dropped == 0 {
  673. return 0
  674. }
  675. if len(kept) == 0 {
  676. delete(finalmask, "tcp")
  677. } else {
  678. finalmask["tcp"] = kept
  679. }
  680. if len(finalmask) == 0 {
  681. delete(stream, "finalmask")
  682. }
  683. return dropped
  684. }
  685. // dropEmptyRandPackets removes the leftover empty "packet" from finalmask
  686. // items that also carry a rand, and reports how many it cleared.
  687. //
  688. // xray-core treats even an empty array as a packet, and every item kind is
  689. // exclusive: noise refuses "len(item.Packet) > 0 && item.Rand.To > 0" and
  690. // header-custom refuses "exactly one item kind must be set". Either error
  691. // fails the whole config build, so one such item keeps every inbound offline.
  692. // The panel's mask editor wrote that pair whenever an item was switched to the
  693. // rand-driven array kind, so stored rows carry it; clearing an empty packet
  694. // changes nothing about the mask the admin configured.
  695. func dropEmptyRandPackets(node any) int {
  696. switch value := node.(type) {
  697. case map[string]any:
  698. cleared := 0
  699. if packet, ok := value["packet"].([]any); ok && len(packet) == 0 && randIsSet(value["rand"]) {
  700. delete(value, "packet")
  701. cleared++
  702. }
  703. for _, child := range value {
  704. cleared += dropEmptyRandPackets(child)
  705. }
  706. return cleared
  707. case []any:
  708. cleared := 0
  709. for _, child := range value {
  710. cleared += dropEmptyRandPackets(child)
  711. }
  712. return cleared
  713. default:
  714. return 0
  715. }
  716. }
  717. // randIsSet reports whether a finalmask item's rand selects a random packet.
  718. // It is a number on header-custom items and a dash-range string on noise ones.
  719. func randIsSet(value any) bool {
  720. switch rand := value.(type) {
  721. case float64:
  722. return rand > 0
  723. case string:
  724. return rand != "" && rand != "0" && rand != "0-0"
  725. default:
  726. return false
  727. }
  728. }
  729. // validateFinalMaskXmcProfiles rejects an xmc finalmask without complete
  730. // profiles at save time, so the admin gets a targeted error instead of a core
  731. // that refuses to start (or, after GetXrayConfig heals it, an inbound quietly
  732. // serving without the obfuscation they configured).
  733. func validateFinalMaskXmcProfiles(streamSettings string) error {
  734. if streamSettings == "" {
  735. return nil
  736. }
  737. var stream map[string]any
  738. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  739. return nil
  740. }
  741. if incompleteXmcMaskCount(stream) == 0 {
  742. return nil
  743. }
  744. return common.NewError("XMC finalmask requires at least one complete Minecraft profile — each needs a username (3-16 of A-Z a-z 0-9 _), a UUID, and both texture fields from Mojang's session server (XTLS/Xray-core#6487). Complete the profiles or remove the XMC mask.")
  745. }
  746. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  747. // always valid before the row is persisted, and drops the vestigial inbound-level
  748. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  749. // only the per-client values. Leaving an inbound-level secret behind is what
  750. // produced stale links that failed with "incorrect client random".
  751. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  752. if inbound.Protocol != model.MTProto {
  753. return
  754. }
  755. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  756. inbound.Settings = stripped
  757. }
  758. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  759. inbound.Settings = stripped
  760. }
  761. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  762. inbound.Settings = healed
  763. }
  764. }
  765. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  766. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  767. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  768. if inbound == nil || inbound.Protocol != model.MTProto {
  769. return false
  770. }
  771. var parsed struct {
  772. RouteThroughXray bool `json:"routeThroughXray"`
  773. }
  774. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  775. return false
  776. }
  777. return parsed.RouteThroughXray
  778. }
  779. func settingsRouteXrayPort(parsed map[string]any) int {
  780. switch v := parsed["routeXrayPort"].(type) {
  781. case float64:
  782. return int(v)
  783. case int:
  784. return v
  785. case json.Number:
  786. if n, err := v.Int64(); err == nil {
  787. return int(n)
  788. }
  789. }
  790. return 0
  791. }
  792. func parseRouteXrayPort(settings string) int {
  793. if settings == "" {
  794. return 0
  795. }
  796. var parsed map[string]any
  797. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  798. return 0
  799. }
  800. return settingsRouteXrayPort(parsed)
  801. }
  802. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  803. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  804. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  805. // allocated once when routing is first enabled and preserved across edits
  806. // (carried over from oldSettings, which wins over any value the client echoed
  807. // back). When routing is off it — together with the now-inert outbound
  808. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  809. //
  810. // It returns an error when an egress port cannot be allocated or persisted, so
  811. // the caller refuses the save rather than storing a routed-but-portless inbound,
  812. // which would otherwise route no traffic and have its mtg metrics skipped (see
  813. // mtproto_job) — silently losing its accounting.
  814. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  815. if inbound.Protocol != model.MTProto {
  816. return nil
  817. }
  818. var parsed map[string]any
  819. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  820. return nil
  821. }
  822. routed, _ := parsed["routeThroughXray"].(bool)
  823. if !routed {
  824. _, hadPort := parsed["routeXrayPort"]
  825. _, hadTag := parsed["outboundTag"]
  826. if !hadPort && !hadTag {
  827. return nil
  828. }
  829. delete(parsed, "routeXrayPort")
  830. delete(parsed, "outboundTag")
  831. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  832. inbound.Settings = string(bs)
  833. } else {
  834. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  835. }
  836. return nil
  837. }
  838. // Prefer the already-stored port (carried across edits), then any value the
  839. // client sent, then allocate a fresh one.
  840. port := parseRouteXrayPort(oldSettings)
  841. if port <= 0 {
  842. port = settingsRouteXrayPort(parsed)
  843. }
  844. if port <= 0 {
  845. allocated, err := mtproto.FreeLocalPort()
  846. if err != nil {
  847. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  848. }
  849. port = allocated
  850. }
  851. if settingsRouteXrayPort(parsed) == port {
  852. return nil
  853. }
  854. parsed["routeXrayPort"] = port
  855. bs, err := json.MarshalIndent(parsed, "", " ")
  856. if err != nil {
  857. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  858. }
  859. inbound.Settings = string(bs)
  860. return nil
  861. }
  862. // AddInbound creates a new inbound configuration.
  863. // It validates port uniqueness, client email uniqueness, and required fields,
  864. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  865. // Returns the created inbound, whether Xray needs restart, and any error.
  866. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  867. inbound.Id = 0
  868. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  869. // Normalize streamSettings based on protocol
  870. s.normalizeStreamSettings(inbound)
  871. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  872. return inbound, false, err
  873. }
  874. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  875. return inbound, false, err
  876. }
  877. s.normalizeMtprotoSecret(inbound)
  878. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  879. return inbound, false, err
  880. }
  881. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  882. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  883. return inbound, false, err
  884. }
  885. conflict, err := s.checkPortConflict(inbound, 0)
  886. if err != nil {
  887. return inbound, false, err
  888. }
  889. if conflict != nil {
  890. return inbound, false, common.NewError(conflict.String())
  891. }
  892. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  893. if err != nil {
  894. return inbound, false, err
  895. }
  896. clients, err := s.GetClients(inbound)
  897. if err != nil {
  898. return inbound, false, err
  899. }
  900. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  901. if err != nil {
  902. return inbound, false, err
  903. }
  904. if existEmail != "" {
  905. return inbound, false, common.NewError("Duplicate email:", existEmail)
  906. }
  907. if inbound.DisableFlow {
  908. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  909. inbound.Settings = stripped
  910. }
  911. for i := range clients {
  912. clients[i].Flow = ""
  913. }
  914. }
  915. // Ensure created_at and updated_at on clients in settings
  916. if len(clients) > 0 {
  917. var settings map[string]any
  918. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  919. now := time.Now().Unix() * 1000
  920. updatedClients := make([]model.Client, 0, len(clients))
  921. for _, c := range clients {
  922. if c.CreatedAt == 0 {
  923. c.CreatedAt = now
  924. }
  925. c.UpdatedAt = now
  926. updatedClients = append(updatedClients, c)
  927. }
  928. settings["clients"] = updatedClients
  929. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  930. inbound.Settings = string(bs)
  931. } else {
  932. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  933. }
  934. } else if err2 != nil {
  935. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  936. }
  937. }
  938. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  939. // the inbound method (e.g. an API caller supplied a wrong-size key).
  940. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  941. inbound.Settings = normalized
  942. }
  943. // Secure client ID
  944. for _, client := range clients {
  945. switch inbound.Protocol {
  946. case "trojan":
  947. if client.Password == "" {
  948. return inbound, false, common.NewError("empty client ID")
  949. }
  950. case "shadowsocks":
  951. if client.Email == "" {
  952. return inbound, false, common.NewError("empty client ID")
  953. }
  954. case "hysteria":
  955. if client.Auth == "" {
  956. return inbound, false, common.NewError("empty client ID")
  957. }
  958. case "wireguard":
  959. if client.PublicKey == "" {
  960. return inbound, false, common.NewError("wireguard client requires a key")
  961. }
  962. case "mtproto":
  963. if client.Secret == "" {
  964. return inbound, false, common.NewError("mtproto client requires a secret")
  965. }
  966. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  967. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  968. }
  969. default:
  970. if client.ID == "" {
  971. return inbound, false, common.NewError("empty client ID")
  972. }
  973. }
  974. }
  975. db := database.GetDB()
  976. needRestart := false
  977. var postCommitApply func()
  978. err = db.Transaction(func(tx *gorm.DB) error {
  979. markDirty := false
  980. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  981. return err
  982. }
  983. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  984. // Enable=true on every imported stat row) are authoritative for this call
  985. // and must not be clobbered by the AddClientStat loop below, which derives
  986. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  987. // possibly-stale source for the same columns on a plain (non-import) create.
  988. statEmails := make(map[string]bool, len(inbound.ClientStats))
  989. for i := range inbound.ClientStats {
  990. if inbound.ClientStats[i].Email == "" {
  991. continue
  992. }
  993. statEmails[inbound.ClientStats[i].Email] = true
  994. inbound.ClientStats[i].Id = 0
  995. inbound.ClientStats[i].InboundId = inbound.Id
  996. if err := tx.Clauses(clause.OnConflict{
  997. Columns: []clause.Column{{Name: "email"}},
  998. DoNothing: true,
  999. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  1000. return err
  1001. }
  1002. }
  1003. for _, client := range clients {
  1004. if statEmails[client.Email] {
  1005. continue
  1006. }
  1007. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  1008. return err
  1009. }
  1010. }
  1011. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  1012. return err
  1013. }
  1014. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  1015. return err
  1016. }
  1017. if inbound.NodeID != nil {
  1018. nodeID := *inbound.NodeID
  1019. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  1020. return err
  1021. }
  1022. }
  1023. if inbound.Enable {
  1024. if inbound.NodeID != nil {
  1025. markDirty = true
  1026. } else {
  1027. rt, push, _, perr := s.nodePushPlan(inbound)
  1028. if perr != nil {
  1029. return perr
  1030. }
  1031. if push {
  1032. payload := inbound
  1033. pushable := true
  1034. if inbound.Protocol == model.MTProto {
  1035. if built, bErr := s.buildInboundForLocalRuntime(tx, inbound); bErr == nil {
  1036. payload = built
  1037. } else {
  1038. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  1039. pushable = false
  1040. }
  1041. }
  1042. if pushable {
  1043. postCommitApply = func() {
  1044. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  1045. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  1046. } else {
  1047. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  1048. needRestart = true
  1049. }
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if markDirty && inbound.NodeID != nil {
  1056. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1057. }
  1058. return nil
  1059. })
  1060. if err != nil {
  1061. return inbound, false, err
  1062. }
  1063. if postCommitApply != nil {
  1064. postCommitApply()
  1065. }
  1066. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1067. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1068. // in the generated config, so force a regen to wire it in.
  1069. if mtprotoRoutesThroughXray(inbound) {
  1070. needRestart = true
  1071. }
  1072. return inbound, needRestart, err
  1073. }
  1074. func (s *InboundService) DelInbound(id int) (bool, error) {
  1075. db := database.GetDB()
  1076. needRestart := false
  1077. var postCommitApply func()
  1078. var ib model.Inbound
  1079. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1080. if loadErr == nil {
  1081. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1082. if shouldPushToRuntime {
  1083. if ib.NodeID != nil {
  1084. rt, push, _, perr := s.nodePushPlan(&ib)
  1085. if perr != nil {
  1086. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1087. } else if push {
  1088. postCommitApply = func() {
  1089. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1090. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1091. } else {
  1092. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1093. }
  1094. }
  1095. }
  1096. } else {
  1097. rt, push, _, perr := s.nodePushPlan(&ib)
  1098. if perr != nil {
  1099. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1100. } else if push {
  1101. postCommitApply = func() {
  1102. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1103. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1104. } else {
  1105. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1106. needRestart = true
  1107. }
  1108. }
  1109. } else {
  1110. needRestart = true
  1111. }
  1112. }
  1113. } else {
  1114. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1115. }
  1116. } else {
  1117. logger.Debug("DelInbound: inbound not found, id:", id)
  1118. }
  1119. if err := db.Transaction(func(tx *gorm.DB) error {
  1120. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1121. return err
  1122. }
  1123. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1124. return err
  1125. }
  1126. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1127. return err
  1128. }
  1129. if loadErr == nil && ib.NodeID != nil {
  1130. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1131. }
  1132. return nil
  1133. }); err != nil {
  1134. return needRestart, err
  1135. }
  1136. if postCommitApply != nil {
  1137. postCommitApply()
  1138. }
  1139. if loadErr == nil && ib.Tag != "" {
  1140. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1141. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1142. } else if routingChanged {
  1143. needRestart = true
  1144. }
  1145. }
  1146. if !database.IsPostgres() {
  1147. var count int64
  1148. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1149. return needRestart, err
  1150. }
  1151. if count == 0 {
  1152. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1153. return needRestart, err
  1154. }
  1155. }
  1156. }
  1157. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1158. if mtprotoRoutesThroughXray(&ib) {
  1159. needRestart = true
  1160. }
  1161. return needRestart, nil
  1162. }
  1163. type BulkDelInboundResult struct {
  1164. Deleted int `json:"deleted"`
  1165. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1166. }
  1167. type BulkDelInboundReport struct {
  1168. Id int `json:"id"`
  1169. Reason string `json:"reason"`
  1170. }
  1171. // DelInbounds removes every inbound in the list, reusing the single-delete
  1172. // path per id. Failures are recorded in Skipped and processing continues for
  1173. // the rest; the aggregated needRestart is returned so the caller restarts
  1174. // xray at most once.
  1175. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1176. result := BulkDelInboundResult{}
  1177. needRestart := false
  1178. for _, id := range ids {
  1179. r, err := s.DelInbound(id)
  1180. if err != nil {
  1181. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1182. continue
  1183. }
  1184. result.Deleted++
  1185. if r {
  1186. needRestart = true
  1187. }
  1188. }
  1189. return result, needRestart, nil
  1190. }
  1191. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1192. db := database.GetDB()
  1193. inbound := &model.Inbound{}
  1194. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1195. if err != nil {
  1196. return nil, err
  1197. }
  1198. return inbound, nil
  1199. }
  1200. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1201. db := database.GetDB()
  1202. inbound := &model.Inbound{}
  1203. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. s.enrichClientStats(db, []*model.Inbound{inbound})
  1208. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1209. return inbound, nil
  1210. }
  1211. // SetInboundSubSortIndex changes only the subscription sort order, so a
  1212. // reorder cannot carry a stale settings/client payload over another edit.
  1213. func (s *InboundService) SetInboundSubSortIndex(id int, index int) error {
  1214. index = normalizeSubSortIndex(index)
  1215. inbound, err := s.GetInbound(id)
  1216. if err != nil {
  1217. return err
  1218. }
  1219. if inbound.SubSortIndex == index {
  1220. return nil
  1221. }
  1222. db := database.GetDB()
  1223. if err := db.Transaction(func(tx *gorm.DB) error {
  1224. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1225. Update("sub_sort_index", index).Error; err != nil {
  1226. return err
  1227. }
  1228. if inbound.NodeID != nil {
  1229. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1230. }
  1231. return nil
  1232. }); err != nil {
  1233. return err
  1234. }
  1235. inbound.SubSortIndex = index
  1236. if inbound.NodeID == nil {
  1237. return nil
  1238. }
  1239. rt, push, _, perr := s.nodePushPlan(inbound)
  1240. if perr != nil {
  1241. return perr
  1242. }
  1243. if push {
  1244. narrow, ok := rt.(interface {
  1245. SetInboundSubSortIndex(context.Context, *model.Inbound, int) error
  1246. })
  1247. if !ok {
  1248. return fmt.Errorf("runtime %s does not support narrow subscription ordering updates", rt.Name())
  1249. }
  1250. if err := narrow.SetInboundSubSortIndex(context.Background(), inbound, index); err != nil {
  1251. logger.Warning("SetInboundSubSortIndex: remote metadata update on", rt.Name(), "failed:", err)
  1252. }
  1253. }
  1254. return nil
  1255. }
  1256. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1257. inbound, err := s.GetInbound(id)
  1258. if err != nil {
  1259. return false, err
  1260. }
  1261. if inbound.Enable == enable {
  1262. return false, nil
  1263. }
  1264. db := database.GetDB()
  1265. if err := db.Transaction(func(tx *gorm.DB) error {
  1266. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1267. Update("enable", enable).Error; err != nil {
  1268. return err
  1269. }
  1270. if inbound.NodeID != nil {
  1271. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1272. }
  1273. return nil
  1274. }); err != nil {
  1275. return false, err
  1276. }
  1277. inbound.Enable = enable
  1278. needRestart := false
  1279. rt, push, _, perr := s.nodePushPlan(inbound)
  1280. if perr != nil {
  1281. return false, perr
  1282. }
  1283. // Remote nodes interpret DelInbound as a real row delete (it hits
  1284. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1285. // switch on a remote inbound used to wipe the row entirely (#4402).
  1286. // PATCH the remote row via UpdateInbound instead — preserves the
  1287. // settings/client history and just flips the enable flag.
  1288. if inbound.NodeID != nil {
  1289. if push {
  1290. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1291. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1292. }
  1293. }
  1294. return false, nil
  1295. }
  1296. if mtprotoRoutesThroughXray(inbound) {
  1297. needRestart = true
  1298. }
  1299. if !push {
  1300. return true, nil
  1301. }
  1302. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1303. !strings.Contains(err.Error(), "not found") {
  1304. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1305. needRestart = true
  1306. }
  1307. if !enable {
  1308. return needRestart, nil
  1309. }
  1310. runtimeInbound, err := s.buildInboundForLocalRuntime(db, inbound)
  1311. if err != nil {
  1312. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1313. return true, nil
  1314. }
  1315. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1316. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1317. needRestart = true
  1318. }
  1319. return needRestart, nil
  1320. }
  1321. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1322. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1323. // Normalize streamSettings based on protocol
  1324. s.normalizeStreamSettings(inbound)
  1325. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1326. return inbound, false, err
  1327. }
  1328. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1329. return inbound, false, err
  1330. }
  1331. s.normalizeMtprotoSecret(inbound)
  1332. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1333. oldInbound, err := s.GetInbound(inbound.Id)
  1334. if err != nil {
  1335. return inbound, false, err
  1336. }
  1337. // Restore the stored NodeID before the port-conflict check so a node inbound
  1338. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1339. inbound.NodeID = oldInbound.NodeID
  1340. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1341. if err != nil {
  1342. return inbound, false, err
  1343. }
  1344. if conflict != nil {
  1345. return inbound, false, common.NewError(conflict.String())
  1346. }
  1347. // Capture the pre-edit protocol and routing state before oldInbound is
  1348. // overwritten with the new values further down, then ensure a routed
  1349. // inbound keeps a stable egress port (reusing the one already stored).
  1350. oldProtocol := oldInbound.Protocol
  1351. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1352. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1353. return inbound, false, err
  1354. }
  1355. tag := oldInbound.Tag
  1356. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1357. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1358. needRestart := false
  1359. var postCommitApply func()
  1360. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1361. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1362. return err
  1363. }
  1364. // Ensure created_at and updated_at exist in inbound.Settings clients
  1365. {
  1366. var oldSettings map[string]any
  1367. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1368. emailToCreated := map[string]int64{}
  1369. emailToUpdated := map[string]int64{}
  1370. if oldSettings != nil {
  1371. if oc, ok := oldSettings["clients"].([]any); ok {
  1372. for _, it := range oc {
  1373. if m, ok2 := it.(map[string]any); ok2 {
  1374. if email, ok3 := m["email"].(string); ok3 {
  1375. switch v := m["created_at"].(type) {
  1376. case float64:
  1377. emailToCreated[email] = int64(v)
  1378. case int64:
  1379. emailToCreated[email] = v
  1380. }
  1381. switch v := m["updated_at"].(type) {
  1382. case float64:
  1383. emailToUpdated[email] = int64(v)
  1384. case int64:
  1385. emailToUpdated[email] = v
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. }
  1392. var newSettings map[string]any
  1393. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1394. now := time.Now().Unix() * 1000
  1395. if nSlice, ok := newSettings["clients"].([]any); ok {
  1396. for i := range nSlice {
  1397. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1398. email, _ := m["email"].(string)
  1399. if _, ok3 := m["created_at"]; !ok3 {
  1400. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1401. m["created_at"] = v
  1402. } else {
  1403. m["created_at"] = now
  1404. }
  1405. }
  1406. // Preserve client's updated_at if present; do not bump on parent inbound update
  1407. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1408. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1409. m["updated_at"] = v
  1410. }
  1411. }
  1412. nSlice[i] = m
  1413. }
  1414. }
  1415. newSettings["clients"] = nSlice
  1416. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1417. inbound.Settings = string(bs)
  1418. }
  1419. }
  1420. }
  1421. }
  1422. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1423. // keep their old length and would be rejected by xray. Regenerate mismatched
  1424. // client keys so the inbound stays connectable.
  1425. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1426. inbound.Settings = normalized
  1427. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1428. }
  1429. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1430. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1431. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1432. // but was stripped while the inbound was ineligible.
  1433. if !inbound.DisableFlow {
  1434. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1435. inbound.Settings = restored
  1436. }
  1437. } else {
  1438. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1439. inbound.Settings = stripped
  1440. }
  1441. }
  1442. oldInbound.Total = inbound.Total
  1443. oldInbound.Remark = inbound.Remark
  1444. oldInbound.SubSortIndex = inbound.SubSortIndex
  1445. oldInbound.Enable = inbound.Enable
  1446. oldInbound.ExpiryTime = inbound.ExpiryTime
  1447. oldInbound.TrafficReset = inbound.TrafficReset
  1448. oldInbound.TrafficResetDay = inbound.TrafficResetDay
  1449. oldInbound.Listen = inbound.Listen
  1450. oldInbound.Port = inbound.Port
  1451. oldInbound.Protocol = inbound.Protocol
  1452. oldInbound.DisableFlow = inbound.DisableFlow
  1453. oldInbound.Settings = inbound.Settings
  1454. oldInbound.StreamSettings = inbound.StreamSettings
  1455. oldInbound.Sniffing = inbound.Sniffing
  1456. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1457. normalizeInboundShareAddress(oldInbound)
  1458. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1459. inbound.ShareAddr = oldInbound.ShareAddr
  1460. } else {
  1461. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1462. return err
  1463. }
  1464. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1465. oldInbound.ShareAddr = inbound.ShareAddr
  1466. }
  1467. if oldTagWasAuto && inbound.Tag == tag {
  1468. inbound.Tag = ""
  1469. }
  1470. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1471. if err != nil {
  1472. return err
  1473. }
  1474. oldInbound.Tag = resolvedTag
  1475. inbound.Tag = oldInbound.Tag
  1476. if oldInbound.NodeID == nil {
  1477. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1478. if perr != nil {
  1479. return perr
  1480. }
  1481. if !push {
  1482. needRestart = true
  1483. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1484. oldSnapshot := *oldInbound
  1485. oldSnapshot.Tag = tag
  1486. oldSnapshot.Protocol = oldProtocol
  1487. payload := oldInbound
  1488. pushable := true
  1489. if inbound.Enable {
  1490. if built, err2 := s.buildInboundForLocalRuntime(tx, oldInbound); err2 == nil {
  1491. payload = built
  1492. } else {
  1493. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1494. pushable = false
  1495. }
  1496. }
  1497. newProtocolIsMtproto := oldInbound.Protocol == model.MTProto
  1498. if pushable {
  1499. postCommitApply = func() {
  1500. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1501. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1502. } else {
  1503. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1504. if !newProtocolIsMtproto {
  1505. needRestart = true
  1506. }
  1507. }
  1508. }
  1509. }
  1510. } else {
  1511. oldSnapshot := *oldInbound
  1512. oldSnapshot.Tag = tag
  1513. var runtimeInbound *model.Inbound
  1514. if inbound.Enable {
  1515. var err2 error
  1516. runtimeInbound, err2 = s.buildInboundForLocalRuntime(tx, oldInbound)
  1517. if err2 != nil {
  1518. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1519. needRestart = true
  1520. }
  1521. }
  1522. postCommitApply = func() {
  1523. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1524. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1525. }
  1526. if runtimeInbound == nil {
  1527. return
  1528. }
  1529. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1530. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1531. } else {
  1532. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1533. needRestart = true
  1534. }
  1535. }
  1536. }
  1537. } else {
  1538. nodeID := *oldInbound.NodeID
  1539. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1540. return err
  1541. }
  1542. }
  1543. if err := tx.Save(oldInbound).Error; err != nil {
  1544. return err
  1545. }
  1546. newClients, gcErr := s.GetClients(oldInbound)
  1547. if gcErr != nil {
  1548. return gcErr
  1549. }
  1550. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1551. return err
  1552. }
  1553. if oldInbound.NodeID != nil {
  1554. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1555. return err
  1556. }
  1557. }
  1558. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1559. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1560. // settings.
  1561. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1562. needRestart = true
  1563. }
  1564. return nil
  1565. })
  1566. if txErr != nil {
  1567. return inbound, false, txErr
  1568. }
  1569. if postCommitApply != nil {
  1570. postCommitApply()
  1571. }
  1572. // After the rename is committed, point any routing rules / loopback outbounds
  1573. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1574. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1575. // can't roll back the inbound edit.
  1576. if tag != oldInbound.Tag {
  1577. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1578. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1579. } else if routingChanged {
  1580. needRestart = true
  1581. }
  1582. }
  1583. return inbound, needRestart, nil
  1584. }
  1585. // A node mirrors this payload into its own DB, so every client must survive:
  1586. // filtering one out makes the node delete it, and the master then mirrors that.
  1587. func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1588. if inbound == nil {
  1589. return nil, fmt.Errorf("inbound is nil")
  1590. }
  1591. built := *inbound
  1592. settings := map[string]any{}
  1593. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1594. return nil, err
  1595. }
  1596. if !inboundCanHostFallbacks(inbound) {
  1597. return &built, nil
  1598. }
  1599. fallbacks, err := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  1600. if err != nil {
  1601. return nil, err
  1602. }
  1603. if len(fallbacks) == 0 {
  1604. return &built, nil
  1605. }
  1606. generic := make([]any, 0, len(fallbacks))
  1607. for _, f := range fallbacks {
  1608. generic = append(generic, f)
  1609. }
  1610. settings["fallbacks"] = generic
  1611. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1612. if mErr != nil {
  1613. return nil, mErr
  1614. }
  1615. built.Settings = string(modifiedSettings)
  1616. return &built, nil
  1617. }
  1618. // Strips disabled clients on top of the node payload. Safe only because the
  1619. // target here is an in-memory Xray/mtg config, not another panel's database.
  1620. func (s *InboundService) buildInboundForLocalRuntime(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1621. built, err := s.buildInboundForNodePush(tx, inbound)
  1622. if err != nil {
  1623. return nil, err
  1624. }
  1625. settings := map[string]any{}
  1626. if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil {
  1627. return nil, err
  1628. }
  1629. clients, ok := settings["clients"].([]any)
  1630. if !ok {
  1631. return built, nil
  1632. }
  1633. var clientStats []xray.ClientTraffic
  1634. if err := tx.Model(xray.ClientTraffic{}).
  1635. Where("inbound_id = ?", built.Id).
  1636. Select("email", "enable").
  1637. Find(&clientStats).Error; err != nil {
  1638. return nil, err
  1639. }
  1640. enableMap := make(map[string]bool, len(clientStats))
  1641. for _, clientTraffic := range clientStats {
  1642. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1643. }
  1644. finalClients := make([]any, 0, len(clients))
  1645. for _, client := range clients {
  1646. c, ok := client.(map[string]any)
  1647. if !ok {
  1648. continue
  1649. }
  1650. email, _ := c["email"].(string)
  1651. if enable, exists := enableMap[email]; exists && !enable {
  1652. continue
  1653. }
  1654. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1655. continue
  1656. }
  1657. finalClients = append(finalClients, c)
  1658. }
  1659. settings["clients"] = finalClients
  1660. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1661. if err != nil {
  1662. return nil, err
  1663. }
  1664. runtimeInbound := *built
  1665. runtimeInbound.Settings = string(modifiedSettings)
  1666. return &runtimeInbound, nil
  1667. }
  1668. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1669. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1670. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1671. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1672. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1673. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1674. oldClients, err := s.GetClients(oldInbound)
  1675. if err != nil {
  1676. return err
  1677. }
  1678. newClients, err := s.GetClients(newInbound)
  1679. if err != nil {
  1680. return err
  1681. }
  1682. // Email is the unique key for ClientTraffic rows. Clients without an
  1683. // email have no stats row to sync — skip them on both sides instead of
  1684. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1685. oldEmails := make(map[string]struct{}, len(oldClients))
  1686. for i := range oldClients {
  1687. if oldClients[i].Email == "" {
  1688. continue
  1689. }
  1690. oldEmails[oldClients[i].Email] = struct{}{}
  1691. }
  1692. newEmails := make(map[string]struct{}, len(newClients))
  1693. for i := range newClients {
  1694. if newClients[i].Email == "" {
  1695. continue
  1696. }
  1697. newEmails[newClients[i].Email] = struct{}{}
  1698. }
  1699. // Drop stats rows for removed emails — but not when a sibling inbound
  1700. // still references the email, since the row is the shared accumulator.
  1701. for i := range oldClients {
  1702. email := oldClients[i].Email
  1703. if email == "" {
  1704. continue
  1705. }
  1706. if _, kept := newEmails[email]; kept {
  1707. continue
  1708. }
  1709. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1710. if err != nil {
  1711. return err
  1712. }
  1713. if stillUsed {
  1714. continue
  1715. }
  1716. if err := s.DelClientStat(tx, email); err != nil {
  1717. return err
  1718. }
  1719. // Keep inbound_client_ips in sync when the inbound edit drops an
  1720. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1721. if err := s.DelClientIPs(tx, email); err != nil {
  1722. return err
  1723. }
  1724. }
  1725. for i := range newClients {
  1726. email := newClients[i].Email
  1727. if email == "" {
  1728. continue
  1729. }
  1730. if _, existed := oldEmails[email]; existed {
  1731. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1732. return err
  1733. }
  1734. continue
  1735. }
  1736. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1737. return err
  1738. }
  1739. }
  1740. return nil
  1741. }
  1742. func (s *InboundService) GetInboundTags() (string, error) {
  1743. db := database.GetDB()
  1744. var inboundTags []string
  1745. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1746. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1747. return "", err
  1748. }
  1749. tags, _ := json.Marshal(inboundTags)
  1750. return string(tags), nil
  1751. }
  1752. func (s *InboundService) GetClientReverseTags() (string, error) {
  1753. db := database.GetDB()
  1754. var inbounds []model.Inbound
  1755. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1756. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1757. return "[]", err
  1758. }
  1759. tagSet := make(map[string]struct{})
  1760. for _, inbound := range inbounds {
  1761. var settings map[string]any
  1762. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1763. continue
  1764. }
  1765. clients, ok := settings["clients"].([]any)
  1766. if !ok {
  1767. continue
  1768. }
  1769. for _, client := range clients {
  1770. clientMap, ok := client.(map[string]any)
  1771. if !ok {
  1772. continue
  1773. }
  1774. reverse, ok := clientMap["reverse"].(map[string]any)
  1775. if !ok {
  1776. continue
  1777. }
  1778. tag, _ := reverse["tag"].(string)
  1779. tag = strings.TrimSpace(tag)
  1780. if tag != "" {
  1781. tagSet[tag] = struct{}{}
  1782. }
  1783. }
  1784. }
  1785. rawTags := make([]string, 0, len(tagSet))
  1786. for tag := range tagSet {
  1787. rawTags = append(rawTags, tag)
  1788. }
  1789. sort.Strings(rawTags)
  1790. result, _ := json.Marshal(rawTags)
  1791. return string(result), nil
  1792. }
  1793. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1794. db := database.GetDB()
  1795. var inbounds []*model.Inbound
  1796. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1797. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1798. return nil, err
  1799. }
  1800. return inbounds, nil
  1801. }