inbound.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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 "mtproto":
  765. if client.Secret == "" {
  766. return inbound, false, common.NewError("mtproto client requires a secret")
  767. }
  768. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  769. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  770. }
  771. default:
  772. if client.ID == "" {
  773. return inbound, false, common.NewError("empty client ID")
  774. }
  775. }
  776. }
  777. db := database.GetDB()
  778. needRestart := false
  779. var postCommitApply func()
  780. err = db.Transaction(func(tx *gorm.DB) error {
  781. markDirty := false
  782. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  783. return err
  784. }
  785. for i := range inbound.ClientStats {
  786. if inbound.ClientStats[i].Email == "" {
  787. continue
  788. }
  789. inbound.ClientStats[i].Id = 0
  790. inbound.ClientStats[i].InboundId = inbound.Id
  791. if err := tx.Clauses(clause.OnConflict{
  792. Columns: []clause.Column{{Name: "email"}},
  793. DoNothing: true,
  794. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  795. return err
  796. }
  797. }
  798. for _, client := range clients {
  799. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  800. return err
  801. }
  802. }
  803. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  804. return err
  805. }
  806. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  807. return err
  808. }
  809. if inbound.NodeID != nil {
  810. nodeID := *inbound.NodeID
  811. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  812. return err
  813. }
  814. }
  815. if inbound.Enable {
  816. if inbound.NodeID != nil {
  817. markDirty = true
  818. } else {
  819. rt, push, _, perr := s.nodePushPlan(inbound)
  820. if perr != nil {
  821. return perr
  822. }
  823. if push {
  824. payload := inbound
  825. pushable := true
  826. if inbound.Protocol == model.MTProto {
  827. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  828. payload = built
  829. } else {
  830. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  831. pushable = false
  832. }
  833. }
  834. if pushable {
  835. postCommitApply = func() {
  836. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  837. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  838. } else {
  839. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  840. needRestart = true
  841. }
  842. }
  843. }
  844. }
  845. }
  846. }
  847. if markDirty && inbound.NodeID != nil {
  848. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  849. }
  850. return nil
  851. })
  852. if err != nil {
  853. return inbound, false, err
  854. }
  855. if postCommitApply != nil {
  856. postCommitApply()
  857. }
  858. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  859. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  860. // in the generated config, so force a regen to wire it in.
  861. if mtprotoRoutesThroughXray(inbound) {
  862. needRestart = true
  863. }
  864. return inbound, needRestart, err
  865. }
  866. func (s *InboundService) DelInbound(id int) (bool, error) {
  867. db := database.GetDB()
  868. needRestart := false
  869. var postCommitApply func()
  870. var ib model.Inbound
  871. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  872. if loadErr == nil {
  873. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  874. if shouldPushToRuntime {
  875. if ib.NodeID != nil {
  876. rt, push, _, perr := s.nodePushPlan(&ib)
  877. if perr != nil {
  878. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  879. } else if push {
  880. postCommitApply = func() {
  881. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  882. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  883. } else {
  884. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  885. }
  886. }
  887. }
  888. } else {
  889. rt, push, _, perr := s.nodePushPlan(&ib)
  890. if perr != nil {
  891. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  892. } else if push {
  893. postCommitApply = func() {
  894. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  895. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  896. } else {
  897. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  898. needRestart = true
  899. }
  900. }
  901. } else {
  902. needRestart = true
  903. }
  904. }
  905. } else {
  906. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  907. }
  908. } else {
  909. logger.Debug("DelInbound: inbound not found, id:", id)
  910. }
  911. if err := db.Transaction(func(tx *gorm.DB) error {
  912. if err := s.clientService.DetachInbound(tx, id); err != nil {
  913. return err
  914. }
  915. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  916. return err
  917. }
  918. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  919. return err
  920. }
  921. if loadErr == nil && ib.NodeID != nil {
  922. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  923. }
  924. return nil
  925. }); err != nil {
  926. return needRestart, err
  927. }
  928. if postCommitApply != nil {
  929. postCommitApply()
  930. }
  931. if loadErr == nil && ib.Tag != "" {
  932. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  933. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  934. } else if routingChanged {
  935. needRestart = true
  936. }
  937. }
  938. if !database.IsPostgres() {
  939. var count int64
  940. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  941. return needRestart, err
  942. }
  943. if count == 0 {
  944. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  945. return needRestart, err
  946. }
  947. }
  948. }
  949. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  950. if mtprotoRoutesThroughXray(&ib) {
  951. needRestart = true
  952. }
  953. return needRestart, nil
  954. }
  955. type BulkDelInboundResult struct {
  956. Deleted int `json:"deleted"`
  957. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  958. }
  959. type BulkDelInboundReport struct {
  960. Id int `json:"id"`
  961. Reason string `json:"reason"`
  962. }
  963. // DelInbounds removes every inbound in the list, reusing the single-delete
  964. // path per id. Failures are recorded in Skipped and processing continues for
  965. // the rest; the aggregated needRestart is returned so the caller restarts
  966. // xray at most once.
  967. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  968. result := BulkDelInboundResult{}
  969. needRestart := false
  970. for _, id := range ids {
  971. r, err := s.DelInbound(id)
  972. if err != nil {
  973. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  974. continue
  975. }
  976. result.Deleted++
  977. if r {
  978. needRestart = true
  979. }
  980. }
  981. return result, needRestart, nil
  982. }
  983. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  984. db := database.GetDB()
  985. inbound := &model.Inbound{}
  986. err := db.Model(model.Inbound{}).First(inbound, id).Error
  987. if err != nil {
  988. return nil, err
  989. }
  990. return inbound, nil
  991. }
  992. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  993. db := database.GetDB()
  994. inbound := &model.Inbound{}
  995. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  996. if err != nil {
  997. return nil, err
  998. }
  999. s.enrichClientStats(db, []*model.Inbound{inbound})
  1000. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1001. return inbound, nil
  1002. }
  1003. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1004. inbound, err := s.GetInbound(id)
  1005. if err != nil {
  1006. return false, err
  1007. }
  1008. if inbound.Enable == enable {
  1009. return false, nil
  1010. }
  1011. db := database.GetDB()
  1012. if err := db.Transaction(func(tx *gorm.DB) error {
  1013. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1014. Update("enable", enable).Error; err != nil {
  1015. return err
  1016. }
  1017. if inbound.NodeID != nil {
  1018. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1019. }
  1020. return nil
  1021. }); err != nil {
  1022. return false, err
  1023. }
  1024. inbound.Enable = enable
  1025. needRestart := false
  1026. rt, push, _, perr := s.nodePushPlan(inbound)
  1027. if perr != nil {
  1028. return false, perr
  1029. }
  1030. // Remote nodes interpret DelInbound as a real row delete (it hits
  1031. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1032. // switch on a remote inbound used to wipe the row entirely (#4402).
  1033. // PATCH the remote row via UpdateInbound instead — preserves the
  1034. // settings/client history and just flips the enable flag.
  1035. if inbound.NodeID != nil {
  1036. if push {
  1037. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1038. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1039. }
  1040. }
  1041. return false, nil
  1042. }
  1043. if !push {
  1044. return true, nil
  1045. }
  1046. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1047. !strings.Contains(err.Error(), "not found") {
  1048. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1049. needRestart = true
  1050. }
  1051. if !enable {
  1052. return needRestart, nil
  1053. }
  1054. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  1055. if err != nil {
  1056. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1057. return true, nil
  1058. }
  1059. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1060. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1061. needRestart = true
  1062. }
  1063. return needRestart, nil
  1064. }
  1065. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1066. // Normalize streamSettings based on protocol
  1067. s.normalizeStreamSettings(inbound)
  1068. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1069. return inbound, false, err
  1070. }
  1071. s.normalizeMtprotoSecret(inbound)
  1072. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1073. oldInbound, err := s.GetInbound(inbound.Id)
  1074. if err != nil {
  1075. return inbound, false, err
  1076. }
  1077. // Restore the stored NodeID before the port-conflict check so a node inbound
  1078. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1079. inbound.NodeID = oldInbound.NodeID
  1080. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1081. if err != nil {
  1082. return inbound, false, err
  1083. }
  1084. if conflict != nil {
  1085. return inbound, false, common.NewError(conflict.String())
  1086. }
  1087. // Capture the pre-edit protocol and routing state before oldInbound is
  1088. // overwritten with the new values further down, then ensure a routed
  1089. // inbound keeps a stable egress port (reusing the one already stored).
  1090. oldProtocol := oldInbound.Protocol
  1091. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1092. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1093. return inbound, false, err
  1094. }
  1095. tag := oldInbound.Tag
  1096. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1097. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1098. needRestart := false
  1099. var postCommitApply func()
  1100. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1101. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1102. return err
  1103. }
  1104. // Ensure created_at and updated_at exist in inbound.Settings clients
  1105. {
  1106. var oldSettings map[string]any
  1107. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1108. emailToCreated := map[string]int64{}
  1109. emailToUpdated := map[string]int64{}
  1110. if oldSettings != nil {
  1111. if oc, ok := oldSettings["clients"].([]any); ok {
  1112. for _, it := range oc {
  1113. if m, ok2 := it.(map[string]any); ok2 {
  1114. if email, ok3 := m["email"].(string); ok3 {
  1115. switch v := m["created_at"].(type) {
  1116. case float64:
  1117. emailToCreated[email] = int64(v)
  1118. case int64:
  1119. emailToCreated[email] = v
  1120. }
  1121. switch v := m["updated_at"].(type) {
  1122. case float64:
  1123. emailToUpdated[email] = int64(v)
  1124. case int64:
  1125. emailToUpdated[email] = v
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. }
  1132. var newSettings map[string]any
  1133. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1134. now := time.Now().Unix() * 1000
  1135. if nSlice, ok := newSettings["clients"].([]any); ok {
  1136. for i := range nSlice {
  1137. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1138. email, _ := m["email"].(string)
  1139. if _, ok3 := m["created_at"]; !ok3 {
  1140. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1141. m["created_at"] = v
  1142. } else {
  1143. m["created_at"] = now
  1144. }
  1145. }
  1146. // Preserve client's updated_at if present; do not bump on parent inbound update
  1147. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1148. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1149. m["updated_at"] = v
  1150. }
  1151. }
  1152. nSlice[i] = m
  1153. }
  1154. }
  1155. newSettings["clients"] = nSlice
  1156. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1157. inbound.Settings = string(bs)
  1158. }
  1159. }
  1160. }
  1161. }
  1162. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1163. // keep their old length and would be rejected by xray. Regenerate mismatched
  1164. // client keys so the inbound stays connectable.
  1165. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1166. inbound.Settings = normalized
  1167. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1168. }
  1169. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1170. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1171. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1172. // but was stripped while the inbound was ineligible.
  1173. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1174. inbound.Settings = restored
  1175. }
  1176. oldInbound.Total = inbound.Total
  1177. oldInbound.Remark = inbound.Remark
  1178. oldInbound.SubSortIndex = inbound.SubSortIndex
  1179. oldInbound.Enable = inbound.Enable
  1180. oldInbound.ExpiryTime = inbound.ExpiryTime
  1181. oldInbound.TrafficReset = inbound.TrafficReset
  1182. oldInbound.Listen = inbound.Listen
  1183. oldInbound.Port = inbound.Port
  1184. oldInbound.Protocol = inbound.Protocol
  1185. oldInbound.Settings = inbound.Settings
  1186. oldInbound.StreamSettings = inbound.StreamSettings
  1187. oldInbound.Sniffing = inbound.Sniffing
  1188. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1189. normalizeInboundShareAddress(oldInbound)
  1190. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1191. inbound.ShareAddr = oldInbound.ShareAddr
  1192. } else {
  1193. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1194. return err
  1195. }
  1196. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1197. oldInbound.ShareAddr = inbound.ShareAddr
  1198. }
  1199. if oldTagWasAuto && inbound.Tag == tag {
  1200. inbound.Tag = ""
  1201. }
  1202. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1203. if err != nil {
  1204. return err
  1205. }
  1206. oldInbound.Tag = resolvedTag
  1207. inbound.Tag = oldInbound.Tag
  1208. if oldInbound.NodeID == nil {
  1209. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1210. if perr != nil {
  1211. return perr
  1212. }
  1213. if !push {
  1214. needRestart = true
  1215. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1216. oldSnapshot := *oldInbound
  1217. oldSnapshot.Tag = tag
  1218. oldSnapshot.Protocol = oldProtocol
  1219. payload := oldInbound
  1220. pushable := true
  1221. if inbound.Enable {
  1222. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1223. payload = built
  1224. } else {
  1225. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1226. pushable = false
  1227. }
  1228. }
  1229. if pushable {
  1230. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1231. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1232. } else {
  1233. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1234. if oldInbound.Protocol != model.MTProto {
  1235. needRestart = true
  1236. }
  1237. }
  1238. }
  1239. } else {
  1240. oldSnapshot := *oldInbound
  1241. oldSnapshot.Tag = tag
  1242. var runtimeInbound *model.Inbound
  1243. if inbound.Enable {
  1244. var err2 error
  1245. runtimeInbound, err2 = s.buildRuntimeInboundForAPI(tx, oldInbound)
  1246. if err2 != nil {
  1247. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1248. needRestart = true
  1249. }
  1250. }
  1251. postCommitApply = func() {
  1252. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1253. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1254. }
  1255. if runtimeInbound == nil {
  1256. return
  1257. }
  1258. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1259. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1260. } else {
  1261. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1262. needRestart = true
  1263. }
  1264. }
  1265. }
  1266. } else {
  1267. nodeID := *oldInbound.NodeID
  1268. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1269. return err
  1270. }
  1271. }
  1272. if err := tx.Save(oldInbound).Error; err != nil {
  1273. return err
  1274. }
  1275. newClients, gcErr := s.GetClients(oldInbound)
  1276. if gcErr != nil {
  1277. return gcErr
  1278. }
  1279. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1280. return err
  1281. }
  1282. if oldInbound.NodeID != nil {
  1283. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1284. return err
  1285. }
  1286. }
  1287. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1288. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1289. // settings.
  1290. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1291. needRestart = true
  1292. }
  1293. return nil
  1294. })
  1295. if txErr != nil {
  1296. return inbound, false, txErr
  1297. }
  1298. if postCommitApply != nil {
  1299. postCommitApply()
  1300. }
  1301. // After the rename is committed, point any routing rules / loopback outbounds
  1302. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1303. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1304. // can't roll back the inbound edit.
  1305. if tag != oldInbound.Tag {
  1306. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1307. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1308. } else if routingChanged {
  1309. needRestart = true
  1310. }
  1311. }
  1312. return inbound, needRestart, nil
  1313. }
  1314. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1315. if inbound == nil {
  1316. return nil, fmt.Errorf("inbound is nil")
  1317. }
  1318. runtimeInbound := *inbound
  1319. settings := map[string]any{}
  1320. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1321. return nil, err
  1322. }
  1323. clients, ok := settings["clients"].([]any)
  1324. if !ok {
  1325. return &runtimeInbound, nil
  1326. }
  1327. var clientStats []xray.ClientTraffic
  1328. err := tx.Model(xray.ClientTraffic{}).
  1329. Where("inbound_id = ?", inbound.Id).
  1330. Select("email", "enable").
  1331. Find(&clientStats).Error
  1332. if err != nil {
  1333. return nil, err
  1334. }
  1335. enableMap := make(map[string]bool, len(clientStats))
  1336. for _, clientTraffic := range clientStats {
  1337. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1338. }
  1339. finalClients := make([]any, 0, len(clients))
  1340. for _, client := range clients {
  1341. c, ok := client.(map[string]any)
  1342. if !ok {
  1343. continue
  1344. }
  1345. email, _ := c["email"].(string)
  1346. if enable, exists := enableMap[email]; exists && !enable {
  1347. continue
  1348. }
  1349. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1350. continue
  1351. }
  1352. finalClients = append(finalClients, c)
  1353. }
  1354. settings["clients"] = finalClients
  1355. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1356. if err != nil {
  1357. return nil, err
  1358. }
  1359. runtimeInbound.Settings = string(modifiedSettings)
  1360. return &runtimeInbound, nil
  1361. }
  1362. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1363. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1364. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1365. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1366. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1367. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1368. oldClients, err := s.GetClients(oldInbound)
  1369. if err != nil {
  1370. return err
  1371. }
  1372. newClients, err := s.GetClients(newInbound)
  1373. if err != nil {
  1374. return err
  1375. }
  1376. // Email is the unique key for ClientTraffic rows. Clients without an
  1377. // email have no stats row to sync — skip them on both sides instead of
  1378. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1379. oldEmails := make(map[string]struct{}, len(oldClients))
  1380. for i := range oldClients {
  1381. if oldClients[i].Email == "" {
  1382. continue
  1383. }
  1384. oldEmails[oldClients[i].Email] = struct{}{}
  1385. }
  1386. newEmails := make(map[string]struct{}, len(newClients))
  1387. for i := range newClients {
  1388. if newClients[i].Email == "" {
  1389. continue
  1390. }
  1391. newEmails[newClients[i].Email] = struct{}{}
  1392. }
  1393. // Drop stats rows for removed emails — but not when a sibling inbound
  1394. // still references the email, since the row is the shared accumulator.
  1395. for i := range oldClients {
  1396. email := oldClients[i].Email
  1397. if email == "" {
  1398. continue
  1399. }
  1400. if _, kept := newEmails[email]; kept {
  1401. continue
  1402. }
  1403. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1404. if err != nil {
  1405. return err
  1406. }
  1407. if stillUsed {
  1408. continue
  1409. }
  1410. if err := s.DelClientStat(tx, email); err != nil {
  1411. return err
  1412. }
  1413. // Keep inbound_client_ips in sync when the inbound edit drops an
  1414. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1415. if err := s.DelClientIPs(tx, email); err != nil {
  1416. return err
  1417. }
  1418. }
  1419. for i := range newClients {
  1420. email := newClients[i].Email
  1421. if email == "" {
  1422. continue
  1423. }
  1424. if _, existed := oldEmails[email]; existed {
  1425. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1426. return err
  1427. }
  1428. continue
  1429. }
  1430. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1431. return err
  1432. }
  1433. }
  1434. return nil
  1435. }
  1436. func (s *InboundService) GetInboundTags() (string, error) {
  1437. db := database.GetDB()
  1438. var inboundTags []string
  1439. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1440. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1441. return "", err
  1442. }
  1443. tags, _ := json.Marshal(inboundTags)
  1444. return string(tags), nil
  1445. }
  1446. func (s *InboundService) GetClientReverseTags() (string, error) {
  1447. db := database.GetDB()
  1448. var inbounds []model.Inbound
  1449. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1450. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1451. return "[]", err
  1452. }
  1453. tagSet := make(map[string]struct{})
  1454. for _, inbound := range inbounds {
  1455. var settings map[string]any
  1456. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1457. continue
  1458. }
  1459. clients, ok := settings["clients"].([]any)
  1460. if !ok {
  1461. continue
  1462. }
  1463. for _, client := range clients {
  1464. clientMap, ok := client.(map[string]any)
  1465. if !ok {
  1466. continue
  1467. }
  1468. reverse, ok := clientMap["reverse"].(map[string]any)
  1469. if !ok {
  1470. continue
  1471. }
  1472. tag, _ := reverse["tag"].(string)
  1473. tag = strings.TrimSpace(tag)
  1474. if tag != "" {
  1475. tagSet[tag] = struct{}{}
  1476. }
  1477. }
  1478. }
  1479. rawTags := make([]string, 0, len(tagSet))
  1480. for tag := range tagSet {
  1481. rawTags = append(rawTags, tag)
  1482. }
  1483. sort.Strings(rawTags)
  1484. result, _ := json.Marshal(rawTags)
  1485. return string(result), nil
  1486. }
  1487. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1488. db := database.GetDB()
  1489. var inbounds []*model.Inbound
  1490. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1491. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1492. return nil, err
  1493. }
  1494. return inbounds, nil
  1495. }