inbound.go 47 KB

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