inbound.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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. default:
  702. if client.ID == "" {
  703. return inbound, false, common.NewError("empty client ID")
  704. }
  705. }
  706. }
  707. db := database.GetDB()
  708. tx := db.Begin()
  709. markDirty := false
  710. defer func() {
  711. if err != nil {
  712. tx.Rollback()
  713. return
  714. }
  715. if markDirty && inbound.NodeID != nil {
  716. if dErr := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); dErr != nil {
  717. err = dErr
  718. tx.Rollback()
  719. return
  720. }
  721. }
  722. tx.Commit()
  723. }()
  724. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  725. // those rows with an ON CONFLICT target on the primary key only, which
  726. // collides with the globally-unique client_traffics.email when an imported
  727. // inbound carries clients that another inbound already created (e.g.
  728. // importing two inbounds that share the same clients). We insert the stats
  729. // ourselves below with the same email-conflict guard AddClientStat uses.
  730. err = tx.Omit("ClientStats").Save(inbound).Error
  731. if err != nil {
  732. return inbound, false, err
  733. }
  734. // Imported stats first, so their traffic counters survive; emails that
  735. // already own a (shared) row are skipped instead of tripping the unique
  736. // constraint.
  737. for i := range inbound.ClientStats {
  738. if inbound.ClientStats[i].Email == "" {
  739. continue
  740. }
  741. inbound.ClientStats[i].Id = 0
  742. inbound.ClientStats[i].InboundId = inbound.Id
  743. if err = tx.Clauses(clause.OnConflict{
  744. Columns: []clause.Column{{Name: "email"}},
  745. DoNothing: true,
  746. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  747. return inbound, false, err
  748. }
  749. }
  750. // Then make sure every client has a stats row. AddClientStat is a no-op
  751. // where one exists (including the rows just inserted), and fills the gap
  752. // for clients an import payload didn't carry stats for.
  753. for _, client := range clients {
  754. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  755. return inbound, false, err
  756. }
  757. }
  758. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  759. return inbound, false, err
  760. }
  761. // Legacy import: an inbound exported from a build that predated the hosts
  762. // table carries its external proxies inline in streamSettings.externalProxy.
  763. // The startup migration that converts those to host rows runs once and is
  764. // gated off afterwards, so it never sees a freshly imported inbound —
  765. // reproduce it here. No-op for inbounds without externalProxy (everything the
  766. // current UI builds), so this only fires on such imports.
  767. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  768. return inbound, false, err
  769. }
  770. // Before the deferred commit, so a node in "selected" sync mode cannot
  771. // sweep the new central row in the gap before its tag is allowed.
  772. if inbound.NodeID != nil {
  773. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  774. logger.Warning("allow inbound tag on node failed:", aErr)
  775. }
  776. }
  777. needRestart := false
  778. if inbound.Enable {
  779. rt, push, dirty, perr := s.nodePushPlan(inbound)
  780. if perr != nil {
  781. err = perr
  782. return inbound, false, err
  783. }
  784. if dirty {
  785. markDirty = true
  786. }
  787. if push {
  788. payload := inbound
  789. pushable := true
  790. if inbound.NodeID == nil && inbound.Protocol == model.MTProto {
  791. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  792. payload = built
  793. } else {
  794. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  795. pushable = false
  796. }
  797. }
  798. if pushable {
  799. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  800. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  801. } else {
  802. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  803. if inbound.NodeID != nil {
  804. markDirty = true
  805. } else if inbound.Protocol != model.MTProto {
  806. needRestart = true
  807. }
  808. }
  809. }
  810. }
  811. }
  812. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  813. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  814. // in the generated config, so force a regen to wire it in.
  815. if mtprotoRoutesThroughXray(inbound) {
  816. needRestart = true
  817. }
  818. return inbound, needRestart, err
  819. }
  820. func (s *InboundService) DelInbound(id int) (bool, error) {
  821. db := database.GetDB()
  822. needRestart := false
  823. markDirty := false
  824. var ib model.Inbound
  825. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  826. if loadErr == nil {
  827. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  828. if shouldPushToRuntime {
  829. rt, push, dirty, perr := s.nodePushPlan(&ib)
  830. if perr != nil {
  831. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  832. markDirty = true
  833. } else if push {
  834. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  835. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  836. } else {
  837. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  838. if ib.NodeID == nil {
  839. needRestart = true
  840. } else {
  841. markDirty = true
  842. }
  843. }
  844. } else if ib.NodeID == nil {
  845. needRestart = true
  846. } else if dirty {
  847. markDirty = true
  848. }
  849. } else {
  850. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  851. }
  852. } else {
  853. logger.Debug("DelInbound: inbound not found, id:", id)
  854. }
  855. if err := s.clientService.DetachInbound(db, id); err != nil {
  856. return false, err
  857. }
  858. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  859. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  860. if loadErr == nil && ib.Tag != "" {
  861. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  862. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  863. } else if routingChanged {
  864. needRestart = true
  865. }
  866. }
  867. if err := db.Transaction(func(tx *gorm.DB) error {
  868. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  869. return err
  870. }
  871. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  872. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  873. return err
  874. }
  875. if markDirty && ib.NodeID != nil {
  876. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  877. }
  878. return nil
  879. }); err != nil {
  880. return needRestart, err
  881. }
  882. if !database.IsPostgres() {
  883. var count int64
  884. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  885. return needRestart, err
  886. }
  887. if count == 0 {
  888. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  889. return needRestart, err
  890. }
  891. }
  892. }
  893. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  894. if mtprotoRoutesThroughXray(&ib) {
  895. needRestart = true
  896. }
  897. return needRestart, nil
  898. }
  899. type BulkDelInboundResult struct {
  900. Deleted int `json:"deleted"`
  901. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  902. }
  903. type BulkDelInboundReport struct {
  904. Id int `json:"id"`
  905. Reason string `json:"reason"`
  906. }
  907. // DelInbounds removes every inbound in the list, reusing the single-delete
  908. // path per id. Failures are recorded in Skipped and processing continues for
  909. // the rest; the aggregated needRestart is returned so the caller restarts
  910. // xray at most once.
  911. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  912. result := BulkDelInboundResult{}
  913. needRestart := false
  914. for _, id := range ids {
  915. r, err := s.DelInbound(id)
  916. if err != nil {
  917. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  918. continue
  919. }
  920. result.Deleted++
  921. if r {
  922. needRestart = true
  923. }
  924. }
  925. return result, needRestart, nil
  926. }
  927. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  928. db := database.GetDB()
  929. inbound := &model.Inbound{}
  930. err := db.Model(model.Inbound{}).First(inbound, id).Error
  931. if err != nil {
  932. return nil, err
  933. }
  934. return inbound, nil
  935. }
  936. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  937. db := database.GetDB()
  938. inbound := &model.Inbound{}
  939. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  940. if err != nil {
  941. return nil, err
  942. }
  943. s.enrichClientStats(db, []*model.Inbound{inbound})
  944. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  945. return inbound, nil
  946. }
  947. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  948. inbound, err := s.GetInbound(id)
  949. if err != nil {
  950. return false, err
  951. }
  952. if inbound.Enable == enable {
  953. return false, nil
  954. }
  955. db := database.GetDB()
  956. if err := db.Transaction(func(tx *gorm.DB) error {
  957. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  958. Update("enable", enable).Error; err != nil {
  959. return err
  960. }
  961. if inbound.NodeID != nil {
  962. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  963. }
  964. return nil
  965. }); err != nil {
  966. return false, err
  967. }
  968. inbound.Enable = enable
  969. needRestart := false
  970. rt, push, _, perr := s.nodePushPlan(inbound)
  971. if perr != nil {
  972. return false, perr
  973. }
  974. // Remote nodes interpret DelInbound as a real row delete (it hits
  975. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  976. // switch on a remote inbound used to wipe the row entirely (#4402).
  977. // PATCH the remote row via UpdateInbound instead — preserves the
  978. // settings/client history and just flips the enable flag.
  979. if inbound.NodeID != nil {
  980. if push {
  981. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  982. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  983. }
  984. }
  985. return false, nil
  986. }
  987. if !push {
  988. return true, nil
  989. }
  990. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  991. !strings.Contains(err.Error(), "not found") {
  992. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  993. needRestart = true
  994. }
  995. if !enable {
  996. return needRestart, nil
  997. }
  998. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  999. if err != nil {
  1000. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1001. return true, nil
  1002. }
  1003. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1004. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1005. needRestart = true
  1006. }
  1007. return needRestart, nil
  1008. }
  1009. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1010. // Normalize streamSettings based on protocol
  1011. s.normalizeStreamSettings(inbound)
  1012. s.normalizeMtprotoSecret(inbound)
  1013. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1014. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1015. if err != nil {
  1016. return inbound, false, err
  1017. }
  1018. if conflict != nil {
  1019. return inbound, false, common.NewError(conflict.String())
  1020. }
  1021. oldInbound, err := s.GetInbound(inbound.Id)
  1022. if err != nil {
  1023. return inbound, false, err
  1024. }
  1025. inbound.NodeID = oldInbound.NodeID
  1026. // Capture the pre-edit protocol and routing state before oldInbound is
  1027. // overwritten with the new values further down, then ensure a routed
  1028. // inbound keeps a stable egress port (reusing the one already stored).
  1029. oldProtocol := oldInbound.Protocol
  1030. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1031. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1032. return inbound, false, err
  1033. }
  1034. tag := oldInbound.Tag
  1035. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1036. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1037. needRestart := false
  1038. // Persist the client-stat sync, settings munging, runtime push and inbound
  1039. // save as one transaction routed through the serial traffic writer, so it
  1040. // never runs concurrently with the @every 5s traffic poll. Both touch
  1041. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  1042. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  1043. //
  1044. // The runtime push stays inside the transaction here (unlike the client-edit
  1045. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  1046. // node before the central row is committed, or a "selected"-mode node would
  1047. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  1048. // holding the writer across the node call is an acceptable trade.
  1049. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1050. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1051. return err
  1052. }
  1053. // Ensure created_at and updated_at exist in inbound.Settings clients
  1054. {
  1055. var oldSettings map[string]any
  1056. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1057. emailToCreated := map[string]int64{}
  1058. emailToUpdated := map[string]int64{}
  1059. if oldSettings != nil {
  1060. if oc, ok := oldSettings["clients"].([]any); ok {
  1061. for _, it := range oc {
  1062. if m, ok2 := it.(map[string]any); ok2 {
  1063. if email, ok3 := m["email"].(string); ok3 {
  1064. switch v := m["created_at"].(type) {
  1065. case float64:
  1066. emailToCreated[email] = int64(v)
  1067. case int64:
  1068. emailToCreated[email] = v
  1069. }
  1070. switch v := m["updated_at"].(type) {
  1071. case float64:
  1072. emailToUpdated[email] = int64(v)
  1073. case int64:
  1074. emailToUpdated[email] = v
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. }
  1081. var newSettings map[string]any
  1082. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1083. now := time.Now().Unix() * 1000
  1084. if nSlice, ok := newSettings["clients"].([]any); ok {
  1085. for i := range nSlice {
  1086. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1087. email, _ := m["email"].(string)
  1088. if _, ok3 := m["created_at"]; !ok3 {
  1089. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1090. m["created_at"] = v
  1091. } else {
  1092. m["created_at"] = now
  1093. }
  1094. }
  1095. // Preserve client's updated_at if present; do not bump on parent inbound update
  1096. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1097. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1098. m["updated_at"] = v
  1099. }
  1100. }
  1101. nSlice[i] = m
  1102. }
  1103. }
  1104. newSettings["clients"] = nSlice
  1105. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1106. inbound.Settings = string(bs)
  1107. }
  1108. }
  1109. }
  1110. }
  1111. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1112. // keep their old length and would be rejected by xray. Regenerate mismatched
  1113. // client keys so the inbound stays connectable.
  1114. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1115. inbound.Settings = normalized
  1116. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1117. }
  1118. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1119. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1120. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1121. // but was stripped while the inbound was ineligible.
  1122. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1123. inbound.Settings = restored
  1124. }
  1125. oldInbound.Total = inbound.Total
  1126. oldInbound.Remark = inbound.Remark
  1127. oldInbound.SubSortIndex = inbound.SubSortIndex
  1128. oldInbound.Enable = inbound.Enable
  1129. oldInbound.ExpiryTime = inbound.ExpiryTime
  1130. oldInbound.TrafficReset = inbound.TrafficReset
  1131. oldInbound.Listen = inbound.Listen
  1132. oldInbound.Port = inbound.Port
  1133. oldInbound.Protocol = inbound.Protocol
  1134. oldInbound.Settings = inbound.Settings
  1135. oldInbound.StreamSettings = inbound.StreamSettings
  1136. oldInbound.Sniffing = inbound.Sniffing
  1137. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1138. normalizeInboundShareAddress(oldInbound)
  1139. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1140. inbound.ShareAddr = oldInbound.ShareAddr
  1141. } else {
  1142. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1143. return err
  1144. }
  1145. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1146. oldInbound.ShareAddr = inbound.ShareAddr
  1147. }
  1148. if oldTagWasAuto && inbound.Tag == tag {
  1149. inbound.Tag = ""
  1150. }
  1151. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1152. if err != nil {
  1153. return err
  1154. }
  1155. oldInbound.Tag = resolvedTag
  1156. inbound.Tag = oldInbound.Tag
  1157. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1158. if perr != nil {
  1159. return perr
  1160. }
  1161. if oldInbound.NodeID == nil {
  1162. if !push {
  1163. needRestart = true
  1164. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1165. oldSnapshot := *oldInbound
  1166. oldSnapshot.Tag = tag
  1167. oldSnapshot.Protocol = oldProtocol
  1168. payload := oldInbound
  1169. pushable := true
  1170. if inbound.Enable {
  1171. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1172. payload = built
  1173. } else {
  1174. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1175. pushable = false
  1176. }
  1177. }
  1178. if pushable {
  1179. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1180. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1181. } else {
  1182. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1183. if oldInbound.Protocol != model.MTProto {
  1184. needRestart = true
  1185. }
  1186. }
  1187. }
  1188. } else {
  1189. oldSnapshot := *oldInbound
  1190. oldSnapshot.Tag = tag
  1191. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1192. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1193. }
  1194. if inbound.Enable {
  1195. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1196. if err2 != nil {
  1197. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1198. needRestart = true
  1199. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1200. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1201. } else {
  1202. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1203. needRestart = true
  1204. }
  1205. }
  1206. }
  1207. } else if push {
  1208. oldSnapshot := *oldInbound
  1209. oldSnapshot.Tag = tag
  1210. if !inbound.Enable {
  1211. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1212. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1213. }
  1214. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1215. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1216. }
  1217. }
  1218. // A rename must allow the new tag before the inbound row is committed, or a
  1219. // node in "selected" sync mode would sweep the renamed central row on the
  1220. // next pull.
  1221. if oldInbound.NodeID != nil {
  1222. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1223. logger.Warning("allow inbound tag on node failed:", aErr)
  1224. }
  1225. }
  1226. if err := tx.Save(oldInbound).Error; err != nil {
  1227. return err
  1228. }
  1229. newClients, gcErr := s.GetClients(oldInbound)
  1230. if gcErr != nil {
  1231. return gcErr
  1232. }
  1233. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1234. return err
  1235. }
  1236. if oldInbound.NodeID != nil {
  1237. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1238. return err
  1239. }
  1240. }
  1241. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1242. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1243. // settings.
  1244. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1245. needRestart = true
  1246. }
  1247. return nil
  1248. })
  1249. if txErr != nil {
  1250. return inbound, false, txErr
  1251. }
  1252. // After the rename is committed, point any routing rules / loopback outbounds
  1253. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1254. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1255. // can't roll back the inbound edit.
  1256. if tag != oldInbound.Tag {
  1257. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1258. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1259. } else if routingChanged {
  1260. needRestart = true
  1261. }
  1262. }
  1263. return inbound, needRestart, nil
  1264. }
  1265. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1266. if inbound == nil {
  1267. return nil, fmt.Errorf("inbound is nil")
  1268. }
  1269. runtimeInbound := *inbound
  1270. settings := map[string]any{}
  1271. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1272. return nil, err
  1273. }
  1274. clients, ok := settings["clients"].([]any)
  1275. if !ok {
  1276. return &runtimeInbound, nil
  1277. }
  1278. var clientStats []xray.ClientTraffic
  1279. err := tx.Model(xray.ClientTraffic{}).
  1280. Where("inbound_id = ?", inbound.Id).
  1281. Select("email", "enable").
  1282. Find(&clientStats).Error
  1283. if err != nil {
  1284. return nil, err
  1285. }
  1286. enableMap := make(map[string]bool, len(clientStats))
  1287. for _, clientTraffic := range clientStats {
  1288. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1289. }
  1290. finalClients := make([]any, 0, len(clients))
  1291. for _, client := range clients {
  1292. c, ok := client.(map[string]any)
  1293. if !ok {
  1294. continue
  1295. }
  1296. email, _ := c["email"].(string)
  1297. if enable, exists := enableMap[email]; exists && !enable {
  1298. continue
  1299. }
  1300. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1301. continue
  1302. }
  1303. finalClients = append(finalClients, c)
  1304. }
  1305. settings["clients"] = finalClients
  1306. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. runtimeInbound.Settings = string(modifiedSettings)
  1311. return &runtimeInbound, nil
  1312. }
  1313. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1314. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1315. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1316. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1317. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1318. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1319. oldClients, err := s.GetClients(oldInbound)
  1320. if err != nil {
  1321. return err
  1322. }
  1323. newClients, err := s.GetClients(newInbound)
  1324. if err != nil {
  1325. return err
  1326. }
  1327. // Email is the unique key for ClientTraffic rows. Clients without an
  1328. // email have no stats row to sync — skip them on both sides instead of
  1329. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1330. oldEmails := make(map[string]struct{}, len(oldClients))
  1331. for i := range oldClients {
  1332. if oldClients[i].Email == "" {
  1333. continue
  1334. }
  1335. oldEmails[oldClients[i].Email] = struct{}{}
  1336. }
  1337. newEmails := make(map[string]struct{}, len(newClients))
  1338. for i := range newClients {
  1339. if newClients[i].Email == "" {
  1340. continue
  1341. }
  1342. newEmails[newClients[i].Email] = struct{}{}
  1343. }
  1344. // Drop stats rows for removed emails — but not when a sibling inbound
  1345. // still references the email, since the row is the shared accumulator.
  1346. for i := range oldClients {
  1347. email := oldClients[i].Email
  1348. if email == "" {
  1349. continue
  1350. }
  1351. if _, kept := newEmails[email]; kept {
  1352. continue
  1353. }
  1354. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. if stillUsed {
  1359. continue
  1360. }
  1361. if err := s.DelClientStat(tx, email); err != nil {
  1362. return err
  1363. }
  1364. // Keep inbound_client_ips in sync when the inbound edit drops an
  1365. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1366. if err := s.DelClientIPs(tx, email); err != nil {
  1367. return err
  1368. }
  1369. }
  1370. for i := range newClients {
  1371. email := newClients[i].Email
  1372. if email == "" {
  1373. continue
  1374. }
  1375. if _, existed := oldEmails[email]; existed {
  1376. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1377. return err
  1378. }
  1379. continue
  1380. }
  1381. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1382. return err
  1383. }
  1384. }
  1385. return nil
  1386. }
  1387. func (s *InboundService) GetInboundTags() (string, error) {
  1388. db := database.GetDB()
  1389. var inboundTags []string
  1390. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1391. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1392. return "", err
  1393. }
  1394. tags, _ := json.Marshal(inboundTags)
  1395. return string(tags), nil
  1396. }
  1397. func (s *InboundService) GetClientReverseTags() (string, error) {
  1398. db := database.GetDB()
  1399. var inbounds []model.Inbound
  1400. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1401. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1402. return "[]", err
  1403. }
  1404. tagSet := make(map[string]struct{})
  1405. for _, inbound := range inbounds {
  1406. var settings map[string]any
  1407. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1408. continue
  1409. }
  1410. clients, ok := settings["clients"].([]any)
  1411. if !ok {
  1412. continue
  1413. }
  1414. for _, client := range clients {
  1415. clientMap, ok := client.(map[string]any)
  1416. if !ok {
  1417. continue
  1418. }
  1419. reverse, ok := clientMap["reverse"].(map[string]any)
  1420. if !ok {
  1421. continue
  1422. }
  1423. tag, _ := reverse["tag"].(string)
  1424. tag = strings.TrimSpace(tag)
  1425. if tag != "" {
  1426. tagSet[tag] = struct{}{}
  1427. }
  1428. }
  1429. }
  1430. rawTags := make([]string, 0, len(tagSet))
  1431. for tag := range tagSet {
  1432. rawTags = append(rawTags, tag)
  1433. }
  1434. sort.Strings(rawTags)
  1435. result, _ := json.Marshal(rawTags)
  1436. return string(result), nil
  1437. }
  1438. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1439. db := database.GetDB()
  1440. var inbounds []*model.Inbound
  1441. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1442. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1443. return nil, err
  1444. }
  1445. return inbounds, nil
  1446. }