inbound.go 65 KB

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