inbound.go 76 KB

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