1
0

inbound.go 50 KB

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