1
0

inbound.go 62 KB

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