inbound.go 68 KB

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