inbound.go 73 KB

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