inbound.go 71 KB

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