inbound.go 48 KB

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