inbound.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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. settings := map[string][]model.Client{}
  422. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  423. if settings == nil {
  424. return nil, fmt.Errorf("setting is null")
  425. }
  426. clients := settings["clients"]
  427. if clients == nil {
  428. return nil, nil
  429. }
  430. return clients, nil
  431. }
  432. // GetClientsBySubId returns the inbound's clients with the given subscription
  433. // id, resolved from the normalized clients tables (the same source the running
  434. // Xray users are built from) instead of parsing the settings JSON blob.
  435. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  436. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  437. }
  438. func (s *InboundService) GetAllEmails() ([]string, error) {
  439. db := database.GetDB()
  440. var emails []string
  441. query := fmt.Sprintf(
  442. "SELECT DISTINCT %s %s",
  443. database.JSONFieldText("client.value", "email"),
  444. database.JSONClientsFromInbound(),
  445. )
  446. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  447. return nil, err
  448. }
  449. return emails, nil
  450. }
  451. // getAllEmailSubIDs returns email→subId. An email seen with two different
  452. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  453. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  454. db := database.GetDB()
  455. var rows []struct {
  456. Email string
  457. SubID string
  458. }
  459. query := fmt.Sprintf(
  460. "SELECT %s AS email, %s AS sub_id %s",
  461. database.JSONFieldText("client.value", "email"),
  462. database.JSONFieldText("client.value", "subId"),
  463. database.JSONClientsFromInbound(),
  464. )
  465. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  466. return nil, err
  467. }
  468. result := make(map[string]string, len(rows))
  469. for _, r := range rows {
  470. email := strings.ToLower(r.Email)
  471. if email == "" {
  472. continue
  473. }
  474. subID := r.SubID
  475. if existing, ok := result[email]; ok {
  476. if existing != subID {
  477. result[email] = ""
  478. }
  479. continue
  480. }
  481. result[email] = subID
  482. }
  483. return result, nil
  484. }
  485. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  486. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  487. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  488. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  489. // mode).
  490. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  491. protocolsWithStream := map[model.Protocol]bool{
  492. model.VMESS: true,
  493. model.VLESS: true,
  494. model.Trojan: true,
  495. model.Shadowsocks: true,
  496. model.Hysteria: true,
  497. model.WireGuard: true,
  498. model.Tunnel: true,
  499. }
  500. if !protocolsWithStream[inbound.Protocol] {
  501. inbound.StreamSettings = ""
  502. }
  503. }
  504. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  505. // stream uses REALITY security, or nil otherwise. A non-empty result means
  506. // this stream carries the finalmask+REALITY combination that panics
  507. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  508. // wraps the connection before REALITY's handshake ever sees it, and
  509. // reality.Server() does an unchecked type assertion assuming a raw
  510. // *net.TCPConn, which panics once finalmask is in front of it.
  511. //
  512. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  513. // listener ahead of REALITY's handshake, in xray-core's own
  514. // transport/internet/memory_settings.go) is only constructed when tcp masks
  515. // are present; a finalmask.udp-only config never touches the TCP accept path
  516. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  517. // rejected.
  518. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  519. if stream["security"] != "reality" {
  520. return nil
  521. }
  522. finalmask, ok := stream["finalmask"].(map[string]any)
  523. if !ok {
  524. return nil
  525. }
  526. tcp, _ := finalmask["tcp"].([]any)
  527. return tcp
  528. }
  529. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  530. // with REALITY security at save time. Upstream has confirmed this
  531. // combination will be documented as unsupported rather than made graceful,
  532. // so the panel must not let it be saved.
  533. func validateFinalMaskRealityCombo(streamSettings string) error {
  534. if streamSettings == "" {
  535. return nil
  536. }
  537. var stream map[string]any
  538. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  539. return nil
  540. }
  541. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  542. return nil
  543. }
  544. 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.")
  545. }
  546. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  547. // always valid before the row is persisted, and drops the vestigial inbound-level
  548. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  549. // only the per-client values. Leaving an inbound-level secret behind is what
  550. // produced stale links that failed with "incorrect client random".
  551. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  552. if inbound.Protocol != model.MTProto {
  553. return
  554. }
  555. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  556. inbound.Settings = stripped
  557. }
  558. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  559. inbound.Settings = stripped
  560. }
  561. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  562. inbound.Settings = healed
  563. }
  564. }
  565. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  566. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  567. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  568. if inbound == nil || inbound.Protocol != model.MTProto {
  569. return false
  570. }
  571. var parsed struct {
  572. RouteThroughXray bool `json:"routeThroughXray"`
  573. }
  574. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  575. return false
  576. }
  577. return parsed.RouteThroughXray
  578. }
  579. func settingsRouteXrayPort(parsed map[string]any) int {
  580. switch v := parsed["routeXrayPort"].(type) {
  581. case float64:
  582. return int(v)
  583. case int:
  584. return v
  585. case json.Number:
  586. if n, err := v.Int64(); err == nil {
  587. return int(n)
  588. }
  589. }
  590. return 0
  591. }
  592. func parseRouteXrayPort(settings string) int {
  593. if settings == "" {
  594. return 0
  595. }
  596. var parsed map[string]any
  597. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  598. return 0
  599. }
  600. return settingsRouteXrayPort(parsed)
  601. }
  602. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  603. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  604. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  605. // allocated once when routing is first enabled and preserved across edits
  606. // (carried over from oldSettings, which wins over any value the client echoed
  607. // back). When routing is off it — together with the now-inert outbound
  608. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  609. //
  610. // It returns an error when an egress port cannot be allocated or persisted, so
  611. // the caller refuses the save rather than storing a routed-but-portless inbound,
  612. // which would otherwise route no traffic and have its mtg metrics skipped (see
  613. // mtproto_job) — silently losing its accounting.
  614. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  615. if inbound.Protocol != model.MTProto {
  616. return nil
  617. }
  618. var parsed map[string]any
  619. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  620. return nil
  621. }
  622. routed, _ := parsed["routeThroughXray"].(bool)
  623. if !routed {
  624. _, hadPort := parsed["routeXrayPort"]
  625. _, hadTag := parsed["outboundTag"]
  626. if !hadPort && !hadTag {
  627. return nil
  628. }
  629. delete(parsed, "routeXrayPort")
  630. delete(parsed, "outboundTag")
  631. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  632. inbound.Settings = string(bs)
  633. } else {
  634. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  635. }
  636. return nil
  637. }
  638. // Prefer the already-stored port (carried across edits), then any value the
  639. // client sent, then allocate a fresh one.
  640. port := parseRouteXrayPort(oldSettings)
  641. if port <= 0 {
  642. port = settingsRouteXrayPort(parsed)
  643. }
  644. if port <= 0 {
  645. allocated, err := mtproto.FreeLocalPort()
  646. if err != nil {
  647. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  648. }
  649. port = allocated
  650. }
  651. if settingsRouteXrayPort(parsed) == port {
  652. return nil
  653. }
  654. parsed["routeXrayPort"] = port
  655. bs, err := json.MarshalIndent(parsed, "", " ")
  656. if err != nil {
  657. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  658. }
  659. inbound.Settings = string(bs)
  660. return nil
  661. }
  662. // AddInbound creates a new inbound configuration.
  663. // It validates port uniqueness, client email uniqueness, and required fields,
  664. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  665. // Returns the created inbound, whether Xray needs restart, and any error.
  666. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  667. // Normalize streamSettings based on protocol
  668. s.normalizeStreamSettings(inbound)
  669. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  670. return inbound, false, err
  671. }
  672. s.normalizeMtprotoSecret(inbound)
  673. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  674. return inbound, false, err
  675. }
  676. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  677. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  678. return inbound, false, err
  679. }
  680. conflict, err := s.checkPortConflict(inbound, 0)
  681. if err != nil {
  682. return inbound, false, err
  683. }
  684. if conflict != nil {
  685. return inbound, false, common.NewError(conflict.String())
  686. }
  687. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  688. if err != nil {
  689. return inbound, false, err
  690. }
  691. clients, err := s.GetClients(inbound)
  692. if err != nil {
  693. return inbound, false, err
  694. }
  695. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  696. if err != nil {
  697. return inbound, false, err
  698. }
  699. if existEmail != "" {
  700. return inbound, false, common.NewError("Duplicate email:", existEmail)
  701. }
  702. // Ensure created_at and updated_at on clients in settings
  703. if len(clients) > 0 {
  704. var settings map[string]any
  705. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  706. now := time.Now().Unix() * 1000
  707. updatedClients := make([]model.Client, 0, len(clients))
  708. for _, c := range clients {
  709. if c.CreatedAt == 0 {
  710. c.CreatedAt = now
  711. }
  712. c.UpdatedAt = now
  713. updatedClients = append(updatedClients, c)
  714. }
  715. settings["clients"] = updatedClients
  716. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  717. inbound.Settings = string(bs)
  718. } else {
  719. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  720. }
  721. } else if err2 != nil {
  722. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  723. }
  724. }
  725. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  726. // the inbound method (e.g. an API caller supplied a wrong-size key).
  727. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  728. inbound.Settings = normalized
  729. }
  730. // Secure client ID
  731. for _, client := range clients {
  732. switch inbound.Protocol {
  733. case "trojan":
  734. if client.Password == "" {
  735. return inbound, false, common.NewError("empty client ID")
  736. }
  737. case "shadowsocks":
  738. if client.Email == "" {
  739. return inbound, false, common.NewError("empty client ID")
  740. }
  741. case "hysteria":
  742. if client.Auth == "" {
  743. return inbound, false, common.NewError("empty client ID")
  744. }
  745. case "mtproto":
  746. if client.Secret == "" {
  747. return inbound, false, common.NewError("mtproto client requires a secret")
  748. }
  749. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  750. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  751. }
  752. default:
  753. if client.ID == "" {
  754. return inbound, false, common.NewError("empty client ID")
  755. }
  756. }
  757. }
  758. db := database.GetDB()
  759. tx := db.Begin()
  760. markDirty := false
  761. defer func() {
  762. if err != nil {
  763. tx.Rollback()
  764. return
  765. }
  766. if markDirty && inbound.NodeID != nil {
  767. if dErr := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); dErr != nil {
  768. err = dErr
  769. tx.Rollback()
  770. return
  771. }
  772. }
  773. tx.Commit()
  774. }()
  775. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  776. // those rows with an ON CONFLICT target on the primary key only, which
  777. // collides with the globally-unique client_traffics.email when an imported
  778. // inbound carries clients that another inbound already created (e.g.
  779. // importing two inbounds that share the same clients). We insert the stats
  780. // ourselves below with the same email-conflict guard AddClientStat uses.
  781. err = tx.Omit("ClientStats").Save(inbound).Error
  782. if err != nil {
  783. return inbound, false, err
  784. }
  785. // Imported stats first, so their traffic counters survive; emails that
  786. // already own a (shared) row are skipped instead of tripping the unique
  787. // constraint.
  788. for i := range inbound.ClientStats {
  789. if inbound.ClientStats[i].Email == "" {
  790. continue
  791. }
  792. inbound.ClientStats[i].Id = 0
  793. inbound.ClientStats[i].InboundId = inbound.Id
  794. if err = tx.Clauses(clause.OnConflict{
  795. Columns: []clause.Column{{Name: "email"}},
  796. DoNothing: true,
  797. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  798. return inbound, false, err
  799. }
  800. }
  801. // Then make sure every client has a stats row. AddClientStat is a no-op
  802. // where one exists (including the rows just inserted), and fills the gap
  803. // for clients an import payload didn't carry stats for.
  804. for _, client := range clients {
  805. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  806. return inbound, false, err
  807. }
  808. }
  809. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  810. return inbound, false, err
  811. }
  812. // Legacy import: an inbound exported from a build that predated the hosts
  813. // table carries its external proxies inline in streamSettings.externalProxy.
  814. // The startup migration that converts those to host rows runs once and is
  815. // gated off afterwards, so it never sees a freshly imported inbound —
  816. // reproduce it here. No-op for inbounds without externalProxy (everything the
  817. // current UI builds), so this only fires on such imports.
  818. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  819. return inbound, false, err
  820. }
  821. // Before the deferred commit, so a node in "selected" sync mode cannot
  822. // sweep the new central row in the gap before its tag is allowed.
  823. if inbound.NodeID != nil {
  824. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  825. logger.Warning("allow inbound tag on node failed:", aErr)
  826. }
  827. }
  828. needRestart := false
  829. if inbound.Enable {
  830. rt, push, dirty, perr := s.nodePushPlan(inbound)
  831. if perr != nil {
  832. err = perr
  833. return inbound, false, err
  834. }
  835. if dirty {
  836. markDirty = true
  837. }
  838. if push {
  839. payload := inbound
  840. pushable := true
  841. if inbound.NodeID == nil && inbound.Protocol == model.MTProto {
  842. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  843. payload = built
  844. } else {
  845. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  846. pushable = false
  847. }
  848. }
  849. if pushable {
  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. if inbound.NodeID != nil {
  855. markDirty = true
  856. } else if inbound.Protocol != model.MTProto {
  857. needRestart = true
  858. }
  859. }
  860. }
  861. }
  862. }
  863. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  864. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  865. // in the generated config, so force a regen to wire it in.
  866. if mtprotoRoutesThroughXray(inbound) {
  867. needRestart = true
  868. }
  869. return inbound, needRestart, err
  870. }
  871. func (s *InboundService) DelInbound(id int) (bool, error) {
  872. db := database.GetDB()
  873. needRestart := false
  874. markDirty := false
  875. var ib model.Inbound
  876. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  877. if loadErr == nil {
  878. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  879. if shouldPushToRuntime {
  880. rt, push, dirty, perr := s.nodePushPlan(&ib)
  881. if perr != nil {
  882. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  883. markDirty = true
  884. } else if push {
  885. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  886. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  887. } else {
  888. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  889. if ib.NodeID == nil {
  890. needRestart = true
  891. } else {
  892. markDirty = true
  893. }
  894. }
  895. } else if ib.NodeID == nil {
  896. needRestart = true
  897. } else if dirty {
  898. markDirty = true
  899. }
  900. } else {
  901. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  902. }
  903. } else {
  904. logger.Debug("DelInbound: inbound not found, id:", id)
  905. }
  906. if err := s.clientService.DetachInbound(db, id); err != nil {
  907. return false, err
  908. }
  909. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  910. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  911. if loadErr == nil && ib.Tag != "" {
  912. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  913. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  914. } else if routingChanged {
  915. needRestart = true
  916. }
  917. }
  918. if err := db.Transaction(func(tx *gorm.DB) error {
  919. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  920. return err
  921. }
  922. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  923. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  924. return err
  925. }
  926. if markDirty && ib.NodeID != nil {
  927. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  928. }
  929. return nil
  930. }); err != nil {
  931. return needRestart, err
  932. }
  933. if !database.IsPostgres() {
  934. var count int64
  935. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  936. return needRestart, err
  937. }
  938. if count == 0 {
  939. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  940. return needRestart, err
  941. }
  942. }
  943. }
  944. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  945. if mtprotoRoutesThroughXray(&ib) {
  946. needRestart = true
  947. }
  948. return needRestart, nil
  949. }
  950. type BulkDelInboundResult struct {
  951. Deleted int `json:"deleted"`
  952. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  953. }
  954. type BulkDelInboundReport struct {
  955. Id int `json:"id"`
  956. Reason string `json:"reason"`
  957. }
  958. // DelInbounds removes every inbound in the list, reusing the single-delete
  959. // path per id. Failures are recorded in Skipped and processing continues for
  960. // the rest; the aggregated needRestart is returned so the caller restarts
  961. // xray at most once.
  962. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  963. result := BulkDelInboundResult{}
  964. needRestart := false
  965. for _, id := range ids {
  966. r, err := s.DelInbound(id)
  967. if err != nil {
  968. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  969. continue
  970. }
  971. result.Deleted++
  972. if r {
  973. needRestart = true
  974. }
  975. }
  976. return result, needRestart, nil
  977. }
  978. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  979. db := database.GetDB()
  980. inbound := &model.Inbound{}
  981. err := db.Model(model.Inbound{}).First(inbound, id).Error
  982. if err != nil {
  983. return nil, err
  984. }
  985. return inbound, nil
  986. }
  987. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  988. db := database.GetDB()
  989. inbound := &model.Inbound{}
  990. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  991. if err != nil {
  992. return nil, err
  993. }
  994. s.enrichClientStats(db, []*model.Inbound{inbound})
  995. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  996. return inbound, nil
  997. }
  998. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  999. inbound, err := s.GetInbound(id)
  1000. if err != nil {
  1001. return false, err
  1002. }
  1003. if inbound.Enable == enable {
  1004. return false, nil
  1005. }
  1006. db := database.GetDB()
  1007. if err := db.Transaction(func(tx *gorm.DB) error {
  1008. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1009. Update("enable", enable).Error; err != nil {
  1010. return err
  1011. }
  1012. if inbound.NodeID != nil {
  1013. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1014. }
  1015. return nil
  1016. }); err != nil {
  1017. return false, err
  1018. }
  1019. inbound.Enable = enable
  1020. needRestart := false
  1021. rt, push, _, perr := s.nodePushPlan(inbound)
  1022. if perr != nil {
  1023. return false, perr
  1024. }
  1025. // Remote nodes interpret DelInbound as a real row delete (it hits
  1026. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1027. // switch on a remote inbound used to wipe the row entirely (#4402).
  1028. // PATCH the remote row via UpdateInbound instead — preserves the
  1029. // settings/client history and just flips the enable flag.
  1030. if inbound.NodeID != nil {
  1031. if push {
  1032. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1033. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1034. }
  1035. }
  1036. return false, nil
  1037. }
  1038. if !push {
  1039. return true, nil
  1040. }
  1041. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1042. !strings.Contains(err.Error(), "not found") {
  1043. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1044. needRestart = true
  1045. }
  1046. if !enable {
  1047. return needRestart, nil
  1048. }
  1049. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  1050. if err != nil {
  1051. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1052. return true, nil
  1053. }
  1054. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1055. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1056. needRestart = true
  1057. }
  1058. return needRestart, nil
  1059. }
  1060. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1061. // Normalize streamSettings based on protocol
  1062. s.normalizeStreamSettings(inbound)
  1063. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1064. return inbound, false, err
  1065. }
  1066. s.normalizeMtprotoSecret(inbound)
  1067. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1068. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1069. if err != nil {
  1070. return inbound, false, err
  1071. }
  1072. if conflict != nil {
  1073. return inbound, false, common.NewError(conflict.String())
  1074. }
  1075. oldInbound, err := s.GetInbound(inbound.Id)
  1076. if err != nil {
  1077. return inbound, false, err
  1078. }
  1079. inbound.NodeID = oldInbound.NodeID
  1080. // Capture the pre-edit protocol and routing state before oldInbound is
  1081. // overwritten with the new values further down, then ensure a routed
  1082. // inbound keeps a stable egress port (reusing the one already stored).
  1083. oldProtocol := oldInbound.Protocol
  1084. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1085. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1086. return inbound, false, err
  1087. }
  1088. tag := oldInbound.Tag
  1089. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1090. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1091. needRestart := false
  1092. // Persist the client-stat sync, settings munging, runtime push and inbound
  1093. // save as one transaction routed through the serial traffic writer, so it
  1094. // never runs concurrently with the @every 5s traffic poll. Both touch
  1095. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  1096. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  1097. //
  1098. // The runtime push stays inside the transaction here (unlike the client-edit
  1099. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  1100. // node before the central row is committed, or a "selected"-mode node would
  1101. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  1102. // holding the writer across the node call is an acceptable trade.
  1103. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1104. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1105. return err
  1106. }
  1107. // Ensure created_at and updated_at exist in inbound.Settings clients
  1108. {
  1109. var oldSettings map[string]any
  1110. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1111. emailToCreated := map[string]int64{}
  1112. emailToUpdated := map[string]int64{}
  1113. if oldSettings != nil {
  1114. if oc, ok := oldSettings["clients"].([]any); ok {
  1115. for _, it := range oc {
  1116. if m, ok2 := it.(map[string]any); ok2 {
  1117. if email, ok3 := m["email"].(string); ok3 {
  1118. switch v := m["created_at"].(type) {
  1119. case float64:
  1120. emailToCreated[email] = int64(v)
  1121. case int64:
  1122. emailToCreated[email] = v
  1123. }
  1124. switch v := m["updated_at"].(type) {
  1125. case float64:
  1126. emailToUpdated[email] = int64(v)
  1127. case int64:
  1128. emailToUpdated[email] = v
  1129. }
  1130. }
  1131. }
  1132. }
  1133. }
  1134. }
  1135. var newSettings map[string]any
  1136. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1137. now := time.Now().Unix() * 1000
  1138. if nSlice, ok := newSettings["clients"].([]any); ok {
  1139. for i := range nSlice {
  1140. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1141. email, _ := m["email"].(string)
  1142. if _, ok3 := m["created_at"]; !ok3 {
  1143. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1144. m["created_at"] = v
  1145. } else {
  1146. m["created_at"] = now
  1147. }
  1148. }
  1149. // Preserve client's updated_at if present; do not bump on parent inbound update
  1150. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1151. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1152. m["updated_at"] = v
  1153. }
  1154. }
  1155. nSlice[i] = m
  1156. }
  1157. }
  1158. newSettings["clients"] = nSlice
  1159. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1160. inbound.Settings = string(bs)
  1161. }
  1162. }
  1163. }
  1164. }
  1165. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1166. // keep their old length and would be rejected by xray. Regenerate mismatched
  1167. // client keys so the inbound stays connectable.
  1168. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1169. inbound.Settings = normalized
  1170. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1171. }
  1172. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1173. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1174. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1175. // but was stripped while the inbound was ineligible.
  1176. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1177. inbound.Settings = restored
  1178. }
  1179. oldInbound.Total = inbound.Total
  1180. oldInbound.Remark = inbound.Remark
  1181. oldInbound.SubSortIndex = inbound.SubSortIndex
  1182. oldInbound.Enable = inbound.Enable
  1183. oldInbound.ExpiryTime = inbound.ExpiryTime
  1184. oldInbound.TrafficReset = inbound.TrafficReset
  1185. oldInbound.Listen = inbound.Listen
  1186. oldInbound.Port = inbound.Port
  1187. oldInbound.Protocol = inbound.Protocol
  1188. oldInbound.Settings = inbound.Settings
  1189. oldInbound.StreamSettings = inbound.StreamSettings
  1190. oldInbound.Sniffing = inbound.Sniffing
  1191. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1192. normalizeInboundShareAddress(oldInbound)
  1193. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1194. inbound.ShareAddr = oldInbound.ShareAddr
  1195. } else {
  1196. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1197. return err
  1198. }
  1199. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1200. oldInbound.ShareAddr = inbound.ShareAddr
  1201. }
  1202. if oldTagWasAuto && inbound.Tag == tag {
  1203. inbound.Tag = ""
  1204. }
  1205. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1206. if err != nil {
  1207. return err
  1208. }
  1209. oldInbound.Tag = resolvedTag
  1210. inbound.Tag = oldInbound.Tag
  1211. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1212. if perr != nil {
  1213. return perr
  1214. }
  1215. if oldInbound.NodeID == nil {
  1216. if !push {
  1217. needRestart = true
  1218. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1219. oldSnapshot := *oldInbound
  1220. oldSnapshot.Tag = tag
  1221. oldSnapshot.Protocol = oldProtocol
  1222. payload := oldInbound
  1223. pushable := true
  1224. if inbound.Enable {
  1225. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1226. payload = built
  1227. } else {
  1228. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1229. pushable = false
  1230. }
  1231. }
  1232. if pushable {
  1233. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1234. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1235. } else {
  1236. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1237. if oldInbound.Protocol != model.MTProto {
  1238. needRestart = true
  1239. }
  1240. }
  1241. }
  1242. } else {
  1243. oldSnapshot := *oldInbound
  1244. oldSnapshot.Tag = tag
  1245. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1246. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1247. }
  1248. if inbound.Enable {
  1249. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1250. if err2 != nil {
  1251. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1252. needRestart = true
  1253. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1254. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1255. } else {
  1256. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1257. needRestart = true
  1258. }
  1259. }
  1260. }
  1261. } else if push {
  1262. oldSnapshot := *oldInbound
  1263. oldSnapshot.Tag = tag
  1264. if !inbound.Enable {
  1265. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1266. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1267. }
  1268. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1269. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1270. }
  1271. }
  1272. // A rename must allow the new tag before the inbound row is committed, or a
  1273. // node in "selected" sync mode would sweep the renamed central row on the
  1274. // next pull.
  1275. if oldInbound.NodeID != nil {
  1276. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1277. logger.Warning("allow inbound tag on node failed:", aErr)
  1278. }
  1279. }
  1280. if err := tx.Save(oldInbound).Error; err != nil {
  1281. return err
  1282. }
  1283. newClients, gcErr := s.GetClients(oldInbound)
  1284. if gcErr != nil {
  1285. return gcErr
  1286. }
  1287. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1288. return err
  1289. }
  1290. if oldInbound.NodeID != nil {
  1291. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1292. return err
  1293. }
  1294. }
  1295. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1296. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1297. // settings.
  1298. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1299. needRestart = true
  1300. }
  1301. return nil
  1302. })
  1303. if txErr != nil {
  1304. return inbound, false, txErr
  1305. }
  1306. // After the rename is committed, point any routing rules / loopback outbounds
  1307. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1308. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1309. // can't roll back the inbound edit.
  1310. if tag != oldInbound.Tag {
  1311. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1312. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1313. } else if routingChanged {
  1314. needRestart = true
  1315. }
  1316. }
  1317. return inbound, needRestart, nil
  1318. }
  1319. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1320. if inbound == nil {
  1321. return nil, fmt.Errorf("inbound is nil")
  1322. }
  1323. runtimeInbound := *inbound
  1324. settings := map[string]any{}
  1325. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1326. return nil, err
  1327. }
  1328. clients, ok := settings["clients"].([]any)
  1329. if !ok {
  1330. return &runtimeInbound, nil
  1331. }
  1332. var clientStats []xray.ClientTraffic
  1333. err := tx.Model(xray.ClientTraffic{}).
  1334. Where("inbound_id = ?", inbound.Id).
  1335. Select("email", "enable").
  1336. Find(&clientStats).Error
  1337. if err != nil {
  1338. return nil, err
  1339. }
  1340. enableMap := make(map[string]bool, len(clientStats))
  1341. for _, clientTraffic := range clientStats {
  1342. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1343. }
  1344. finalClients := make([]any, 0, len(clients))
  1345. for _, client := range clients {
  1346. c, ok := client.(map[string]any)
  1347. if !ok {
  1348. continue
  1349. }
  1350. email, _ := c["email"].(string)
  1351. if enable, exists := enableMap[email]; exists && !enable {
  1352. continue
  1353. }
  1354. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1355. continue
  1356. }
  1357. finalClients = append(finalClients, c)
  1358. }
  1359. settings["clients"] = finalClients
  1360. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1361. if err != nil {
  1362. return nil, err
  1363. }
  1364. runtimeInbound.Settings = string(modifiedSettings)
  1365. return &runtimeInbound, nil
  1366. }
  1367. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1368. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1369. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1370. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1371. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1372. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1373. oldClients, err := s.GetClients(oldInbound)
  1374. if err != nil {
  1375. return err
  1376. }
  1377. newClients, err := s.GetClients(newInbound)
  1378. if err != nil {
  1379. return err
  1380. }
  1381. // Email is the unique key for ClientTraffic rows. Clients without an
  1382. // email have no stats row to sync — skip them on both sides instead of
  1383. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1384. oldEmails := make(map[string]struct{}, len(oldClients))
  1385. for i := range oldClients {
  1386. if oldClients[i].Email == "" {
  1387. continue
  1388. }
  1389. oldEmails[oldClients[i].Email] = struct{}{}
  1390. }
  1391. newEmails := make(map[string]struct{}, len(newClients))
  1392. for i := range newClients {
  1393. if newClients[i].Email == "" {
  1394. continue
  1395. }
  1396. newEmails[newClients[i].Email] = struct{}{}
  1397. }
  1398. // Drop stats rows for removed emails — but not when a sibling inbound
  1399. // still references the email, since the row is the shared accumulator.
  1400. for i := range oldClients {
  1401. email := oldClients[i].Email
  1402. if email == "" {
  1403. continue
  1404. }
  1405. if _, kept := newEmails[email]; kept {
  1406. continue
  1407. }
  1408. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1409. if err != nil {
  1410. return err
  1411. }
  1412. if stillUsed {
  1413. continue
  1414. }
  1415. if err := s.DelClientStat(tx, email); err != nil {
  1416. return err
  1417. }
  1418. // Keep inbound_client_ips in sync when the inbound edit drops an
  1419. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1420. if err := s.DelClientIPs(tx, email); err != nil {
  1421. return err
  1422. }
  1423. }
  1424. for i := range newClients {
  1425. email := newClients[i].Email
  1426. if email == "" {
  1427. continue
  1428. }
  1429. if _, existed := oldEmails[email]; existed {
  1430. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1431. return err
  1432. }
  1433. continue
  1434. }
  1435. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1436. return err
  1437. }
  1438. }
  1439. return nil
  1440. }
  1441. func (s *InboundService) GetInboundTags() (string, error) {
  1442. db := database.GetDB()
  1443. var inboundTags []string
  1444. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1445. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1446. return "", err
  1447. }
  1448. tags, _ := json.Marshal(inboundTags)
  1449. return string(tags), nil
  1450. }
  1451. func (s *InboundService) GetClientReverseTags() (string, error) {
  1452. db := database.GetDB()
  1453. var inbounds []model.Inbound
  1454. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1455. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1456. return "[]", err
  1457. }
  1458. tagSet := make(map[string]struct{})
  1459. for _, inbound := range inbounds {
  1460. var settings map[string]any
  1461. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1462. continue
  1463. }
  1464. clients, ok := settings["clients"].([]any)
  1465. if !ok {
  1466. continue
  1467. }
  1468. for _, client := range clients {
  1469. clientMap, ok := client.(map[string]any)
  1470. if !ok {
  1471. continue
  1472. }
  1473. reverse, ok := clientMap["reverse"].(map[string]any)
  1474. if !ok {
  1475. continue
  1476. }
  1477. tag, _ := reverse["tag"].(string)
  1478. tag = strings.TrimSpace(tag)
  1479. if tag != "" {
  1480. tagSet[tag] = struct{}{}
  1481. }
  1482. }
  1483. }
  1484. rawTags := make([]string, 0, len(tagSet))
  1485. for tag := range tagSet {
  1486. rawTags = append(rawTags, tag)
  1487. }
  1488. sort.Strings(rawTags)
  1489. result, _ := json.Marshal(rawTags)
  1490. return string(result), nil
  1491. }
  1492. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1493. db := database.GetDB()
  1494. var inbounds []*model.Inbound
  1495. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1496. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1497. return nil, err
  1498. }
  1499. return inbounds, nil
  1500. }