inbound.go 51 KB

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