inbound.go 48 KB

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