inbound.go 59 KB

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