inbound.go 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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 neither check with ignoreId==0.
  1182. if inbound.NodeID == nil && inbound.Protocol == model.AmneziaWG {
  1183. conflict, cErr := checkAmneziawgnetSocksRelayCollision(tx, inbound.Id)
  1184. if cErr != nil {
  1185. return cErr
  1186. }
  1187. if conflict != nil {
  1188. return common.NewError(conflict.String())
  1189. }
  1190. conflict, cErr = checkAmneziawgnetSocksReverseConflict(tx, inbound.Id)
  1191. if cErr != nil {
  1192. return cErr
  1193. }
  1194. if conflict != nil {
  1195. return common.NewError(conflict.String())
  1196. }
  1197. }
  1198. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  1199. // Enable=true on every imported stat row) are authoritative for this call
  1200. // and must not be clobbered by the AddClientStat loop below, which derives
  1201. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  1202. // possibly-stale source for the same columns on a plain (non-import) create.
  1203. statEmails := make(map[string]bool, len(inbound.ClientStats))
  1204. for i := range inbound.ClientStats {
  1205. if inbound.ClientStats[i].Email == "" {
  1206. continue
  1207. }
  1208. statEmails[inbound.ClientStats[i].Email] = true
  1209. inbound.ClientStats[i].Id = 0
  1210. inbound.ClientStats[i].InboundId = inbound.Id
  1211. if err := tx.Clauses(clause.OnConflict{
  1212. Columns: []clause.Column{{Name: "email"}},
  1213. DoNothing: true,
  1214. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  1215. return err
  1216. }
  1217. }
  1218. for _, client := range clients {
  1219. if statEmails[client.Email] {
  1220. continue
  1221. }
  1222. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  1223. return err
  1224. }
  1225. }
  1226. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  1227. return err
  1228. }
  1229. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  1230. return err
  1231. }
  1232. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1233. return err
  1234. }
  1235. if inbound.NodeID != nil {
  1236. nodeID := *inbound.NodeID
  1237. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  1238. return err
  1239. }
  1240. }
  1241. if inbound.Enable {
  1242. if inbound.NodeID != nil {
  1243. markDirty = true
  1244. } else {
  1245. rt, push, _, perr := s.nodePushPlan(inbound)
  1246. if perr != nil {
  1247. return perr
  1248. }
  1249. if push {
  1250. payload := inbound
  1251. pushable := true
  1252. if inbound.Protocol == model.MTProto || inbound.Protocol == model.TUIC {
  1253. if built, bErr := s.buildInboundForLocalRuntime(tx, inbound); bErr == nil {
  1254. payload = built
  1255. } else {
  1256. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  1257. pushable = false
  1258. }
  1259. }
  1260. if pushable {
  1261. postCommitApply = func() {
  1262. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  1263. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  1264. } else {
  1265. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  1266. if inbound.Protocol != model.MTProto && inbound.Protocol != model.TUIC {
  1267. needRestart = true
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. }
  1275. if markDirty && inbound.NodeID != nil {
  1276. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1277. }
  1278. return nil
  1279. })
  1280. if err != nil {
  1281. return inbound, false, err
  1282. }
  1283. if postCommitApply != nil {
  1284. postCommitApply()
  1285. }
  1286. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1287. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1288. // in the generated config, so force a regen to wire it in.
  1289. if mtprotoRoutesThroughXray(inbound) {
  1290. needRestart = true
  1291. }
  1292. return inbound, needRestart, err
  1293. }
  1294. func (s *InboundService) DelInbound(id int) (bool, error) {
  1295. db := database.GetDB()
  1296. needRestart := false
  1297. var postCommitApply func()
  1298. var ib model.Inbound
  1299. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1300. if loadErr == nil {
  1301. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1302. if shouldPushToRuntime {
  1303. if ib.NodeID != nil {
  1304. rt, push, _, perr := s.nodePushPlan(&ib)
  1305. if perr != nil {
  1306. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1307. } else if push {
  1308. postCommitApply = func() {
  1309. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1310. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1311. } else {
  1312. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1313. }
  1314. }
  1315. }
  1316. } else {
  1317. rt, push, _, perr := s.nodePushPlan(&ib)
  1318. if perr != nil {
  1319. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1320. } else if push {
  1321. postCommitApply = func() {
  1322. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1323. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1324. } else {
  1325. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1326. needRestart = true
  1327. }
  1328. }
  1329. } else {
  1330. needRestart = true
  1331. }
  1332. }
  1333. } else {
  1334. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1335. }
  1336. } else {
  1337. logger.Debug("DelInbound: inbound not found, id:", id)
  1338. }
  1339. if err := db.Transaction(func(tx *gorm.DB) error {
  1340. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1341. return err
  1342. }
  1343. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1344. return err
  1345. }
  1346. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1347. return err
  1348. }
  1349. // Drop the deleted inbound from any sub-balancer that selects it; a
  1350. // dangling id would emit a member no subscriber can resolve (#5648).
  1351. var balancers []model.SubBalancer
  1352. if err := tx.Find(&balancers).Error; err != nil {
  1353. return err
  1354. }
  1355. for i := range balancers {
  1356. before := balancers[i].InboundIds
  1357. balancers[i].InboundIds = slices.DeleteFunc(before, func(b int) bool { return b == id })
  1358. if len(balancers[i].InboundIds) == len(before) {
  1359. continue
  1360. }
  1361. if err := tx.Save(&balancers[i]).Error; err != nil {
  1362. return err
  1363. }
  1364. }
  1365. if loadErr == nil && ib.NodeID != nil {
  1366. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1367. }
  1368. return nil
  1369. }); err != nil {
  1370. return needRestart, err
  1371. }
  1372. if postCommitApply != nil {
  1373. postCommitApply()
  1374. }
  1375. if loadErr == nil && ib.Tag != "" {
  1376. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1377. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1378. } else if routingChanged {
  1379. needRestart = true
  1380. }
  1381. }
  1382. if !database.IsPostgres() {
  1383. var count int64
  1384. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1385. return needRestart, err
  1386. }
  1387. if count == 0 {
  1388. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1389. return needRestart, err
  1390. }
  1391. }
  1392. }
  1393. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1394. if mtprotoRoutesThroughXray(&ib) {
  1395. needRestart = true
  1396. }
  1397. return needRestart, nil
  1398. }
  1399. type BulkDelInboundResult struct {
  1400. Deleted int `json:"deleted"`
  1401. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1402. }
  1403. type BulkDelInboundReport struct {
  1404. Id int `json:"id"`
  1405. Reason string `json:"reason"`
  1406. }
  1407. // DelInbounds removes every inbound in the list, reusing the single-delete
  1408. // path per id. Failures are recorded in Skipped and processing continues for
  1409. // the rest; the aggregated needRestart is returned so the caller restarts
  1410. // xray at most once.
  1411. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1412. result := BulkDelInboundResult{}
  1413. needRestart := false
  1414. for _, id := range ids {
  1415. r, err := s.DelInbound(id)
  1416. if err != nil {
  1417. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1418. continue
  1419. }
  1420. result.Deleted++
  1421. if r {
  1422. needRestart = true
  1423. }
  1424. }
  1425. return result, needRestart, nil
  1426. }
  1427. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1428. db := database.GetDB()
  1429. inbound := &model.Inbound{}
  1430. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1431. if err != nil {
  1432. return nil, err
  1433. }
  1434. return inbound, nil
  1435. }
  1436. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1437. db := database.GetDB()
  1438. inbound := &model.Inbound{}
  1439. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1440. if err != nil {
  1441. return nil, err
  1442. }
  1443. s.enrichClientStats(db, []*model.Inbound{inbound})
  1444. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1445. return inbound, nil
  1446. }
  1447. // SetInboundSubSortIndex changes only the subscription sort order, so a
  1448. // reorder cannot carry a stale settings/client payload over another edit.
  1449. func (s *InboundService) SetInboundSubSortIndex(id int, index int) error {
  1450. index = normalizeSubSortIndex(index)
  1451. inbound, err := s.GetInbound(id)
  1452. if err != nil {
  1453. return err
  1454. }
  1455. if inbound.SubSortIndex == index {
  1456. return nil
  1457. }
  1458. db := database.GetDB()
  1459. if err := db.Transaction(func(tx *gorm.DB) error {
  1460. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1461. Update("sub_sort_index", index).Error; err != nil {
  1462. return err
  1463. }
  1464. if inbound.NodeID != nil {
  1465. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1466. }
  1467. return nil
  1468. }); err != nil {
  1469. return err
  1470. }
  1471. inbound.SubSortIndex = index
  1472. if inbound.NodeID == nil {
  1473. return nil
  1474. }
  1475. rt, push, _, perr := s.nodePushPlan(inbound)
  1476. if perr != nil {
  1477. return perr
  1478. }
  1479. if push {
  1480. narrow, ok := rt.(interface {
  1481. SetInboundSubSortIndex(context.Context, *model.Inbound, int) error
  1482. })
  1483. if !ok {
  1484. return fmt.Errorf("runtime %s does not support narrow subscription ordering updates", rt.Name())
  1485. }
  1486. if err := narrow.SetInboundSubSortIndex(context.Background(), inbound, index); err != nil {
  1487. logger.Warning("SetInboundSubSortIndex: remote metadata update on", rt.Name(), "failed:", err)
  1488. }
  1489. }
  1490. return nil
  1491. }
  1492. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1493. inbound, err := s.GetInbound(id)
  1494. if err != nil {
  1495. return false, err
  1496. }
  1497. if inbound.Enable == enable {
  1498. return false, nil
  1499. }
  1500. db := database.GetDB()
  1501. if err := db.Transaction(func(tx *gorm.DB) error {
  1502. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1503. Update("enable", enable).Error; err != nil {
  1504. return err
  1505. }
  1506. if inbound.NodeID != nil {
  1507. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1508. }
  1509. return nil
  1510. }); err != nil {
  1511. return false, err
  1512. }
  1513. inbound.Enable = enable
  1514. needRestart := false
  1515. rt, push, _, perr := s.nodePushPlan(inbound)
  1516. if perr != nil {
  1517. return false, perr
  1518. }
  1519. // Remote nodes interpret DelInbound as a real row delete (it hits
  1520. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1521. // switch on a remote inbound used to wipe the row entirely (#4402).
  1522. // PATCH the remote row via UpdateInbound instead — preserves the
  1523. // settings/client history and just flips the enable flag.
  1524. if inbound.NodeID != nil {
  1525. if push {
  1526. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1527. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1528. }
  1529. }
  1530. return false, nil
  1531. }
  1532. if mtprotoRoutesThroughXray(inbound) {
  1533. needRestart = true
  1534. }
  1535. if !push {
  1536. return true, nil
  1537. }
  1538. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1539. !strings.Contains(err.Error(), "not found") {
  1540. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1541. needRestart = true
  1542. }
  1543. if !enable {
  1544. return needRestart, nil
  1545. }
  1546. runtimeInbound, err := s.buildInboundForLocalRuntime(db, inbound)
  1547. if err != nil {
  1548. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1549. return true, nil
  1550. }
  1551. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1552. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1553. needRestart = true
  1554. }
  1555. return needRestart, nil
  1556. }
  1557. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1558. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1559. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1560. // Normalize streamSettings based on protocol
  1561. s.normalizeStreamSettings(inbound)
  1562. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1563. return inbound, false, err
  1564. }
  1565. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1566. return inbound, false, err
  1567. }
  1568. s.normalizeMtprotoSecret(inbound)
  1569. oldInbound, err := s.GetInbound(inbound.Id)
  1570. if err != nil {
  1571. return inbound, false, err
  1572. }
  1573. if err := s.normalizeAmneziaWGSettings(inbound, oldInbound.Settings); err != nil {
  1574. return inbound, false, err
  1575. }
  1576. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1577. clients, err := s.GetClients(inbound)
  1578. if err != nil {
  1579. return inbound, false, err
  1580. }
  1581. if inbound.Protocol == model.Hysteria {
  1582. for _, client := range clients {
  1583. if client.Auth == "" {
  1584. return inbound, false, common.NewError("empty client ID")
  1585. }
  1586. }
  1587. }
  1588. if inbound.Protocol == model.TUIC {
  1589. for _, client := range clients {
  1590. if client.ID == "" {
  1591. return inbound, false, common.NewError("empty client ID")
  1592. }
  1593. if client.Password == "" {
  1594. return inbound, false, common.NewError("tuic client requires a password")
  1595. }
  1596. if client.Email == "" {
  1597. return inbound, false, common.NewError("empty client email")
  1598. }
  1599. }
  1600. }
  1601. // Grandfather a row that was already stored incomplete so it stays editable;
  1602. // only a save that breaks a previously valid TLS block is refused.
  1603. if !s.FromNodeSync {
  1604. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1605. if validateInboundTLSCertificates(oldInbound.StreamSettings) == nil {
  1606. return inbound, false, err
  1607. }
  1608. }
  1609. }
  1610. // Restore the stored NodeID before the port-conflict check so a node inbound
  1611. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1612. inbound.NodeID = oldInbound.NodeID
  1613. // The node assignment is the stored one, so only a protocol change can
  1614. // introduce one; a row adopted from a node keeps the protocol it arrived with.
  1615. if inbound.NodeID != nil && inbound.Protocol != oldInbound.Protocol && !isNodeEligibleProtocol(inbound.Protocol) {
  1616. return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
  1617. }
  1618. // Capture the pre-edit protocol and routing state before oldInbound is
  1619. // overwritten with the new values further down, then ensure a routed
  1620. // inbound keeps a stable egress port (reusing the one already stored).
  1621. oldProtocol := oldInbound.Protocol
  1622. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1623. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1624. return inbound, false, err
  1625. }
  1626. tag := oldInbound.Tag
  1627. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1628. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1629. needRestart := false
  1630. var postCommitApply func()
  1631. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1632. conflict, cErr := checkPortConflictTx(tx, inbound, inbound.Id)
  1633. if cErr != nil {
  1634. return cErr
  1635. }
  1636. if conflict != nil {
  1637. return common.NewError(conflict.String())
  1638. }
  1639. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1640. return err
  1641. }
  1642. // Ensure created_at and updated_at exist in inbound.Settings clients
  1643. {
  1644. var oldSettings map[string]any
  1645. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1646. emailToCreated := map[string]int64{}
  1647. emailToUpdated := map[string]int64{}
  1648. if oldSettings != nil {
  1649. if oc, ok := oldSettings["clients"].([]any); ok {
  1650. for _, it := range oc {
  1651. if m, ok2 := it.(map[string]any); ok2 {
  1652. if email, ok3 := m["email"].(string); ok3 {
  1653. switch v := m["created_at"].(type) {
  1654. case float64:
  1655. emailToCreated[email] = int64(v)
  1656. case int64:
  1657. emailToCreated[email] = v
  1658. }
  1659. switch v := m["updated_at"].(type) {
  1660. case float64:
  1661. emailToUpdated[email] = int64(v)
  1662. case int64:
  1663. emailToUpdated[email] = v
  1664. }
  1665. }
  1666. }
  1667. }
  1668. }
  1669. }
  1670. var newSettings map[string]any
  1671. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1672. now := time.Now().Unix() * 1000
  1673. if nSlice, ok := newSettings["clients"].([]any); ok {
  1674. for i := range nSlice {
  1675. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1676. email, _ := m["email"].(string)
  1677. if _, ok3 := m["created_at"]; !ok3 {
  1678. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1679. m["created_at"] = v
  1680. } else {
  1681. m["created_at"] = now
  1682. }
  1683. }
  1684. // Preserve client's updated_at if present; do not bump on parent inbound update
  1685. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1686. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1687. m["updated_at"] = v
  1688. }
  1689. }
  1690. nSlice[i] = m
  1691. }
  1692. }
  1693. newSettings["clients"] = nSlice
  1694. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1695. inbound.Settings = string(bs)
  1696. }
  1697. }
  1698. }
  1699. }
  1700. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1701. // keep their old length and would be rejected by xray. Regenerate mismatched
  1702. // client keys so the inbound stays connectable.
  1703. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1704. inbound.Settings = normalized
  1705. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1706. }
  1707. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1708. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1709. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1710. // but was stripped while the inbound was ineligible.
  1711. if !inbound.DisableFlow {
  1712. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1713. inbound.Settings = restored
  1714. }
  1715. } else {
  1716. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1717. inbound.Settings = stripped
  1718. }
  1719. }
  1720. oldInbound.Total = inbound.Total
  1721. oldInbound.Remark = inbound.Remark
  1722. oldInbound.SubSortIndex = inbound.SubSortIndex
  1723. oldInbound.Enable = inbound.Enable
  1724. oldInbound.ExpiryTime = inbound.ExpiryTime
  1725. oldInbound.TrafficReset = inbound.TrafficReset
  1726. oldInbound.TrafficResetDay = inbound.TrafficResetDay
  1727. oldInbound.Listen = inbound.Listen
  1728. oldInbound.Port = inbound.Port
  1729. oldInbound.Protocol = inbound.Protocol
  1730. oldInbound.DisableFlow = inbound.DisableFlow
  1731. oldInbound.Settings = inbound.Settings
  1732. oldInbound.StreamSettings = inbound.StreamSettings
  1733. oldInbound.Sniffing = inbound.Sniffing
  1734. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1735. normalizeInboundShareAddress(oldInbound)
  1736. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1737. inbound.ShareAddr = oldInbound.ShareAddr
  1738. } else {
  1739. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1740. return err
  1741. }
  1742. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1743. oldInbound.ShareAddr = inbound.ShareAddr
  1744. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1745. return err
  1746. }
  1747. }
  1748. if oldTagWasAuto && inbound.Tag == tag {
  1749. inbound.Tag = ""
  1750. }
  1751. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1752. if err != nil {
  1753. return err
  1754. }
  1755. oldInbound.Tag = resolvedTag
  1756. inbound.Tag = oldInbound.Tag
  1757. if oldInbound.NodeID == nil {
  1758. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1759. if perr != nil {
  1760. return perr
  1761. }
  1762. if !push {
  1763. needRestart = true
  1764. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto || oldProtocol == model.TUIC || oldInbound.Protocol == model.TUIC {
  1765. oldSnapshot := *oldInbound
  1766. oldSnapshot.Tag = tag
  1767. oldSnapshot.Protocol = oldProtocol
  1768. payload := oldInbound
  1769. pushable := true
  1770. if inbound.Enable {
  1771. if built, err2 := s.buildInboundForLocalRuntime(tx, oldInbound); err2 == nil {
  1772. payload = built
  1773. } else {
  1774. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1775. pushable = false
  1776. }
  1777. }
  1778. newProtocolIsSidecar := oldInbound.Protocol == model.MTProto || oldInbound.Protocol == model.TUIC
  1779. if pushable {
  1780. postCommitApply = func() {
  1781. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1782. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1783. } else {
  1784. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1785. if !newProtocolIsSidecar {
  1786. needRestart = true
  1787. }
  1788. }
  1789. }
  1790. }
  1791. } else {
  1792. oldSnapshot := *oldInbound
  1793. oldSnapshot.Tag = tag
  1794. var runtimeInbound *model.Inbound
  1795. if inbound.Enable {
  1796. var err2 error
  1797. runtimeInbound, err2 = s.buildInboundForLocalRuntime(tx, oldInbound)
  1798. if err2 != nil {
  1799. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1800. needRestart = true
  1801. }
  1802. }
  1803. postCommitApply = func() {
  1804. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1805. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1806. }
  1807. if runtimeInbound == nil {
  1808. return
  1809. }
  1810. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1811. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1812. } else {
  1813. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1814. needRestart = true
  1815. }
  1816. }
  1817. }
  1818. } else {
  1819. nodeID := *oldInbound.NodeID
  1820. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1821. return err
  1822. }
  1823. }
  1824. if err := tx.Save(oldInbound).Error; err != nil {
  1825. return err
  1826. }
  1827. newClients, gcErr := s.GetClients(oldInbound)
  1828. if gcErr != nil {
  1829. return gcErr
  1830. }
  1831. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1832. return err
  1833. }
  1834. if oldInbound.NodeID != nil {
  1835. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1836. return err
  1837. }
  1838. }
  1839. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1840. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1841. // settings.
  1842. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1843. needRestart = true
  1844. }
  1845. return nil
  1846. })
  1847. if txErr != nil {
  1848. return inbound, false, txErr
  1849. }
  1850. if postCommitApply != nil {
  1851. postCommitApply()
  1852. }
  1853. // After the rename is committed, point any routing rules / loopback outbounds
  1854. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1855. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1856. // can't roll back the inbound edit.
  1857. if tag != oldInbound.Tag {
  1858. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1859. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1860. } else if routingChanged {
  1861. needRestart = true
  1862. }
  1863. }
  1864. return inbound, needRestart, nil
  1865. }
  1866. // A node mirrors this payload into its own DB, so every client must survive:
  1867. // filtering one out makes the node delete it, and the master then mirrors that.
  1868. func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1869. if inbound == nil {
  1870. return nil, fmt.Errorf("inbound is nil")
  1871. }
  1872. built := *inbound
  1873. settings := map[string]any{}
  1874. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1875. return nil, err
  1876. }
  1877. if !inboundCanHostFallbacks(inbound) {
  1878. return &built, nil
  1879. }
  1880. fallbacks, err := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  1881. if err != nil {
  1882. return nil, err
  1883. }
  1884. if len(fallbacks) == 0 {
  1885. return &built, nil
  1886. }
  1887. generic := make([]any, 0, len(fallbacks))
  1888. for _, f := range fallbacks {
  1889. generic = append(generic, f)
  1890. }
  1891. settings["fallbacks"] = generic
  1892. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1893. if mErr != nil {
  1894. return nil, mErr
  1895. }
  1896. built.Settings = string(modifiedSettings)
  1897. return &built, nil
  1898. }
  1899. // Strips disabled clients on top of the node payload. Safe only because the
  1900. // target here is an in-memory Xray/mtg config, not another panel's database.
  1901. func (s *InboundService) buildInboundForLocalRuntime(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1902. built, err := s.buildInboundForNodePush(tx, inbound)
  1903. if err != nil {
  1904. return nil, err
  1905. }
  1906. settings := map[string]any{}
  1907. if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil {
  1908. return nil, err
  1909. }
  1910. clients, ok := settings["clients"].([]any)
  1911. if !ok {
  1912. return built, nil
  1913. }
  1914. var clientStats []xray.ClientTraffic
  1915. if err := tx.Model(xray.ClientTraffic{}).
  1916. Where("inbound_id = ?", built.Id).
  1917. Select("email", "enable").
  1918. Find(&clientStats).Error; err != nil {
  1919. return nil, err
  1920. }
  1921. enableMap := make(map[string]bool, len(clientStats))
  1922. for _, clientTraffic := range clientStats {
  1923. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1924. }
  1925. finalClients := make([]any, 0, len(clients))
  1926. for _, client := range clients {
  1927. c, ok := client.(map[string]any)
  1928. if !ok {
  1929. continue
  1930. }
  1931. email, _ := c["email"].(string)
  1932. if enable, exists := enableMap[email]; exists && !enable {
  1933. continue
  1934. }
  1935. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1936. continue
  1937. }
  1938. finalClients = append(finalClients, c)
  1939. }
  1940. settings["clients"] = finalClients
  1941. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1942. if err != nil {
  1943. return nil, err
  1944. }
  1945. runtimeInbound := *built
  1946. runtimeInbound.Settings = string(modifiedSettings)
  1947. return &runtimeInbound, nil
  1948. }
  1949. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1950. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1951. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1952. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1953. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1954. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1955. oldClients, err := s.GetClients(oldInbound)
  1956. if err != nil {
  1957. return err
  1958. }
  1959. newClients, err := s.GetClients(newInbound)
  1960. if err != nil {
  1961. return err
  1962. }
  1963. // Email is the unique key for ClientTraffic rows. Clients without an
  1964. // email have no stats row to sync — skip them on both sides instead of
  1965. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1966. oldEmails := make(map[string]struct{}, len(oldClients))
  1967. for i := range oldClients {
  1968. if oldClients[i].Email == "" {
  1969. continue
  1970. }
  1971. oldEmails[oldClients[i].Email] = struct{}{}
  1972. }
  1973. newEmails := make(map[string]struct{}, len(newClients))
  1974. for i := range newClients {
  1975. if newClients[i].Email == "" {
  1976. continue
  1977. }
  1978. newEmails[newClients[i].Email] = struct{}{}
  1979. }
  1980. // Drop stats rows for removed emails — but not when a sibling inbound
  1981. // still references the email, since the row is the shared accumulator.
  1982. for i := range oldClients {
  1983. email := oldClients[i].Email
  1984. if email == "" {
  1985. continue
  1986. }
  1987. if _, kept := newEmails[email]; kept {
  1988. continue
  1989. }
  1990. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1991. if err != nil {
  1992. return err
  1993. }
  1994. if stillUsed {
  1995. continue
  1996. }
  1997. if err := s.DelClientStat(tx, email); err != nil {
  1998. return err
  1999. }
  2000. // Keep inbound_client_ips in sync when the inbound edit drops an
  2001. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  2002. if err := s.DelClientIPs(tx, email); err != nil {
  2003. return err
  2004. }
  2005. }
  2006. for i := range newClients {
  2007. email := newClients[i].Email
  2008. if email == "" {
  2009. continue
  2010. }
  2011. if _, existed := oldEmails[email]; existed {
  2012. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  2013. return err
  2014. }
  2015. continue
  2016. }
  2017. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  2018. return err
  2019. }
  2020. }
  2021. return nil
  2022. }
  2023. func (s *InboundService) GetInboundTags() (string, error) {
  2024. db := database.GetDB()
  2025. var inboundTags []string
  2026. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2027. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2028. return "", err
  2029. }
  2030. tags, _ := json.Marshal(inboundTags)
  2031. return string(tags), nil
  2032. }
  2033. func (s *InboundService) GetClientReverseTags() (string, error) {
  2034. db := database.GetDB()
  2035. var inbounds []model.Inbound
  2036. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2037. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2038. return "[]", err
  2039. }
  2040. tagSet := make(map[string]struct{})
  2041. for _, inbound := range inbounds {
  2042. var settings map[string]any
  2043. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2044. continue
  2045. }
  2046. clients, ok := settings["clients"].([]any)
  2047. if !ok {
  2048. continue
  2049. }
  2050. for _, client := range clients {
  2051. clientMap, ok := client.(map[string]any)
  2052. if !ok {
  2053. continue
  2054. }
  2055. reverse, ok := clientMap["reverse"].(map[string]any)
  2056. if !ok {
  2057. continue
  2058. }
  2059. tag, _ := reverse["tag"].(string)
  2060. tag = strings.TrimSpace(tag)
  2061. if tag != "" {
  2062. tagSet[tag] = struct{}{}
  2063. }
  2064. }
  2065. }
  2066. rawTags := make([]string, 0, len(tagSet))
  2067. for tag := range tagSet {
  2068. rawTags = append(rawTags, tag)
  2069. }
  2070. sort.Strings(rawTags)
  2071. result, _ := json.Marshal(rawTags)
  2072. return string(result), nil
  2073. }
  2074. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2075. db := database.GetDB()
  2076. var inbounds []*model.Inbound
  2077. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2078. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2079. return nil, err
  2080. }
  2081. return inbounds, nil
  2082. }