inbound.go 71 KB

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