1
0

inbound.go 58 KB

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