1
0

inbound.go 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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. "regexp"
  11. "slices"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/google/uuid"
  16. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  17. "github.com/mhsanaei/3x-ui/v3/internal/database"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  21. "github.com/mhsanaei/3x-ui/v3/internal/tuic"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  24. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  25. "gorm.io/gorm"
  26. "gorm.io/gorm/clause"
  27. )
  28. type InboundService struct {
  29. clientService ClientService
  30. fallbackService FallbackService
  31. // FromNodeSync marks a master push: the row was validated where the operator
  32. // acted, and a node that refuses it only falls out of sync.
  33. FromNodeSync bool
  34. }
  35. func normalizeTrafficResetDay(day int) int {
  36. if day < 1 {
  37. return 1
  38. }
  39. return min(day, 31)
  40. }
  41. func normalizeInboundShareAddrStrategy(strategy string) string {
  42. strategy = strings.TrimSpace(strategy)
  43. switch strategy {
  44. case "listen", "custom":
  45. return strategy
  46. default:
  47. return "node"
  48. }
  49. }
  50. func normalizeInboundShareAddress(inbound *model.Inbound) {
  51. if inbound == nil {
  52. return
  53. }
  54. if inbound.Protocol == model.MTProto {
  55. inbound.ShareAddrStrategy = "listen"
  56. inbound.ShareAddr = ""
  57. return
  58. }
  59. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  60. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  61. inbound.ShareAddr = addr
  62. } else {
  63. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  64. }
  65. }
  66. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  67. if inbound == nil {
  68. return nil
  69. }
  70. if inbound.Protocol == model.MTProto {
  71. inbound.ShareAddrStrategy = "listen"
  72. inbound.ShareAddr = ""
  73. return nil
  74. }
  75. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  76. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  77. if err != nil {
  78. return common.NewError("shareAddr must be a host or IP without scheme or port")
  79. }
  80. inbound.ShareAddr = addr
  81. return nil
  82. }
  83. func normalizeInboundShareHost(raw string) (string, error) {
  84. addr := strings.TrimSpace(raw)
  85. if addr == "" {
  86. return "", nil
  87. }
  88. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  89. return "", fmt.Errorf("invalid share address %q", raw)
  90. }
  91. if strings.HasPrefix(addr, "[") {
  92. if !strings.HasSuffix(addr, "]") {
  93. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  94. }
  95. ip := net.ParseIP(addr[1 : len(addr)-1])
  96. if ip == nil || ip.To4() != nil {
  97. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  98. }
  99. return "[" + ip.String() + "]", nil
  100. }
  101. if strings.Contains(addr, ":") {
  102. if _, _, err := net.SplitHostPort(addr); err == nil {
  103. return "", fmt.Errorf("share address must not include port")
  104. }
  105. ip := net.ParseIP(addr)
  106. if ip == nil || ip.To4() != nil {
  107. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  108. }
  109. return "[" + ip.String() + "]", nil
  110. }
  111. host, err := netsafe.NormalizeHost(addr)
  112. if err != nil {
  113. return "", err
  114. }
  115. return host, nil
  116. }
  117. func legacyMtprotoShareAddr(inbound *model.Inbound) string {
  118. if inbound == nil || inbound.Protocol != model.MTProto || strings.TrimSpace(inbound.ShareAddrStrategy) != "custom" {
  119. return ""
  120. }
  121. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  122. if err != nil {
  123. return ""
  124. }
  125. return addr
  126. }
  127. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  128. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  129. return nil
  130. }
  131. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  132. 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 {
  133. return err
  134. }
  135. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  136. if hasShareAddr {
  137. 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 {
  138. return err
  139. }
  140. }
  141. if !hasShareAddr {
  142. return nil
  143. }
  144. var rows []struct {
  145. Id int
  146. ShareAddrStrategy string
  147. ShareAddr string
  148. }
  149. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  150. return err
  151. }
  152. for _, row := range rows {
  153. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  154. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  155. if addrErr != nil {
  156. strategy = "node"
  157. addr = ""
  158. }
  159. updates := map[string]any{}
  160. if strategy != row.ShareAddrStrategy {
  161. updates["share_addr_strategy"] = strategy
  162. }
  163. if addr != row.ShareAddr {
  164. updates["share_addr"] = addr
  165. }
  166. if len(updates) > 0 {
  167. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  168. return err
  169. }
  170. }
  171. }
  172. return nil
  173. }
  174. // GetInbounds retrieves all inbounds for a specific user with client stats.
  175. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  176. db := database.GetDB()
  177. var inbounds []*model.Inbound
  178. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  179. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  180. return nil, err
  181. }
  182. s.enrichClientStats(db, inbounds)
  183. s.annotateFallbackParents(db, inbounds)
  184. s.annotateLocalOriginGuid(inbounds)
  185. return inbounds, nil
  186. }
  187. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  188. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  189. // already carry the originating node's GUID. Read-time only (not persisted) so
  190. // the per-inbound online view can scope by GUID uniformly across a chain of
  191. // nodes (#4983).
  192. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  193. if len(inbounds) == 0 {
  194. return
  195. }
  196. guid := s.panelGuid()
  197. if guid == "" {
  198. return
  199. }
  200. for _, ib := range inbounds {
  201. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  202. ib.OriginNodeGuid = guid
  203. }
  204. }
  205. }
  206. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  207. // strips every per-client field other than email / enable / comment from
  208. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  209. // inbounds page only needs those three to roll up client counts and
  210. // render badges, so this trims tens of bytes per client (UUID, password,
  211. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  212. // up fast on installs with thousands of clients.
  213. //
  214. // Full client data is still available through GET /panel/api/inbounds/get/:id
  215. // for the edit/info/qr/export/clone flows that need it.
  216. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  217. db := database.GetDB()
  218. var inbounds []*model.Inbound
  219. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  220. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  221. return nil, err
  222. }
  223. s.annotateFallbackParents(db, inbounds)
  224. s.annotateLocalOriginGuid(inbounds)
  225. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  226. // so the list's depleted/expiring badges see every client; the UUID/SubId
  227. // enrichment stays skipped. Must run before slimming strips the settings.
  228. s.backfillClientStats(db, inbounds)
  229. // Slim feeds the panel UI only (masters poll the full list), so the badge
  230. // math may see the cross-panel totals a master pushed.
  231. s.overlayInboundsClientStats(db, inbounds)
  232. for _, ib := range inbounds {
  233. ib.Settings = slimSettingsClients(ib.Settings)
  234. }
  235. return inbounds, nil
  236. }
  237. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  238. // keeps only the fields the list view actually reads. Returns the input
  239. // unchanged when the JSON can't be parsed or has no clients array.
  240. func slimSettingsClients(settings string) string {
  241. if settings == "" {
  242. return settings
  243. }
  244. var raw map[string]any
  245. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  246. return settings
  247. }
  248. clients, ok := raw["clients"].([]any)
  249. if !ok || len(clients) == 0 {
  250. return settings
  251. }
  252. slim := make([]any, 0, len(clients))
  253. for _, entry := range clients {
  254. c, ok := entry.(map[string]any)
  255. if !ok {
  256. continue
  257. }
  258. row := make(map[string]any, 3)
  259. if v, ok := c["email"]; ok {
  260. row["email"] = v
  261. }
  262. if v, ok := c["enable"]; ok {
  263. row["enable"] = v
  264. }
  265. if v, ok := c["comment"]; ok && v != "" {
  266. row["comment"] = v
  267. }
  268. slim = append(slim, row)
  269. }
  270. raw["clients"] = slim
  271. out, err := json.Marshal(raw)
  272. if err != nil {
  273. return settings
  274. }
  275. return string(out)
  276. }
  277. // annotateFallbackParents fills FallbackParent on each inbound that is
  278. // the child side of a fallback rule. One DB round-trip serves the full
  279. // list — the frontend needs this to rewrite the child's client-share
  280. // link so it points at the master's reachable endpoint.
  281. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  282. if len(inbounds) == 0 {
  283. return
  284. }
  285. childIds := make([]int, 0, len(inbounds))
  286. for _, ib := range inbounds {
  287. childIds = append(childIds, ib.Id)
  288. }
  289. var rows []model.InboundFallback
  290. if err := db.Where("child_id IN ?", childIds).
  291. Order("sort_order ASC, id ASC").
  292. Find(&rows).Error; err != nil {
  293. return
  294. }
  295. first := make(map[int]model.InboundFallback, len(rows))
  296. for _, r := range rows {
  297. if _, ok := first[r.ChildId]; !ok {
  298. first[r.ChildId] = r
  299. }
  300. }
  301. for _, ib := range inbounds {
  302. if r, ok := first[ib.Id]; ok {
  303. ib.FallbackParent = &model.FallbackParentInfo{
  304. MasterId: r.MasterId,
  305. Path: r.Path,
  306. }
  307. }
  308. }
  309. }
  310. type InboundOption struct {
  311. Id int `json:"id" example:"1"`
  312. Remark string `json:"remark" example:"VLESS-443"`
  313. Tag string `json:"tag" example:"in-443-tcp"`
  314. Protocol string `json:"protocol" example:"vless"`
  315. Port int `json:"port" example:"443"`
  316. Enable bool `json:"enable" example:"true"`
  317. Network string `json:"network,omitempty"`
  318. Security string `json:"security,omitempty"`
  319. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  320. SsMethod string `json:"ssMethod"`
  321. WgPublicKey string `json:"wgPublicKey,omitempty"`
  322. WgMtu int `json:"wgMtu,omitempty"`
  323. WgDns string `json:"wgDns,omitempty"`
  324. MtprotoDomain string `json:"mtprotoDomain,omitempty"`
  325. // AwgServer carries the full AmneziaWG server block (keys, subnet,
  326. // obfuscation params) so the clients page can render a downloadable
  327. // per-client .conf without a second round trip.
  328. AwgServer *amneziawg.ServerSettings `json:"awgServer,omitempty"`
  329. TuicServer *tuic.TuicServerSettings `json:"tuicServer,omitempty"`
  330. // Hosting node; nil for this panel's own inbounds. Lets the clients
  331. // page map a node filter onto inbound IDs (#4997).
  332. NodeId *int `json:"nodeId,omitempty"`
  333. // Share-host resolution inputs, mirroring the subscription's
  334. // resolveInboundAddress so the clients page renders a node-managed WireGuard
  335. // Endpoint that points at the node, not the master panel. NodeAddress is the
  336. // hosting node's externally reachable address (empty for this panel's own
  337. // inbounds); Listen and ShareAddrStrategy/ShareAddr feed the same
  338. // node→listen→custom fallback the share/QR links already use.
  339. NodeAddress string `json:"nodeAddress,omitempty"`
  340. Listen string `json:"listen,omitempty"`
  341. ShareAddr string `json:"shareAddr,omitempty"`
  342. ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
  343. }
  344. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  345. db := database.GetDB()
  346. var rows []struct {
  347. Id int `gorm:"column:id"`
  348. Remark string `gorm:"column:remark"`
  349. Tag string `gorm:"column:tag"`
  350. Protocol string `gorm:"column:protocol"`
  351. Port int `gorm:"column:port"`
  352. Enable bool `gorm:"column:enable"`
  353. StreamSettings string `gorm:"column:stream_settings"`
  354. Settings string `gorm:"column:settings"`
  355. Listen string `gorm:"column:listen"`
  356. ShareAddr string `gorm:"column:share_addr"`
  357. ShareAddrStrategy string `gorm:"column:share_addr_strategy"`
  358. NodeId *int `gorm:"column:node_id"`
  359. NodeAddress string `gorm:"column:node_address"`
  360. DisableFlow bool `gorm:"column:disable_flow"`
  361. }
  362. err := db.Table("inbounds").
  363. 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, inbounds.disable_flow").
  364. Joins("LEFT JOIN nodes ON nodes.id = inbounds.node_id").
  365. Where("inbounds.user_id = ?", userId).
  366. Order("inbounds.id ASC").
  367. Scan(&rows).Error
  368. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  369. return nil, err
  370. }
  371. out := make([]InboundOption, 0, len(rows))
  372. for _, r := range rows {
  373. wgPublicKey, wgMtu, wgDns := inboundWireguardHints(r.Protocol, r.Settings)
  374. netHint, secHint := inboundStreamHints(r.Protocol, r.StreamSettings, r.Settings)
  375. shareAddrStrategy := r.ShareAddrStrategy
  376. if shareAddrStrategy == "node" {
  377. shareAddrStrategy = ""
  378. }
  379. out = append(out, InboundOption{
  380. Id: r.Id,
  381. Remark: r.Remark,
  382. Tag: r.Tag,
  383. Protocol: r.Protocol,
  384. Port: r.Port,
  385. Enable: r.Enable,
  386. Network: netHint,
  387. Security: secHint,
  388. TlsFlowCapable: !r.DisableFlow && inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  389. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  390. WgPublicKey: wgPublicKey,
  391. WgMtu: wgMtu,
  392. WgDns: wgDns,
  393. MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
  394. AwgServer: inboundAmneziaWGServer(r.Protocol, r.Settings),
  395. TuicServer: inboundTuicServer(r.Protocol, r.Settings),
  396. NodeId: r.NodeId,
  397. NodeAddress: r.NodeAddress,
  398. Listen: r.Listen,
  399. ShareAddr: r.ShareAddr,
  400. ShareAddrStrategy: shareAddrStrategy,
  401. })
  402. }
  403. return out, nil
  404. }
  405. func inboundStreamHints(protocol string, streamSettings string, settings string) (string, string) {
  406. p := strings.ToLower(protocol)
  407. if p == "wireguard" || p == "amneziawg" || p == "hysteria" {
  408. return "udp", ""
  409. }
  410. var netHint, secHint string
  411. if strings.TrimSpace(streamSettings) != "" {
  412. var raw struct {
  413. Network string `json:"network"`
  414. Security string `json:"security"`
  415. }
  416. if err := json.Unmarshal([]byte(streamSettings), &raw); err == nil {
  417. netHint = raw.Network
  418. secHint = raw.Security
  419. }
  420. }
  421. if netHint == "" && strings.TrimSpace(settings) != "" {
  422. var raw struct {
  423. Network string `json:"network"`
  424. AllowedNetwork string `json:"allowedNetwork"`
  425. UDP bool `json:"udp"`
  426. }
  427. if err := json.Unmarshal([]byte(settings), &raw); err == nil {
  428. if raw.Network != "" {
  429. netHint = raw.Network
  430. } else if raw.AllowedNetwork != "" {
  431. netHint = raw.AllowedNetwork
  432. } else if raw.UDP {
  433. netHint = "tcp,udp"
  434. }
  435. }
  436. }
  437. if netHint == "" {
  438. netHint = "tcp"
  439. }
  440. return netHint, secHint
  441. }
  442. func inboundWireguardHints(protocol string, settings string) (string, int, string) {
  443. if protocol != string(model.WireGuard) || strings.TrimSpace(settings) == "" {
  444. return "", 0, ""
  445. }
  446. var parsed struct {
  447. PublicKey string `json:"publicKey"`
  448. PubKey string `json:"pubKey"`
  449. SecretKey string `json:"secretKey"`
  450. MTU int `json:"mtu"`
  451. DNS string `json:"dns"`
  452. }
  453. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  454. return "", 0, ""
  455. }
  456. publicKey := parsed.PublicKey
  457. if publicKey == "" {
  458. publicKey = parsed.PubKey
  459. }
  460. if publicKey == "" && parsed.SecretKey != "" {
  461. if derived, err := wgutil.PublicKeyFromPrivate(parsed.SecretKey); err == nil {
  462. publicKey = derived
  463. }
  464. }
  465. return publicKey, parsed.MTU, parsed.DNS
  466. }
  467. // inboundAmneziaWGServer returns the AmneziaWG server block for the clients
  468. // page's config-download builder, or nil when the inbound isn't AmneziaWG or
  469. // its settings don't parse. PrivateKey is redacted: GetInboundOptions is a
  470. // shared, admin-wide list used to fill dropdowns, not a place a live tunnel
  471. // secret needs to travel — the frontend's own AwgServerOptionSchema never
  472. // reads it, so nothing is lost by not sending it, and it shouldn't widen the
  473. // blast radius of a log capture, proxy cache, or browser devtools screenshot.
  474. func inboundAmneziaWGServer(protocol string, settings string) *amneziawg.ServerSettings {
  475. if protocol != string(model.AmneziaWG) || strings.TrimSpace(settings) == "" {
  476. return nil
  477. }
  478. var parsed amneziawg.InboundSettings
  479. if err := json.Unmarshal([]byte(settings), &parsed); err != nil || parsed.Server == nil {
  480. return nil
  481. }
  482. redacted := *parsed.Server
  483. redacted.PrivateKey = ""
  484. return &redacted
  485. }
  486. func inboundTuicServer(protocol string, settings string) *tuic.TuicServerSettings {
  487. if protocol != string(model.TUIC) || strings.TrimSpace(settings) == "" {
  488. return nil
  489. }
  490. var parsed struct {
  491. Server *tuic.TuicServerSettings `json:"server"`
  492. }
  493. if err := json.Unmarshal([]byte(settings), &parsed); err != nil || parsed.Server == nil {
  494. return nil
  495. }
  496. redacted := *parsed.Server
  497. redacted.PrivateKey = ""
  498. return &redacted
  499. }
  500. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  501. // the clients UI to seed a new mtproto client's secret with the right fronting
  502. // hostname.
  503. func inboundMtprotoDomain(protocol string, settings string) string {
  504. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  505. return ""
  506. }
  507. var parsed struct {
  508. FakeTLSDomain string `json:"fakeTlsDomain"`
  509. }
  510. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  511. return ""
  512. }
  513. return strings.TrimSpace(parsed.FakeTLSDomain)
  514. }
  515. // GetAllInbounds retrieves all inbounds with client stats.
  516. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  517. db := database.GetDB()
  518. var inbounds []*model.Inbound
  519. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  520. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  521. return nil, err
  522. }
  523. s.enrichClientStats(db, inbounds)
  524. return inbounds, nil
  525. }
  526. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  527. db := database.GetDB()
  528. var inbounds []*model.Inbound
  529. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  530. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  531. return nil, err
  532. }
  533. return inbounds, nil
  534. }
  535. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  536. return ParseInboundSettingsClients(inbound.Settings)
  537. }
  538. // GetClientsBySubId returns the inbound's clients with the given subscription
  539. // id, resolved from the normalized clients tables (the same source the running
  540. // Xray users are built from) instead of parsing the settings JSON blob.
  541. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  542. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  543. }
  544. // ListClientsForInbound returns every client attached to the inbound from the
  545. // normalized clients tables — the same source the running Xray config uses —
  546. // instead of parsing the embedded settings JSON, which can hold a stale UUID
  547. // after a client identity change (#6436).
  548. func (s *InboundService) ListClientsForInbound(inboundId int) ([]model.Client, error) {
  549. return s.clientService.ListForInbound(nil, inboundId)
  550. }
  551. func (s *InboundService) GetAllEmails() ([]string, error) {
  552. db := database.GetDB()
  553. var emails []string
  554. query := fmt.Sprintf(
  555. "SELECT DISTINCT %s %s",
  556. database.JSONFieldText("client.value", "email"),
  557. database.JSONClientsFromInbound(),
  558. )
  559. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  560. return nil, err
  561. }
  562. return emails, nil
  563. }
  564. // emailSubIDsForClients returns lower(email)→subId for just the emails being
  565. // checked. One clients row owns an email's identity, so the answer no longer
  566. // needs a scan of every inbound's settings JSON (#6252).
  567. func (s *InboundService) emailSubIDsForClients(clients []model.Client) (map[string]string, error) {
  568. want := make(map[string]struct{}, len(clients))
  569. for i := range clients {
  570. if email := strings.ToLower(strings.TrimSpace(clients[i].Email)); email != "" {
  571. want[email] = struct{}{}
  572. }
  573. }
  574. result := make(map[string]string, len(want))
  575. if len(want) == 0 {
  576. return result, nil
  577. }
  578. lowered := make([]string, 0, len(want))
  579. for email := range want {
  580. lowered = append(lowered, email)
  581. }
  582. db := database.GetDB()
  583. for _, batch := range chunkStrings(lowered, sqlInChunk) {
  584. var rows []struct {
  585. Email string
  586. SubID string `gorm:"column:sub_id"`
  587. }
  588. err := db.Model(&model.ClientRecord{}).
  589. Select("email, sub_id").
  590. Where("LOWER(email) IN ?", batch).
  591. Scan(&rows).Error
  592. if err != nil {
  593. return nil, err
  594. }
  595. for _, r := range rows {
  596. result[strings.ToLower(r.Email)] = r.SubID
  597. }
  598. }
  599. return result, nil
  600. }
  601. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  602. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  603. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  604. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  605. // mode). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  606. // "network" — are canonicalized to "network", which every panel reader (link
  607. // generation, port-conflict detection, flow eligibility) keys on.
  608. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  609. protocolsWithStream := map[model.Protocol]bool{
  610. model.VMESS: true,
  611. model.VLESS: true,
  612. model.Trojan: true,
  613. model.Shadowsocks: true,
  614. model.Hysteria: true,
  615. model.WireGuard: true,
  616. model.Tunnel: true,
  617. }
  618. if !protocolsWithStream[inbound.Protocol] {
  619. inbound.StreamSettings = ""
  620. return
  621. }
  622. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  623. }
  624. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  625. // transport under "method" to the panel-canonical "network" key. When both
  626. // keys are present, "method" wins — matching xray-core's own precedence.
  627. func canonicalizeStreamNetworkKey(streamSettings string) string {
  628. if streamSettings == "" {
  629. return streamSettings
  630. }
  631. var stream map[string]any
  632. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  633. return streamSettings
  634. }
  635. method, ok := stream["method"].(string)
  636. if !ok || method == "" {
  637. return streamSettings
  638. }
  639. stream["network"] = method
  640. delete(stream, "method")
  641. out, err := json.MarshalIndent(stream, "", " ")
  642. if err != nil {
  643. return streamSettings
  644. }
  645. return string(out)
  646. }
  647. // validateInboundTLSCertificates rejects incomplete TLS credentials before a save
  648. // can restart Xray. File paths belong to the node, so only presence is checked.
  649. func validateInboundTLSCertificates(streamSettings string) error {
  650. if strings.TrimSpace(streamSettings) == "" {
  651. return nil
  652. }
  653. var stream struct {
  654. Security string `json:"security"`
  655. TLSSettings json.RawMessage `json:"tlsSettings"`
  656. }
  657. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  658. return common.NewError("Invalid inbound stream settings: ", err)
  659. }
  660. if !strings.EqualFold(stream.Security, "tls") {
  661. return nil
  662. }
  663. var settings struct {
  664. Certificates []struct {
  665. CertificateFile string `json:"certificateFile"`
  666. KeyFile string `json:"keyFile"`
  667. Certificate []string `json:"certificate"`
  668. Key []string `json:"key"`
  669. Usage string `json:"usage"`
  670. } `json:"certificates"`
  671. }
  672. if len(stream.TLSSettings) > 0 {
  673. if err := json.Unmarshal(stream.TLSSettings, &settings); err != nil {
  674. return common.NewError("Invalid inbound TLS settings: ", err)
  675. }
  676. }
  677. hasServerCertificate := false
  678. for i, cert := range settings.Certificates {
  679. // Match Xray's file-over-inline precedence for each credential.
  680. certificate := cert.CertificateFile
  681. if certificate == "" {
  682. certificate = strings.Join(cert.Certificate, "\n")
  683. }
  684. if strings.TrimSpace(certificate) == "" {
  685. return common.NewErrorf("TLS certificate %d is missing. Configure a certificate file path or certificate content before saving the inbound.", i+1)
  686. }
  687. if strings.EqualFold(cert.Usage, "verify") {
  688. continue
  689. }
  690. key := cert.KeyFile
  691. if key == "" {
  692. key = strings.Join(cert.Key, "\n")
  693. }
  694. if strings.TrimSpace(key) == "" {
  695. return common.NewErrorf("TLS certificate %d is missing its private key. Configure a private key file path or private key content before saving the inbound.", i+1)
  696. }
  697. hasServerCertificate = true
  698. }
  699. if !hasServerCertificate {
  700. return common.NewError("TLS requires a server certificate and private key. Configure an encipherment or issue certificate before saving the inbound.")
  701. }
  702. return nil
  703. }
  704. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  705. // stream uses REALITY security, or nil otherwise. A non-empty result means
  706. // this stream carries the finalmask+REALITY combination that panics
  707. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  708. // wraps the connection before REALITY's handshake ever sees it, and
  709. // reality.Server() does an unchecked type assertion assuming a raw
  710. // *net.TCPConn, which panics once finalmask is in front of it.
  711. //
  712. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  713. // listener ahead of REALITY's handshake, in xray-core's own
  714. // transport/internet/memory_settings.go) is only constructed when tcp masks
  715. // are present; a finalmask.udp-only config never touches the TCP accept path
  716. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  717. // rejected.
  718. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  719. if stream["security"] != "reality" {
  720. return nil
  721. }
  722. finalmask, ok := stream["finalmask"].(map[string]any)
  723. if !ok {
  724. return nil
  725. }
  726. tcp, _ := finalmask["tcp"].([]any)
  727. return tcp
  728. }
  729. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  730. // with REALITY security at save time. Upstream has confirmed this
  731. // combination will be documented as unsupported rather than made graceful,
  732. // so the panel must not let it be saved.
  733. func validateFinalMaskRealityCombo(streamSettings string) error {
  734. if streamSettings == "" {
  735. return nil
  736. }
  737. var stream map[string]any
  738. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  739. return nil
  740. }
  741. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  742. return nil
  743. }
  744. return common.NewError("Finalmask is not supported with REALITY security — it crashes Xray-core on the first connection (see XTLS/Xray-core#6453). Remove the finalmask configuration or switch security to tls/none.")
  745. }
  746. var xmcProfileUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{3,16}$`)
  747. // xmcMaskProfilesComplete reports whether an xmc finalmask carries the signed
  748. // Minecraft session profiles xray-core has required since v26.7.28 (#6487).
  749. // The core replaced the old `usernames` string list with `profiles` objects
  750. // and removed the "default to Dream when empty" fallback, so a mask still on
  751. // the legacy shape — or one whose profiles are incomplete — now fails
  752. // conf.XMC.Build() and takes the entire config down with it rather than
  753. // degrading that one inbound.
  754. //
  755. // The texture fields are a signed blob only Mojang's session server can issue
  756. // (resolve the UUID by username, then fetch the profile with unsigned=false),
  757. // so the panel cannot synthesize a valid profile from a legacy username; an
  758. // incomplete mask can only be reported or dropped.
  759. func xmcMaskProfilesComplete(mask map[string]any) bool {
  760. settings, ok := mask["settings"].(map[string]any)
  761. if !ok {
  762. return false
  763. }
  764. profiles, _ := settings["profiles"].([]any)
  765. if len(profiles) == 0 {
  766. return false
  767. }
  768. for _, entry := range profiles {
  769. profile, ok := entry.(map[string]any)
  770. if !ok {
  771. return false
  772. }
  773. username, _ := profile["username"].(string)
  774. if !xmcProfileUsernamePattern.MatchString(username) {
  775. return false
  776. }
  777. id, _ := profile["uuid"].(string)
  778. if _, err := uuid.Parse(id); err != nil {
  779. return false
  780. }
  781. if value, _ := profile["texturesValue"].(string); value == "" {
  782. return false
  783. }
  784. if signature, _ := profile["texturesSignature"].(string); signature == "" {
  785. return false
  786. }
  787. }
  788. return true
  789. }
  790. // isIncompleteXmcMask reports whether a finalmask.tcp entry is an xmc mask
  791. // xray-core would refuse to build.
  792. func isIncompleteXmcMask(entry any) bool {
  793. mask, ok := entry.(map[string]any)
  794. if !ok {
  795. return false
  796. }
  797. if maskType, _ := mask["type"].(string); maskType != "xmc" {
  798. return false
  799. }
  800. return !xmcMaskProfilesComplete(mask)
  801. }
  802. // incompleteXmcMaskCount counts the stream's xmc finalmask entries that
  803. // xray-core would refuse to build.
  804. func incompleteXmcMaskCount(stream map[string]any) int {
  805. finalmask, ok := stream["finalmask"].(map[string]any)
  806. if !ok {
  807. return 0
  808. }
  809. tcp, _ := finalmask["tcp"].([]any)
  810. count := 0
  811. for _, entry := range tcp {
  812. if isIncompleteXmcMask(entry) {
  813. count++
  814. }
  815. }
  816. return count
  817. }
  818. // stripIncompleteXmcMasks removes every xmc finalmask entry xray-core would
  819. // refuse to build, returning how many were dropped, and clears the finalmask
  820. // object once nothing is left in it.
  821. //
  822. // AddInbound and UpdateInbound reject an incomplete mask at save time, but a
  823. // row that never went through those paths — an upgrade from a panel predating
  824. // v26.7.28, node sync, a restored backup, a direct DB edit — would otherwise
  825. // fail the whole config build and keep every other inbound offline too.
  826. // Dropping only the offending mask degrades that one inbound instead, which
  827. // the accompanying warning tells the admin to reconfigure.
  828. func stripIncompleteXmcMasks(stream map[string]any) int {
  829. finalmask, ok := stream["finalmask"].(map[string]any)
  830. if !ok {
  831. return 0
  832. }
  833. tcp, _ := finalmask["tcp"].([]any)
  834. if len(tcp) == 0 {
  835. return 0
  836. }
  837. kept := make([]any, 0, len(tcp))
  838. dropped := 0
  839. for _, entry := range tcp {
  840. if isIncompleteXmcMask(entry) {
  841. dropped++
  842. continue
  843. }
  844. kept = append(kept, entry)
  845. }
  846. if dropped == 0 {
  847. return 0
  848. }
  849. if len(kept) == 0 {
  850. delete(finalmask, "tcp")
  851. } else {
  852. finalmask["tcp"] = kept
  853. }
  854. if len(finalmask) == 0 {
  855. delete(stream, "finalmask")
  856. }
  857. return dropped
  858. }
  859. // dropEmptyRandPackets removes the leftover empty "packet" from finalmask
  860. // items that also carry a rand, and reports how many it cleared.
  861. //
  862. // xray-core treats even an empty array as a packet, and every item kind is
  863. // exclusive: noise refuses "len(item.Packet) > 0 && item.Rand.To > 0" and
  864. // header-custom refuses "exactly one item kind must be set". Either error
  865. // fails the whole config build, so one such item keeps every inbound offline.
  866. // The panel's mask editor wrote that pair whenever an item was switched to the
  867. // rand-driven array kind, so stored rows carry it; clearing an empty packet
  868. // changes nothing about the mask the admin configured.
  869. func dropEmptyRandPackets(node any) int {
  870. switch value := node.(type) {
  871. case map[string]any:
  872. cleared := 0
  873. if packet, ok := value["packet"].([]any); ok && len(packet) == 0 && randIsSet(value["rand"]) {
  874. delete(value, "packet")
  875. cleared++
  876. }
  877. for _, child := range value {
  878. cleared += dropEmptyRandPackets(child)
  879. }
  880. return cleared
  881. case []any:
  882. cleared := 0
  883. for _, child := range value {
  884. cleared += dropEmptyRandPackets(child)
  885. }
  886. return cleared
  887. default:
  888. return 0
  889. }
  890. }
  891. // randIsSet reports whether a finalmask item's rand selects a random packet.
  892. // It is a number on header-custom items and a dash-range string on noise ones.
  893. func randIsSet(value any) bool {
  894. switch rand := value.(type) {
  895. case float64:
  896. return rand > 0
  897. case string:
  898. return rand != "" && rand != "0" && rand != "0-0"
  899. default:
  900. return false
  901. }
  902. }
  903. // validateFinalMaskXmcProfiles rejects an xmc finalmask without complete
  904. // profiles at save time, so the admin gets a targeted error instead of a core
  905. // that refuses to start (or, after GetXrayConfig heals it, an inbound quietly
  906. // serving without the obfuscation they configured).
  907. func validateFinalMaskXmcProfiles(streamSettings string) error {
  908. if streamSettings == "" {
  909. return nil
  910. }
  911. var stream map[string]any
  912. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  913. return nil
  914. }
  915. if incompleteXmcMaskCount(stream) == 0 {
  916. return nil
  917. }
  918. return common.NewError("XMC finalmask requires at least one complete Minecraft profile — each needs a username (3-16 of A-Z a-z 0-9 _), a UUID, and both texture fields from Mojang's session server (XTLS/Xray-core#6487). Complete the profiles or remove the XMC mask.")
  919. }
  920. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  921. // always valid before the row is persisted, and drops the vestigial inbound-level
  922. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  923. // only the per-client values. Leaving an inbound-level secret behind is what
  924. // produced stale links that failed with "incorrect client random".
  925. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  926. if inbound.Protocol != model.MTProto {
  927. return
  928. }
  929. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  930. inbound.Settings = stripped
  931. }
  932. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  933. inbound.Settings = stripped
  934. }
  935. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  936. inbound.Settings = healed
  937. }
  938. }
  939. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  940. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  941. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  942. if inbound == nil || inbound.Protocol != model.MTProto {
  943. return false
  944. }
  945. var parsed struct {
  946. RouteThroughXray bool `json:"routeThroughXray"`
  947. }
  948. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  949. return false
  950. }
  951. return parsed.RouteThroughXray
  952. }
  953. func settingsRouteXrayPort(parsed map[string]any) int {
  954. switch v := parsed["routeXrayPort"].(type) {
  955. case float64:
  956. return int(v)
  957. case int:
  958. return v
  959. case json.Number:
  960. if n, err := v.Int64(); err == nil {
  961. return int(n)
  962. }
  963. }
  964. return 0
  965. }
  966. func parseRouteXrayPort(settings string) int {
  967. if settings == "" {
  968. return 0
  969. }
  970. var parsed map[string]any
  971. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  972. return 0
  973. }
  974. return settingsRouteXrayPort(parsed)
  975. }
  976. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  977. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  978. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  979. // allocated once when routing is first enabled and preserved across edits
  980. // (carried over from oldSettings, which wins over any value the client echoed
  981. // back). When routing is off it — together with the now-inert outbound
  982. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  983. //
  984. // It returns an error when an egress port cannot be allocated or persisted, so
  985. // the caller refuses the save rather than storing a routed-but-portless inbound,
  986. // which would otherwise route no traffic and have its mtg metrics skipped (see
  987. // mtproto_job) — silently losing its accounting.
  988. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  989. if inbound.Protocol != model.MTProto {
  990. return nil
  991. }
  992. var parsed map[string]any
  993. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  994. return nil
  995. }
  996. routed, _ := parsed["routeThroughXray"].(bool)
  997. if !routed {
  998. _, hadPort := parsed["routeXrayPort"]
  999. _, hadTag := parsed["outboundTag"]
  1000. if !hadPort && !hadTag {
  1001. return nil
  1002. }
  1003. delete(parsed, "routeXrayPort")
  1004. delete(parsed, "outboundTag")
  1005. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  1006. inbound.Settings = string(bs)
  1007. } else {
  1008. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  1009. }
  1010. return nil
  1011. }
  1012. // Prefer the already-stored port (carried across edits), then any value the
  1013. // client sent, then allocate a fresh one.
  1014. port := parseRouteXrayPort(oldSettings)
  1015. if port <= 0 {
  1016. port = settingsRouteXrayPort(parsed)
  1017. }
  1018. if port <= 0 {
  1019. allocated, err := mtproto.FreeLocalPort()
  1020. if err != nil {
  1021. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  1022. }
  1023. port = allocated
  1024. }
  1025. if settingsRouteXrayPort(parsed) == port {
  1026. return nil
  1027. }
  1028. parsed["routeXrayPort"] = port
  1029. bs, err := json.MarshalIndent(parsed, "", " ")
  1030. if err != nil {
  1031. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  1032. }
  1033. inbound.Settings = string(bs)
  1034. return nil
  1035. }
  1036. // AddInbound creates a new inbound configuration.
  1037. // It validates port uniqueness, client email uniqueness, and required fields,
  1038. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  1039. // Returns the created inbound, whether Xray needs restart, and any error.
  1040. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1041. inbound.Id = 0
  1042. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1043. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1044. // Normalize streamSettings based on protocol
  1045. s.normalizeStreamSettings(inbound)
  1046. if !s.FromNodeSync {
  1047. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1048. return inbound, false, err
  1049. }
  1050. }
  1051. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1052. return inbound, false, err
  1053. }
  1054. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1055. return inbound, false, err
  1056. }
  1057. s.normalizeMtprotoSecret(inbound)
  1058. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  1059. return inbound, false, err
  1060. }
  1061. if err := s.normalizeAmneziaWGSettings(inbound, ""); err != nil {
  1062. return inbound, false, err
  1063. }
  1064. if inbound.NodeID != nil && !isNodeEligibleProtocol(inbound.Protocol) {
  1065. return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
  1066. }
  1067. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1068. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1069. return inbound, false, err
  1070. }
  1071. tag, err := s.resolveInboundTag(inbound, 0)
  1072. if err != nil {
  1073. return inbound, false, err
  1074. }
  1075. inbound.Tag = tag
  1076. normalizeLegacyClientSettings(inbound)
  1077. clients, err := s.GetClients(inbound)
  1078. if err != nil {
  1079. return inbound, false, err
  1080. }
  1081. if err := validateClientsRenewal(clients); err != nil {
  1082. return inbound, false, err
  1083. }
  1084. for _, traffic := range inbound.ClientStats {
  1085. if err := validateClientRenewal(model.Client{Reset: traffic.Reset, ResetDay: traffic.ResetDay, ResetWeekday: traffic.ResetWeekday}); err != nil {
  1086. return inbound, false, err
  1087. }
  1088. }
  1089. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
  1090. if err != nil {
  1091. return inbound, false, err
  1092. }
  1093. if existEmail != "" {
  1094. return inbound, false, common.NewError("Duplicate email:", existEmail)
  1095. }
  1096. if inbound.DisableFlow {
  1097. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1098. inbound.Settings = stripped
  1099. }
  1100. for i := range clients {
  1101. clients[i].Flow = ""
  1102. }
  1103. }
  1104. // Ensure created_at and updated_at on clients in settings
  1105. if len(clients) > 0 {
  1106. var settings map[string]any
  1107. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  1108. now := time.Now().Unix() * 1000
  1109. updatedClients := make([]model.Client, 0, len(clients))
  1110. for _, c := range clients {
  1111. if c.CreatedAt == 0 {
  1112. c.CreatedAt = now
  1113. }
  1114. c.UpdatedAt = now
  1115. updatedClients = append(updatedClients, c)
  1116. }
  1117. settings["clients"] = updatedClients
  1118. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  1119. inbound.Settings = string(bs)
  1120. } else {
  1121. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  1122. }
  1123. } else if err2 != nil {
  1124. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  1125. }
  1126. }
  1127. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  1128. // the inbound method (e.g. an API caller supplied a wrong-size key).
  1129. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1130. inbound.Settings = normalized
  1131. }
  1132. // Secure client ID
  1133. for _, client := range clients {
  1134. switch inbound.Protocol {
  1135. case "trojan":
  1136. if client.Password == "" {
  1137. return inbound, false, common.NewError("empty client ID")
  1138. }
  1139. case "shadowsocks":
  1140. if client.Email == "" {
  1141. return inbound, false, common.NewError("empty client ID")
  1142. }
  1143. case "hysteria":
  1144. if client.Auth == "" {
  1145. return inbound, false, common.NewError("empty client ID")
  1146. }
  1147. case "wireguard", "amneziawg":
  1148. if client.PublicKey == "" {
  1149. return inbound, false, common.NewError("wireguard client requires a key")
  1150. }
  1151. case "mtproto":
  1152. if client.Secret == "" {
  1153. return inbound, false, common.NewError("mtproto client requires a secret")
  1154. }
  1155. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  1156. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  1157. }
  1158. case "tuic":
  1159. if client.ID == "" {
  1160. return inbound, false, common.NewError("empty client ID")
  1161. }
  1162. if client.Password == "" {
  1163. return inbound, false, common.NewError("tuic client requires a password")
  1164. }
  1165. if client.Email == "" {
  1166. return inbound, false, common.NewError("empty client email")
  1167. }
  1168. default:
  1169. if client.ID == "" {
  1170. return inbound, false, common.NewError("empty client ID")
  1171. }
  1172. }
  1173. }
  1174. needRestart := false
  1175. var postCommitApply func()
  1176. err = runSerializedTx(func(tx *gorm.DB) error {
  1177. conflict, cErr := checkPortConflictTx(tx, inbound, 0)
  1178. if cErr != nil {
  1179. return cErr
  1180. }
  1181. if conflict != nil {
  1182. return common.NewError(conflict.String())
  1183. }
  1184. markDirty := false
  1185. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  1186. return err
  1187. }
  1188. // The relay port is derived from the id, only known after Save, and only a
  1189. // local row owns one: checkPortConflictTx ran no relay check with ignoreId==0.
  1190. if inbound.NodeID == nil && inbound.Protocol == model.AmneziaWG {
  1191. if self := amneziawgnetSocksSelfConflict(inbound, inbound.Id); self != "" {
  1192. return common.NewError(self)
  1193. }
  1194. conflict, cErr := checkAmneziawgnetSocksRelayCollision(tx, inbound.Id)
  1195. if cErr != nil {
  1196. return cErr
  1197. }
  1198. if conflict != nil {
  1199. return common.NewError(conflict.String())
  1200. }
  1201. conflict, cErr = checkAmneziawgnetSocksReverseConflict(tx, inbound.Id)
  1202. if cErr != nil {
  1203. return cErr
  1204. }
  1205. if conflict != nil {
  1206. return common.NewError(conflict.String())
  1207. }
  1208. // The clients' forward specs were validated while this row had no id,
  1209. // so the ports it now derives were never in the guard's context.
  1210. if aErr := s.checkAmneziaWGForwardedPorts(tx, inbound.Settings); aErr != nil {
  1211. return aErr
  1212. }
  1213. }
  1214. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  1215. // Enable=true on every imported stat row) are authoritative for this call
  1216. // and must not be clobbered by the AddClientStat loop below, which derives
  1217. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  1218. // possibly-stale source for the same columns on a plain (non-import) create.
  1219. statEmails := make(map[string]bool, len(inbound.ClientStats))
  1220. for i := range inbound.ClientStats {
  1221. if inbound.ClientStats[i].Email == "" {
  1222. continue
  1223. }
  1224. statEmails[inbound.ClientStats[i].Email] = true
  1225. inbound.ClientStats[i].Id = 0
  1226. inbound.ClientStats[i].InboundId = inbound.Id
  1227. if err := tx.Clauses(clause.OnConflict{
  1228. Columns: []clause.Column{{Name: "email"}},
  1229. DoNothing: true,
  1230. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  1231. return err
  1232. }
  1233. }
  1234. for _, client := range clients {
  1235. if statEmails[client.Email] {
  1236. continue
  1237. }
  1238. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  1239. return err
  1240. }
  1241. }
  1242. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  1243. return err
  1244. }
  1245. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  1246. return err
  1247. }
  1248. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1249. return err
  1250. }
  1251. if inbound.NodeID != nil {
  1252. nodeID := *inbound.NodeID
  1253. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  1254. return err
  1255. }
  1256. }
  1257. if inbound.Enable {
  1258. if inbound.NodeID != nil {
  1259. markDirty = true
  1260. } else {
  1261. rt, push, _, perr := s.nodePushPlan(inbound)
  1262. if perr != nil {
  1263. return perr
  1264. }
  1265. if push {
  1266. payload := inbound
  1267. pushable := true
  1268. if inbound.Protocol == model.MTProto || inbound.Protocol == model.TUIC {
  1269. if built, bErr := s.buildInboundForLocalRuntime(tx, inbound); bErr == nil {
  1270. payload = built
  1271. } else {
  1272. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  1273. pushable = false
  1274. }
  1275. }
  1276. if pushable {
  1277. postCommitApply = func() {
  1278. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  1279. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  1280. } else {
  1281. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  1282. if inbound.Protocol != model.MTProto && inbound.Protocol != model.TUIC {
  1283. needRestart = true
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. }
  1291. if markDirty && inbound.NodeID != nil {
  1292. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1293. }
  1294. return nil
  1295. })
  1296. if err != nil {
  1297. return inbound, false, err
  1298. }
  1299. if postCommitApply != nil {
  1300. postCommitApply()
  1301. }
  1302. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1303. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1304. // in the generated config, so force a regen to wire it in.
  1305. if mtprotoRoutesThroughXray(inbound) {
  1306. needRestart = true
  1307. }
  1308. return inbound, needRestart, err
  1309. }
  1310. func (s *InboundService) DelInbound(id int) (bool, error) {
  1311. needRestart, nodePush, err := s.delInbound(id)
  1312. if nodePush != nil {
  1313. nodePush()
  1314. }
  1315. return needRestart, err
  1316. }
  1317. // delInbound deletes the central row and returns the node push instead of running
  1318. // it, so a bulk delete can fan the pushes out once every row is gone.
  1319. func (s *InboundService) delInbound(id int) (bool, func(), error) {
  1320. db := database.GetDB()
  1321. needRestart := false
  1322. var postCommitApply, nodePush func()
  1323. var ib model.Inbound
  1324. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1325. if loadErr == nil {
  1326. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1327. if shouldPushToRuntime {
  1328. if ib.NodeID != nil {
  1329. rt, push, _, perr := s.nodePushPlan(&ib)
  1330. if perr != nil {
  1331. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1332. } else if push {
  1333. nodePush = func() {
  1334. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1335. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1336. } else {
  1337. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1338. }
  1339. }
  1340. }
  1341. } else {
  1342. rt, push, _, perr := s.nodePushPlan(&ib)
  1343. if perr != nil {
  1344. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1345. } else if push {
  1346. postCommitApply = func() {
  1347. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1348. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1349. } else {
  1350. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1351. needRestart = true
  1352. }
  1353. }
  1354. } else {
  1355. needRestart = true
  1356. }
  1357. }
  1358. } else {
  1359. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1360. }
  1361. } else {
  1362. logger.Debug("DelInbound: inbound not found, id:", id)
  1363. }
  1364. if err := db.Transaction(func(tx *gorm.DB) error {
  1365. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1366. return err
  1367. }
  1368. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1369. return err
  1370. }
  1371. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1372. return err
  1373. }
  1374. // Drop the deleted inbound from any sub-balancer that selects it; a
  1375. // dangling id would emit a member no subscriber can resolve (#5648).
  1376. var balancers []model.SubBalancer
  1377. if err := tx.Find(&balancers).Error; err != nil {
  1378. return err
  1379. }
  1380. for i := range balancers {
  1381. before := balancers[i].InboundIds
  1382. balancers[i].InboundIds = slices.DeleteFunc(before, func(b int) bool { return b == id })
  1383. if len(balancers[i].InboundIds) == len(before) {
  1384. continue
  1385. }
  1386. if err := tx.Save(&balancers[i]).Error; err != nil {
  1387. return err
  1388. }
  1389. }
  1390. if loadErr == nil && ib.NodeID != nil {
  1391. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1392. }
  1393. return nil
  1394. }); err != nil {
  1395. return needRestart, nil, err
  1396. }
  1397. if postCommitApply != nil {
  1398. postCommitApply()
  1399. }
  1400. if loadErr == nil && ib.Tag != "" {
  1401. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1402. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1403. } else if routingChanged {
  1404. needRestart = true
  1405. }
  1406. }
  1407. if !database.IsPostgres() {
  1408. var count int64
  1409. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1410. return needRestart, nodePush, err
  1411. }
  1412. if count == 0 {
  1413. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1414. return needRestart, nodePush, err
  1415. }
  1416. }
  1417. }
  1418. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1419. if mtprotoRoutesThroughXray(&ib) {
  1420. needRestart = true
  1421. }
  1422. return needRestart, nodePush, nil
  1423. }
  1424. type BulkDelInboundResult struct {
  1425. Deleted int `json:"deleted"`
  1426. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1427. }
  1428. type BulkDelInboundReport struct {
  1429. Id int `json:"id"`
  1430. Reason string `json:"reason"`
  1431. }
  1432. // DelInbounds removes every inbound in the list, reusing the single-delete
  1433. // path per id. Failures are recorded in Skipped and processing continues for
  1434. // the rest; the aggregated needRestart is returned so the caller restarts
  1435. // xray at most once.
  1436. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1437. result := BulkDelInboundResult{}
  1438. needRestart := false
  1439. var pushIDs []int
  1440. var nodePushes []func()
  1441. for _, id := range ids {
  1442. r, nodePush, err := s.delInbound(id)
  1443. if nodePush != nil {
  1444. pushIDs = append(pushIDs, id)
  1445. nodePushes = append(nodePushes, nodePush)
  1446. }
  1447. if err != nil {
  1448. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1449. continue
  1450. }
  1451. result.Deleted++
  1452. if r {
  1453. needRestart = true
  1454. }
  1455. }
  1456. // Rows go one at a time for the shared routing rewrite; only node pushes fan out.
  1457. fanoutInboundResults(pushIDs, nodeFanoutConcurrency, func(i int) struct{} {
  1458. nodePushes[i]()
  1459. return struct{}{}
  1460. })
  1461. return result, needRestart, nil
  1462. }
  1463. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1464. db := database.GetDB()
  1465. inbound := &model.Inbound{}
  1466. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1467. if err != nil {
  1468. return nil, err
  1469. }
  1470. return inbound, nil
  1471. }
  1472. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1473. db := database.GetDB()
  1474. inbound := &model.Inbound{}
  1475. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1476. if err != nil {
  1477. return nil, err
  1478. }
  1479. s.enrichClientStats(db, []*model.Inbound{inbound})
  1480. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1481. return inbound, nil
  1482. }
  1483. // SetInboundSubSortIndex changes only the subscription sort order, so a
  1484. // reorder cannot carry a stale settings/client payload over another edit.
  1485. func (s *InboundService) SetInboundSubSortIndex(id int, index int) error {
  1486. index = normalizeSubSortIndex(index)
  1487. inbound, err := s.GetInbound(id)
  1488. if err != nil {
  1489. return err
  1490. }
  1491. if inbound.SubSortIndex == index {
  1492. return nil
  1493. }
  1494. db := database.GetDB()
  1495. if err := db.Transaction(func(tx *gorm.DB) error {
  1496. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1497. Update("sub_sort_index", index).Error; err != nil {
  1498. return err
  1499. }
  1500. if inbound.NodeID != nil {
  1501. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1502. }
  1503. return nil
  1504. }); err != nil {
  1505. return err
  1506. }
  1507. inbound.SubSortIndex = index
  1508. if inbound.NodeID == nil {
  1509. return nil
  1510. }
  1511. rt, push, _, perr := s.nodePushPlan(inbound)
  1512. if perr != nil {
  1513. return perr
  1514. }
  1515. if push {
  1516. narrow, ok := rt.(interface {
  1517. SetInboundSubSortIndex(context.Context, *model.Inbound, int) error
  1518. })
  1519. if !ok {
  1520. return fmt.Errorf("runtime %s does not support narrow subscription ordering updates", rt.Name())
  1521. }
  1522. if err := narrow.SetInboundSubSortIndex(context.Background(), inbound, index); err != nil {
  1523. logger.Warning("SetInboundSubSortIndex: remote metadata update on", rt.Name(), "failed:", err)
  1524. }
  1525. }
  1526. return nil
  1527. }
  1528. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1529. inbound, err := s.GetInbound(id)
  1530. if err != nil {
  1531. return false, err
  1532. }
  1533. if inbound.Enable == enable {
  1534. return false, nil
  1535. }
  1536. db := database.GetDB()
  1537. // Enabling puts this row's ports into the running config, and the guards ran
  1538. // only if it was saved: a restored or hand-edited row reaches it unchecked.
  1539. if enable && inbound.NodeID == nil {
  1540. conflict, err := checkPortConflictTx(db, inbound, inbound.Id)
  1541. if err != nil {
  1542. return false, err
  1543. }
  1544. if conflict != nil {
  1545. return false, common.NewError(conflict.String())
  1546. }
  1547. }
  1548. if err := db.Transaction(func(tx *gorm.DB) error {
  1549. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1550. Update("enable", enable).Error; err != nil {
  1551. return err
  1552. }
  1553. if inbound.NodeID != nil {
  1554. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1555. }
  1556. return nil
  1557. }); err != nil {
  1558. return false, err
  1559. }
  1560. inbound.Enable = enable
  1561. needRestart := false
  1562. rt, push, _, perr := s.nodePushPlan(inbound)
  1563. if perr != nil {
  1564. return false, perr
  1565. }
  1566. // Remote nodes interpret DelInbound as a real row delete (it hits
  1567. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1568. // switch on a remote inbound used to wipe the row entirely (#4402).
  1569. // PATCH the remote row via UpdateInbound instead — preserves the
  1570. // settings/client history and just flips the enable flag.
  1571. if inbound.NodeID != nil {
  1572. if push {
  1573. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1574. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1575. }
  1576. }
  1577. return false, nil
  1578. }
  1579. if mtprotoRoutesThroughXray(inbound) {
  1580. needRestart = true
  1581. }
  1582. if !push {
  1583. return true, nil
  1584. }
  1585. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1586. !strings.Contains(err.Error(), "not found") {
  1587. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1588. needRestart = true
  1589. }
  1590. if !enable {
  1591. return needRestart, nil
  1592. }
  1593. runtimeInbound, err := s.buildInboundForLocalRuntime(db, inbound)
  1594. if err != nil {
  1595. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1596. return true, nil
  1597. }
  1598. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1599. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1600. needRestart = true
  1601. }
  1602. return needRestart, nil
  1603. }
  1604. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1605. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1606. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1607. // Normalize streamSettings based on protocol
  1608. s.normalizeStreamSettings(inbound)
  1609. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1610. return inbound, false, err
  1611. }
  1612. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1613. return inbound, false, err
  1614. }
  1615. s.normalizeMtprotoSecret(inbound)
  1616. oldInbound, err := s.GetInbound(inbound.Id)
  1617. if err != nil {
  1618. return inbound, false, err
  1619. }
  1620. if err := s.normalizeAmneziaWGSettings(inbound, oldInbound.Settings); err != nil {
  1621. return inbound, false, err
  1622. }
  1623. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1624. clients, err := s.GetClients(inbound)
  1625. if err != nil {
  1626. return inbound, false, err
  1627. }
  1628. if err := validateClientsRenewal(clients); err != nil {
  1629. return inbound, false, err
  1630. }
  1631. if inbound.Protocol == model.Hysteria {
  1632. for _, client := range clients {
  1633. if client.Auth == "" {
  1634. return inbound, false, common.NewError("empty client ID")
  1635. }
  1636. }
  1637. }
  1638. if inbound.Protocol == model.TUIC {
  1639. for _, client := range clients {
  1640. if client.ID == "" {
  1641. return inbound, false, common.NewError("empty client ID")
  1642. }
  1643. if client.Password == "" {
  1644. return inbound, false, common.NewError("tuic client requires a password")
  1645. }
  1646. if client.Email == "" {
  1647. return inbound, false, common.NewError("empty client email")
  1648. }
  1649. }
  1650. }
  1651. // Grandfather a row that was already stored incomplete so it stays editable;
  1652. // only a save that breaks a previously valid TLS block is refused.
  1653. if !s.FromNodeSync {
  1654. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1655. if validateInboundTLSCertificates(oldInbound.StreamSettings) == nil {
  1656. return inbound, false, err
  1657. }
  1658. }
  1659. }
  1660. // Restore the stored NodeID before the port-conflict check so a node inbound
  1661. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1662. inbound.NodeID = oldInbound.NodeID
  1663. // The node assignment is the stored one, so only a protocol change can
  1664. // introduce one; a row adopted from a node keeps the protocol it arrived with.
  1665. if inbound.NodeID != nil && inbound.Protocol != oldInbound.Protocol && !isNodeEligibleProtocol(inbound.Protocol) {
  1666. return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
  1667. }
  1668. // Capture the pre-edit protocol and routing state before oldInbound is
  1669. // overwritten with the new values further down, then ensure a routed
  1670. // inbound keeps a stable egress port (reusing the one already stored).
  1671. oldProtocol := oldInbound.Protocol
  1672. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1673. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1674. return inbound, false, err
  1675. }
  1676. tag := oldInbound.Tag
  1677. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1678. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1679. needRestart := false
  1680. var postCommitApply func()
  1681. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1682. // Re-read inside the writer: a traffic tick since the read above moved the
  1683. // counters and may have renewed or disabled clients.
  1684. stored := &model.Inbound{}
  1685. if err := tx.First(stored, inbound.Id).Error; err != nil {
  1686. return err
  1687. }
  1688. oldInbound = stored
  1689. if !s.FromNodeSync {
  1690. inbound.Settings = keepStoredClientLifecycle(inbound.Settings, stored.Settings)
  1691. }
  1692. conflict, cErr := checkPortConflictTx(tx, inbound, inbound.Id)
  1693. if cErr != nil {
  1694. return cErr
  1695. }
  1696. if conflict != nil {
  1697. return common.NewError(conflict.String())
  1698. }
  1699. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1700. return err
  1701. }
  1702. // Ensure created_at and updated_at exist in inbound.Settings clients
  1703. {
  1704. var oldSettings map[string]any
  1705. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1706. emailToCreated := map[string]int64{}
  1707. emailToUpdated := map[string]int64{}
  1708. if oldSettings != nil {
  1709. if oc, ok := oldSettings["clients"].([]any); ok {
  1710. for _, it := range oc {
  1711. if m, ok2 := it.(map[string]any); ok2 {
  1712. if email, ok3 := m["email"].(string); ok3 {
  1713. switch v := m["created_at"].(type) {
  1714. case float64:
  1715. emailToCreated[email] = int64(v)
  1716. case int64:
  1717. emailToCreated[email] = v
  1718. }
  1719. switch v := m["updated_at"].(type) {
  1720. case float64:
  1721. emailToUpdated[email] = int64(v)
  1722. case int64:
  1723. emailToUpdated[email] = v
  1724. }
  1725. }
  1726. }
  1727. }
  1728. }
  1729. }
  1730. var newSettings map[string]any
  1731. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1732. now := time.Now().Unix() * 1000
  1733. if nSlice, ok := newSettings["clients"].([]any); ok {
  1734. for i := range nSlice {
  1735. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1736. email, _ := m["email"].(string)
  1737. if _, ok3 := m["created_at"]; !ok3 {
  1738. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1739. m["created_at"] = v
  1740. } else {
  1741. m["created_at"] = now
  1742. }
  1743. }
  1744. // Preserve client's updated_at if present; do not bump on parent inbound update
  1745. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1746. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1747. m["updated_at"] = v
  1748. }
  1749. }
  1750. nSlice[i] = m
  1751. }
  1752. }
  1753. newSettings["clients"] = nSlice
  1754. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1755. inbound.Settings = string(bs)
  1756. }
  1757. }
  1758. }
  1759. }
  1760. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1761. // keep their old length and would be rejected by xray. Regenerate mismatched
  1762. // client keys so the inbound stays connectable.
  1763. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1764. inbound.Settings = normalized
  1765. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1766. }
  1767. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1768. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1769. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1770. // but was stripped while the inbound was ineligible.
  1771. if !inbound.DisableFlow {
  1772. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1773. inbound.Settings = restored
  1774. }
  1775. } else {
  1776. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1777. inbound.Settings = stripped
  1778. }
  1779. }
  1780. oldInbound.Total = inbound.Total
  1781. oldInbound.Remark = inbound.Remark
  1782. oldInbound.SubSortIndex = inbound.SubSortIndex
  1783. oldInbound.ExcludeFromSub = inbound.ExcludeFromSub
  1784. oldInbound.Enable = inbound.Enable
  1785. oldInbound.ExpiryTime = inbound.ExpiryTime
  1786. oldInbound.TrafficReset = inbound.TrafficReset
  1787. oldInbound.TrafficResetDay = inbound.TrafficResetDay
  1788. oldInbound.Listen = inbound.Listen
  1789. oldInbound.Port = inbound.Port
  1790. oldInbound.Protocol = inbound.Protocol
  1791. oldInbound.DisableFlow = inbound.DisableFlow
  1792. oldInbound.Settings = inbound.Settings
  1793. oldInbound.StreamSettings = inbound.StreamSettings
  1794. oldInbound.Sniffing = inbound.Sniffing
  1795. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1796. normalizeInboundShareAddress(oldInbound)
  1797. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1798. inbound.ShareAddr = oldInbound.ShareAddr
  1799. } else {
  1800. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1801. return err
  1802. }
  1803. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1804. oldInbound.ShareAddr = inbound.ShareAddr
  1805. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1806. return err
  1807. }
  1808. }
  1809. if oldTagWasAuto && inbound.Tag == tag {
  1810. inbound.Tag = ""
  1811. }
  1812. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1813. if err != nil {
  1814. return err
  1815. }
  1816. oldInbound.Tag = resolvedTag
  1817. inbound.Tag = oldInbound.Tag
  1818. if oldInbound.NodeID == nil {
  1819. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1820. if perr != nil {
  1821. return perr
  1822. }
  1823. if !push {
  1824. needRestart = true
  1825. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto || oldProtocol == model.TUIC || oldInbound.Protocol == model.TUIC {
  1826. oldSnapshot := *oldInbound
  1827. oldSnapshot.Tag = tag
  1828. oldSnapshot.Protocol = oldProtocol
  1829. payload := oldInbound
  1830. pushable := true
  1831. if inbound.Enable {
  1832. if built, err2 := s.buildInboundForLocalRuntime(tx, oldInbound); err2 == nil {
  1833. payload = built
  1834. } else {
  1835. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1836. pushable = false
  1837. }
  1838. }
  1839. newProtocolIsSidecar := oldInbound.Protocol == model.MTProto || oldInbound.Protocol == model.TUIC
  1840. if pushable {
  1841. postCommitApply = func() {
  1842. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1843. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1844. } else {
  1845. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1846. if !newProtocolIsSidecar {
  1847. needRestart = true
  1848. }
  1849. }
  1850. }
  1851. }
  1852. } else {
  1853. oldSnapshot := *oldInbound
  1854. oldSnapshot.Tag = tag
  1855. var runtimeInbound *model.Inbound
  1856. if inbound.Enable {
  1857. var err2 error
  1858. runtimeInbound, err2 = s.buildInboundForLocalRuntime(tx, oldInbound)
  1859. if err2 != nil {
  1860. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1861. needRestart = true
  1862. }
  1863. }
  1864. postCommitApply = func() {
  1865. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1866. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1867. }
  1868. if runtimeInbound == nil {
  1869. return
  1870. }
  1871. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1872. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1873. } else {
  1874. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1875. needRestart = true
  1876. }
  1877. }
  1878. }
  1879. } else {
  1880. nodeID := *oldInbound.NodeID
  1881. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1882. return err
  1883. }
  1884. }
  1885. if err := tx.Save(oldInbound).Error; err != nil {
  1886. return err
  1887. }
  1888. newClients, gcErr := s.GetClients(oldInbound)
  1889. if gcErr != nil {
  1890. return gcErr
  1891. }
  1892. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1893. return err
  1894. }
  1895. if oldInbound.NodeID != nil {
  1896. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1897. return err
  1898. }
  1899. }
  1900. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1901. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1902. // settings.
  1903. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1904. needRestart = true
  1905. }
  1906. return nil
  1907. })
  1908. if txErr != nil {
  1909. return inbound, false, txErr
  1910. }
  1911. if postCommitApply != nil {
  1912. postCommitApply()
  1913. }
  1914. // After the rename is committed, point any routing rules / loopback outbounds
  1915. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1916. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1917. // can't roll back the inbound edit.
  1918. if tag != oldInbound.Tag {
  1919. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1920. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1921. } else if routingChanged {
  1922. needRestart = true
  1923. }
  1924. }
  1925. return inbound, needRestart, nil
  1926. }
  1927. // A node mirrors this payload into its own DB, so every client must survive:
  1928. // filtering one out makes the node delete it, and the master then mirrors that.
  1929. func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1930. if inbound == nil {
  1931. return nil, fmt.Errorf("inbound is nil")
  1932. }
  1933. built := *inbound
  1934. settings := map[string]any{}
  1935. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1936. return nil, err
  1937. }
  1938. if !inboundCanHostFallbacks(inbound) {
  1939. return &built, nil
  1940. }
  1941. fallbacks, err := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  1942. if err != nil {
  1943. return nil, err
  1944. }
  1945. if len(fallbacks) == 0 {
  1946. return &built, nil
  1947. }
  1948. generic := make([]any, 0, len(fallbacks))
  1949. for _, f := range fallbacks {
  1950. generic = append(generic, f)
  1951. }
  1952. settings["fallbacks"] = generic
  1953. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1954. if mErr != nil {
  1955. return nil, mErr
  1956. }
  1957. built.Settings = string(modifiedSettings)
  1958. return &built, nil
  1959. }
  1960. // Strips disabled clients on top of the node payload. Safe only because the
  1961. // target here is an in-memory Xray/mtg config, not another panel's database.
  1962. func (s *InboundService) buildInboundForLocalRuntime(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1963. built, err := s.buildInboundForNodePush(tx, inbound)
  1964. if err != nil {
  1965. return nil, err
  1966. }
  1967. settings := map[string]any{}
  1968. if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil {
  1969. return nil, err
  1970. }
  1971. clients, ok := settings["clients"].([]any)
  1972. if !ok {
  1973. return built, nil
  1974. }
  1975. emails := make([]string, 0, len(clients))
  1976. for _, client := range clients {
  1977. if c, ok := client.(map[string]any); ok {
  1978. email, _ := c["email"].(string)
  1979. emails = append(emails, email)
  1980. }
  1981. }
  1982. disabled, err := trafficDisabledEmails(tx, emails)
  1983. if err != nil {
  1984. return nil, err
  1985. }
  1986. finalClients := make([]any, 0, len(clients))
  1987. for _, client := range clients {
  1988. c, ok := client.(map[string]any)
  1989. if !ok {
  1990. continue
  1991. }
  1992. email, _ := c["email"].(string)
  1993. if _, off := disabled[email]; off {
  1994. continue
  1995. }
  1996. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1997. continue
  1998. }
  1999. finalClients = append(finalClients, c)
  2000. }
  2001. settings["clients"] = finalClients
  2002. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2003. if err != nil {
  2004. return nil, err
  2005. }
  2006. runtimeInbound := *built
  2007. runtimeInbound.Settings = string(modifiedSettings)
  2008. return &runtimeInbound, nil
  2009. }
  2010. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  2011. // list: removes rows for emails that disappeared, inserts rows for newly-added
  2012. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  2013. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  2014. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  2015. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  2016. oldClients, err := s.GetClients(oldInbound)
  2017. if err != nil {
  2018. return err
  2019. }
  2020. newClients, err := s.GetClients(newInbound)
  2021. if err != nil {
  2022. return err
  2023. }
  2024. // Email is the unique key for ClientTraffic rows. Clients without an
  2025. // email have no stats row to sync — skip them on both sides instead of
  2026. // risking a unique-constraint hit or accidental delete of an unrelated row.
  2027. oldEmails := make(map[string]struct{}, len(oldClients))
  2028. for i := range oldClients {
  2029. if oldClients[i].Email == "" {
  2030. continue
  2031. }
  2032. oldEmails[oldClients[i].Email] = struct{}{}
  2033. }
  2034. newEmails := make(map[string]struct{}, len(newClients))
  2035. for i := range newClients {
  2036. if newClients[i].Email == "" {
  2037. continue
  2038. }
  2039. newEmails[newClients[i].Email] = struct{}{}
  2040. }
  2041. // Drop stats rows for removed emails — but not when a sibling inbound
  2042. // still references the email, since the row is the shared accumulator.
  2043. for i := range oldClients {
  2044. email := oldClients[i].Email
  2045. if email == "" {
  2046. continue
  2047. }
  2048. if _, kept := newEmails[email]; kept {
  2049. continue
  2050. }
  2051. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  2052. if err != nil {
  2053. return err
  2054. }
  2055. if stillUsed {
  2056. continue
  2057. }
  2058. if err := s.DelClientStat(tx, email); err != nil {
  2059. return err
  2060. }
  2061. // Keep inbound_client_ips in sync when the inbound edit drops an
  2062. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  2063. if err := s.DelClientIPs(tx, email); err != nil {
  2064. return err
  2065. }
  2066. }
  2067. for i := range newClients {
  2068. email := newClients[i].Email
  2069. if email == "" {
  2070. continue
  2071. }
  2072. if _, existed := oldEmails[email]; existed {
  2073. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  2074. return err
  2075. }
  2076. continue
  2077. }
  2078. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  2079. return err
  2080. }
  2081. }
  2082. return nil
  2083. }
  2084. func (s *InboundService) GetInboundTags() (string, error) {
  2085. db := database.GetDB()
  2086. var inboundTags []string
  2087. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2088. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2089. return "", err
  2090. }
  2091. tags, _ := json.Marshal(inboundTags)
  2092. return string(tags), nil
  2093. }
  2094. func (s *InboundService) GetClientReverseTags() (string, error) {
  2095. db := database.GetDB()
  2096. var inbounds []model.Inbound
  2097. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2098. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2099. return "[]", err
  2100. }
  2101. tagSet := make(map[string]struct{})
  2102. for _, inbound := range inbounds {
  2103. var settings map[string]any
  2104. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2105. continue
  2106. }
  2107. clients, ok := settings["clients"].([]any)
  2108. if !ok {
  2109. continue
  2110. }
  2111. for _, client := range clients {
  2112. clientMap, ok := client.(map[string]any)
  2113. if !ok {
  2114. continue
  2115. }
  2116. reverse, ok := clientMap["reverse"].(map[string]any)
  2117. if !ok {
  2118. continue
  2119. }
  2120. tag, _ := reverse["tag"].(string)
  2121. tag = strings.TrimSpace(tag)
  2122. if tag != "" {
  2123. tagSet[tag] = struct{}{}
  2124. }
  2125. }
  2126. }
  2127. rawTags := make([]string, 0, len(tagSet))
  2128. for tag := range tagSet {
  2129. rawTags = append(rawTags, tag)
  2130. }
  2131. sort.Strings(rawTags)
  2132. result, _ := json.Marshal(rawTags)
  2133. return string(result), nil
  2134. }
  2135. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2136. db := database.GetDB()
  2137. var inbounds []*model.Inbound
  2138. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2139. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2140. return nil, err
  2141. }
  2142. return inbounds, nil
  2143. }