inbound.go 49 KB

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