1
0

inbound.go 47 KB

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