inbound.go 69 KB

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