1
0

inbound.go 73 KB

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