inbound.go 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604
  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. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/database"
  16. "github.com/mhsanaei/3x-ui/v3/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/logger"
  18. "github.com/mhsanaei/3x-ui/v3/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/web/runtime"
  20. "github.com/mhsanaei/3x-ui/v3/xray"
  21. "gorm.io/gorm"
  22. "gorm.io/gorm/clause"
  23. )
  24. var reportedRemoteTagConflict sync.Map
  25. type InboundService struct {
  26. xrayApi xray.XrayAPI
  27. clientService ClientService
  28. fallbackService FallbackService
  29. }
  30. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  31. mgr := runtime.GetManager()
  32. if mgr == nil {
  33. return nil, fmt.Errorf("runtime manager not initialised")
  34. }
  35. return mgr.RuntimeFor(ib.NodeID)
  36. }
  37. type CopyClientsResult struct {
  38. Added []string `json:"added"`
  39. Skipped []string `json:"skipped"`
  40. Errors []string `json:"errors"`
  41. }
  42. // enrichClientStats parses each inbound's clients once, fills in the
  43. // UUID/SubId fields on the preloaded ClientStats, and tops up rows owned by
  44. // a sibling inbound (shared-email mode — the row is keyed on email so it
  45. // only preloads on its owning inbound).
  46. func (s *InboundService) enrichClientStats(db *gorm.DB, inbounds []*model.Inbound) {
  47. if len(inbounds) == 0 {
  48. return
  49. }
  50. clientsByInbound := make([][]model.Client, len(inbounds))
  51. seenByInbound := make([]map[string]struct{}, len(inbounds))
  52. missing := make(map[string]struct{})
  53. for i, inbound := range inbounds {
  54. clients, _ := s.GetClients(inbound)
  55. clientsByInbound[i] = clients
  56. seen := make(map[string]struct{}, len(inbound.ClientStats))
  57. for _, st := range inbound.ClientStats {
  58. if st.Email != "" {
  59. seen[strings.ToLower(st.Email)] = struct{}{}
  60. }
  61. }
  62. seenByInbound[i] = seen
  63. for _, c := range clients {
  64. if c.Email == "" {
  65. continue
  66. }
  67. if _, ok := seen[strings.ToLower(c.Email)]; !ok {
  68. missing[c.Email] = struct{}{}
  69. }
  70. }
  71. }
  72. if len(missing) > 0 {
  73. emails := make([]string, 0, len(missing))
  74. for e := range missing {
  75. emails = append(emails, e)
  76. }
  77. var extra []xray.ClientTraffic
  78. var loadErr error
  79. for _, batch := range chunkStrings(emails, sqlInChunk) {
  80. var page []xray.ClientTraffic
  81. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  82. loadErr = err
  83. break
  84. }
  85. extra = append(extra, page...)
  86. }
  87. if loadErr != nil {
  88. logger.Warning("enrichClientStats:", loadErr)
  89. } else {
  90. byEmail := make(map[string]xray.ClientTraffic, len(extra))
  91. for _, st := range extra {
  92. byEmail[strings.ToLower(st.Email)] = st
  93. }
  94. for i, inbound := range inbounds {
  95. for _, c := range clientsByInbound[i] {
  96. if c.Email == "" {
  97. continue
  98. }
  99. key := strings.ToLower(c.Email)
  100. if _, ok := seenByInbound[i][key]; ok {
  101. continue
  102. }
  103. if st, ok := byEmail[key]; ok {
  104. inbound.ClientStats = append(inbound.ClientStats, st)
  105. seenByInbound[i][key] = struct{}{}
  106. }
  107. }
  108. }
  109. }
  110. }
  111. for i, inbound := range inbounds {
  112. clients := clientsByInbound[i]
  113. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  114. continue
  115. }
  116. cMap := make(map[string]model.Client, len(clients))
  117. for _, c := range clients {
  118. cMap[strings.ToLower(c.Email)] = c
  119. }
  120. for j := range inbound.ClientStats {
  121. email := strings.ToLower(inbound.ClientStats[j].Email)
  122. if c, ok := cMap[email]; ok {
  123. inbound.ClientStats[j].UUID = c.ID
  124. inbound.ClientStats[j].SubId = c.SubID
  125. }
  126. }
  127. }
  128. }
  129. // GetInbounds retrieves all inbounds for a specific user with client stats.
  130. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  131. db := database.GetDB()
  132. var inbounds []*model.Inbound
  133. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  134. if err != nil && err != gorm.ErrRecordNotFound {
  135. return nil, err
  136. }
  137. s.enrichClientStats(db, inbounds)
  138. s.annotateFallbackParents(db, inbounds)
  139. return inbounds, nil
  140. }
  141. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  142. // strips every per-client field other than email / enable / comment from
  143. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  144. // inbounds page only needs those three to roll up client counts and
  145. // render badges, so this trims tens of bytes per client (UUID, password,
  146. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  147. // up fast on installs with thousands of clients.
  148. //
  149. // Full client data is still available through GET /panel/api/inbounds/get/:id
  150. // for the edit/info/qr/export/clone flows that need it.
  151. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  152. db := database.GetDB()
  153. var inbounds []*model.Inbound
  154. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  155. if err != nil && err != gorm.ErrRecordNotFound {
  156. return nil, err
  157. }
  158. s.annotateFallbackParents(db, inbounds)
  159. for _, ib := range inbounds {
  160. ib.Settings = slimSettingsClients(ib.Settings)
  161. }
  162. return inbounds, nil
  163. }
  164. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  165. // keeps only the fields the list view actually reads. Returns the input
  166. // unchanged when the JSON can't be parsed or has no clients array.
  167. func slimSettingsClients(settings string) string {
  168. if settings == "" {
  169. return settings
  170. }
  171. var raw map[string]any
  172. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  173. return settings
  174. }
  175. clients, ok := raw["clients"].([]any)
  176. if !ok || len(clients) == 0 {
  177. return settings
  178. }
  179. slim := make([]any, 0, len(clients))
  180. for _, entry := range clients {
  181. c, ok := entry.(map[string]any)
  182. if !ok {
  183. continue
  184. }
  185. row := make(map[string]any, 3)
  186. if v, ok := c["email"]; ok {
  187. row["email"] = v
  188. }
  189. if v, ok := c["enable"]; ok {
  190. row["enable"] = v
  191. }
  192. if v, ok := c["comment"]; ok && v != "" {
  193. row["comment"] = v
  194. }
  195. slim = append(slim, row)
  196. }
  197. raw["clients"] = slim
  198. out, err := json.Marshal(raw)
  199. if err != nil {
  200. return settings
  201. }
  202. return string(out)
  203. }
  204. // annotateFallbackParents fills FallbackParent on each inbound that is
  205. // the child side of a fallback rule. One DB round-trip serves the full
  206. // list — the frontend needs this to rewrite the child's client-share
  207. // link so it points at the master's reachable endpoint.
  208. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  209. if len(inbounds) == 0 {
  210. return
  211. }
  212. childIds := make([]int, 0, len(inbounds))
  213. for _, ib := range inbounds {
  214. childIds = append(childIds, ib.Id)
  215. }
  216. var rows []model.InboundFallback
  217. if err := db.Where("child_id IN ?", childIds).
  218. Order("sort_order ASC, id ASC").
  219. Find(&rows).Error; err != nil {
  220. return
  221. }
  222. first := make(map[int]model.InboundFallback, len(rows))
  223. for _, r := range rows {
  224. if _, ok := first[r.ChildId]; !ok {
  225. first[r.ChildId] = r
  226. }
  227. }
  228. for _, ib := range inbounds {
  229. if r, ok := first[ib.Id]; ok {
  230. ib.FallbackParent = &model.FallbackParentInfo{
  231. MasterId: r.MasterId,
  232. Path: r.Path,
  233. }
  234. }
  235. }
  236. }
  237. type InboundOption struct {
  238. Id int `json:"id"`
  239. Remark string `json:"remark"`
  240. Tag string `json:"tag"`
  241. Protocol string `json:"protocol"`
  242. Port int `json:"port"`
  243. TlsFlowCapable bool `json:"tlsFlowCapable"`
  244. }
  245. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  246. db := database.GetDB()
  247. var rows []struct {
  248. Id int `gorm:"column:id"`
  249. Remark string `gorm:"column:remark"`
  250. Tag string `gorm:"column:tag"`
  251. Protocol string `gorm:"column:protocol"`
  252. Port int `gorm:"column:port"`
  253. StreamSettings string `gorm:"column:stream_settings"`
  254. }
  255. err := db.Table("inbounds").
  256. Select("id, remark, tag, protocol, port, stream_settings").
  257. Where("user_id = ?", userId).
  258. Order("id ASC").
  259. Scan(&rows).Error
  260. if err != nil && err != gorm.ErrRecordNotFound {
  261. return nil, err
  262. }
  263. out := make([]InboundOption, 0, len(rows))
  264. for _, r := range rows {
  265. out = append(out, InboundOption{
  266. Id: r.Id,
  267. Remark: r.Remark,
  268. Tag: r.Tag,
  269. Protocol: r.Protocol,
  270. Port: r.Port,
  271. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings),
  272. })
  273. }
  274. return out, nil
  275. }
  276. // inboundCanEnableTlsFlow mirrors Inbound.canEnableTlsFlow() from the frontend:
  277. // XTLS Vision is only valid for VLESS on TCP with tls or reality.
  278. func inboundCanEnableTlsFlow(protocol, streamSettings string) bool {
  279. if protocol != string(model.VLESS) {
  280. return false
  281. }
  282. if streamSettings == "" {
  283. return false
  284. }
  285. var stream struct {
  286. Network string `json:"network"`
  287. Security string `json:"security"`
  288. }
  289. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  290. return false
  291. }
  292. if stream.Network != "tcp" {
  293. return false
  294. }
  295. return stream.Security == "tls" || stream.Security == "reality"
  296. }
  297. // inboundCanHostFallbacks gates the settings.fallbacks injection.
  298. // Xray only honors fallbacks on VLESS and Trojan inbounds carried over
  299. // TCP transport with TLS or Reality security.
  300. func inboundCanHostFallbacks(ib *model.Inbound) bool {
  301. if ib == nil {
  302. return false
  303. }
  304. if ib.Protocol != model.VLESS && ib.Protocol != model.Trojan {
  305. return false
  306. }
  307. return inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings) ||
  308. (ib.Protocol == model.Trojan && trojanStreamSupportsFallbacks(ib.StreamSettings))
  309. }
  310. // trojanStreamSupportsFallbacks mirrors the Trojan side of the same gate
  311. // (Trojan reuses XTLS-Vision capable streams: tcp + tls or reality).
  312. func trojanStreamSupportsFallbacks(streamSettings string) bool {
  313. if streamSettings == "" {
  314. return false
  315. }
  316. var stream struct {
  317. Network string `json:"network"`
  318. Security string `json:"security"`
  319. }
  320. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  321. return false
  322. }
  323. if stream.Network != "tcp" {
  324. return false
  325. }
  326. return stream.Security == "tls" || stream.Security == "reality"
  327. }
  328. // GetAllInbounds retrieves all inbounds with client stats.
  329. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  330. db := database.GetDB()
  331. var inbounds []*model.Inbound
  332. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  333. if err != nil && err != gorm.ErrRecordNotFound {
  334. return nil, err
  335. }
  336. s.enrichClientStats(db, inbounds)
  337. return inbounds, nil
  338. }
  339. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  340. db := database.GetDB()
  341. var inbounds []*model.Inbound
  342. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  343. if err != nil && err != gorm.ErrRecordNotFound {
  344. return nil, err
  345. }
  346. return inbounds, nil
  347. }
  348. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  349. settings := map[string][]model.Client{}
  350. json.Unmarshal([]byte(inbound.Settings), &settings)
  351. if settings == nil {
  352. return nil, fmt.Errorf("setting is null")
  353. }
  354. clients := settings["clients"]
  355. if clients == nil {
  356. return nil, nil
  357. }
  358. return clients, nil
  359. }
  360. func (s *InboundService) getAllEmails() ([]string, error) {
  361. db := database.GetDB()
  362. var emails []string
  363. query := fmt.Sprintf(
  364. "SELECT DISTINCT %s %s",
  365. database.JSONFieldText("client.value", "email"),
  366. database.JSONClientsFromInbound(),
  367. )
  368. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  369. return nil, err
  370. }
  371. return emails, nil
  372. }
  373. // getAllEmailSubIDs returns email→subId. An email seen with two different
  374. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  375. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  376. db := database.GetDB()
  377. var rows []struct {
  378. Email string
  379. SubID string
  380. }
  381. query := fmt.Sprintf(
  382. "SELECT %s AS email, %s AS sub_id %s",
  383. database.JSONFieldText("client.value", "email"),
  384. database.JSONFieldText("client.value", "subId"),
  385. database.JSONClientsFromInbound(),
  386. )
  387. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  388. return nil, err
  389. }
  390. result := make(map[string]string, len(rows))
  391. for _, r := range rows {
  392. email := strings.ToLower(r.Email)
  393. if email == "" {
  394. continue
  395. }
  396. subID := r.SubID
  397. if existing, ok := result[email]; ok {
  398. if existing != subID {
  399. result[email] = ""
  400. }
  401. continue
  402. }
  403. result[email] = subID
  404. }
  405. return result, nil
  406. }
  407. // emailUsedByOtherInbounds reports whether email lives in any inbound other
  408. // than exceptInboundId. Empty email returns false.
  409. func (s *InboundService) emailUsedByOtherInbounds(email string, exceptInboundId int) (bool, error) {
  410. if email == "" {
  411. return false, nil
  412. }
  413. db := database.GetDB()
  414. var count int64
  415. query := fmt.Sprintf(
  416. "SELECT COUNT(*) %s WHERE inbounds.id != ? AND LOWER(%s) = LOWER(?)",
  417. database.JSONClientsFromInbound(),
  418. database.JSONFieldText("client.value", "email"),
  419. )
  420. if err := db.Raw(query, exceptInboundId, email).Scan(&count).Error; err != nil {
  421. return false, err
  422. }
  423. return count > 0, nil
  424. }
  425. func (s *InboundService) emailsUsedByOtherInbounds(emails []string, exceptInboundId int) (map[string]bool, error) {
  426. shared := make(map[string]bool, len(emails))
  427. want := make(map[string]struct{}, len(emails))
  428. for _, e := range emails {
  429. e = strings.ToLower(strings.TrimSpace(e))
  430. if e != "" {
  431. want[e] = struct{}{}
  432. }
  433. }
  434. if len(want) == 0 {
  435. return shared, nil
  436. }
  437. db := database.GetDB()
  438. var rows []string
  439. query := fmt.Sprintf(
  440. "SELECT DISTINCT LOWER(%s) %s WHERE inbounds.id != ?",
  441. database.JSONFieldText("client.value", "email"),
  442. database.JSONClientsFromInbound(),
  443. )
  444. if err := db.Raw(query, exceptInboundId).Scan(&rows).Error; err != nil {
  445. return nil, err
  446. }
  447. for _, e := range rows {
  448. e = strings.ToLower(strings.TrimSpace(e))
  449. if _, ok := want[e]; ok {
  450. shared[e] = true
  451. }
  452. }
  453. return shared, nil
  454. }
  455. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  456. // Only vmess, vless, trojan, shadowsocks, and hysteria protocols use streamSettings.
  457. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  458. protocolsWithStream := map[model.Protocol]bool{
  459. model.VMESS: true,
  460. model.VLESS: true,
  461. model.Trojan: true,
  462. model.Shadowsocks: true,
  463. model.Hysteria: true,
  464. }
  465. if !protocolsWithStream[inbound.Protocol] {
  466. inbound.StreamSettings = ""
  467. }
  468. }
  469. // AddInbound creates a new inbound configuration.
  470. // It validates port uniqueness, client email uniqueness, and required fields,
  471. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  472. // Returns the created inbound, whether Xray needs restart, and any error.
  473. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  474. // Normalize streamSettings based on protocol
  475. s.normalizeStreamSettings(inbound)
  476. conflict, err := s.checkPortConflict(inbound, 0)
  477. if err != nil {
  478. return inbound, false, err
  479. }
  480. if conflict != nil {
  481. return inbound, false, common.NewError(conflict.String())
  482. }
  483. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  484. if err != nil {
  485. return inbound, false, err
  486. }
  487. clients, err := s.GetClients(inbound)
  488. if err != nil {
  489. return inbound, false, err
  490. }
  491. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  492. if err != nil {
  493. return inbound, false, err
  494. }
  495. if existEmail != "" {
  496. return inbound, false, common.NewError("Duplicate email:", existEmail)
  497. }
  498. // Ensure created_at and updated_at on clients in settings
  499. if len(clients) > 0 {
  500. var settings map[string]any
  501. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  502. now := time.Now().Unix() * 1000
  503. updatedClients := make([]model.Client, 0, len(clients))
  504. for _, c := range clients {
  505. if c.CreatedAt == 0 {
  506. c.CreatedAt = now
  507. }
  508. c.UpdatedAt = now
  509. updatedClients = append(updatedClients, c)
  510. }
  511. settings["clients"] = updatedClients
  512. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  513. inbound.Settings = string(bs)
  514. } else {
  515. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  516. }
  517. } else if err2 != nil {
  518. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  519. }
  520. }
  521. // Secure client ID
  522. for _, client := range clients {
  523. switch inbound.Protocol {
  524. case "trojan":
  525. if client.Password == "" {
  526. return inbound, false, common.NewError("empty client ID")
  527. }
  528. case "shadowsocks":
  529. if client.Email == "" {
  530. return inbound, false, common.NewError("empty client ID")
  531. }
  532. case "hysteria":
  533. if client.Auth == "" {
  534. return inbound, false, common.NewError("empty client ID")
  535. }
  536. default:
  537. if client.ID == "" {
  538. return inbound, false, common.NewError("empty client ID")
  539. }
  540. }
  541. }
  542. db := database.GetDB()
  543. tx := db.Begin()
  544. defer func() {
  545. if err == nil {
  546. tx.Commit()
  547. } else {
  548. tx.Rollback()
  549. }
  550. }()
  551. err = tx.Save(inbound).Error
  552. if err == nil {
  553. if len(inbound.ClientStats) == 0 {
  554. for _, client := range clients {
  555. s.AddClientStat(tx, inbound.Id, &client)
  556. }
  557. }
  558. } else {
  559. return inbound, false, err
  560. }
  561. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  562. return inbound, false, err
  563. }
  564. needRestart := false
  565. if inbound.Enable {
  566. rt, rterr := s.runtimeFor(inbound)
  567. if rterr != nil {
  568. err = rterr
  569. return inbound, false, err
  570. }
  571. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  572. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  573. } else {
  574. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  575. if inbound.NodeID != nil {
  576. err = err1
  577. return inbound, false, err
  578. }
  579. needRestart = true
  580. }
  581. }
  582. return inbound, needRestart, err
  583. }
  584. func (s *InboundService) DelInbound(id int) (bool, error) {
  585. db := database.GetDB()
  586. needRestart := false
  587. var ib model.Inbound
  588. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  589. if loadErr == nil {
  590. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  591. if shouldPushToRuntime {
  592. rt, rterr := s.runtimeFor(&ib)
  593. if rterr != nil {
  594. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
  595. if ib.NodeID == nil {
  596. needRestart = true
  597. }
  598. } else if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  599. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  600. } else {
  601. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  602. if ib.NodeID == nil {
  603. needRestart = true
  604. }
  605. }
  606. } else {
  607. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  608. }
  609. } else {
  610. logger.Debug("DelInbound: inbound not found, id:", id)
  611. }
  612. if err := s.clientService.DetachInbound(db, id); err != nil {
  613. return false, err
  614. }
  615. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  616. return needRestart, err
  617. }
  618. if !database.IsPostgres() {
  619. var count int64
  620. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  621. return needRestart, err
  622. }
  623. if count == 0 {
  624. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  625. return needRestart, err
  626. }
  627. }
  628. }
  629. return needRestart, nil
  630. }
  631. type BulkDelInboundResult struct {
  632. Deleted int `json:"deleted"`
  633. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  634. }
  635. type BulkDelInboundReport struct {
  636. Id int `json:"id"`
  637. Reason string `json:"reason"`
  638. }
  639. // DelInbounds removes every inbound in the list, reusing the single-delete
  640. // path per id. Failures are recorded in Skipped and processing continues for
  641. // the rest; the aggregated needRestart is returned so the caller restarts
  642. // xray at most once.
  643. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  644. result := BulkDelInboundResult{}
  645. needRestart := false
  646. for _, id := range ids {
  647. r, err := s.DelInbound(id)
  648. if err != nil {
  649. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  650. continue
  651. }
  652. result.Deleted++
  653. if r {
  654. needRestart = true
  655. }
  656. }
  657. return result, needRestart, nil
  658. }
  659. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  660. db := database.GetDB()
  661. inbound := &model.Inbound{}
  662. err := db.Model(model.Inbound{}).First(inbound, id).Error
  663. if err != nil {
  664. return nil, err
  665. }
  666. return inbound, nil
  667. }
  668. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  669. db := database.GetDB()
  670. inbound := &model.Inbound{}
  671. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  672. if err != nil {
  673. return nil, err
  674. }
  675. s.enrichClientStats(db, []*model.Inbound{inbound})
  676. return inbound, nil
  677. }
  678. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  679. inbound, err := s.GetInbound(id)
  680. if err != nil {
  681. return false, err
  682. }
  683. if inbound.Enable == enable {
  684. return false, nil
  685. }
  686. db := database.GetDB()
  687. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  688. Update("enable", enable).Error; err != nil {
  689. return false, err
  690. }
  691. inbound.Enable = enable
  692. needRestart := false
  693. rt, rterr := s.runtimeFor(inbound)
  694. if rterr != nil {
  695. if inbound.NodeID != nil {
  696. return false, rterr
  697. }
  698. return true, nil
  699. }
  700. // Remote nodes interpret DelInbound as a real row delete (it hits
  701. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  702. // switch on a remote inbound used to wipe the row entirely (#4402).
  703. // PATCH the remote row via UpdateInbound instead — preserves the
  704. // settings/client history and just flips the enable flag.
  705. if inbound.NodeID != nil {
  706. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  707. logger.Debug("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  708. return false, err
  709. }
  710. return false, nil
  711. }
  712. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  713. !strings.Contains(err.Error(), "not found") {
  714. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  715. needRestart = true
  716. }
  717. if !enable {
  718. return needRestart, nil
  719. }
  720. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  721. if err != nil {
  722. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  723. return true, nil
  724. }
  725. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  726. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  727. needRestart = true
  728. }
  729. return needRestart, nil
  730. }
  731. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  732. // Normalize streamSettings based on protocol
  733. s.normalizeStreamSettings(inbound)
  734. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  735. if err != nil {
  736. return inbound, false, err
  737. }
  738. if conflict != nil {
  739. return inbound, false, common.NewError(conflict.String())
  740. }
  741. oldInbound, err := s.GetInbound(inbound.Id)
  742. if err != nil {
  743. return inbound, false, err
  744. }
  745. inbound.NodeID = oldInbound.NodeID
  746. tag := oldInbound.Tag
  747. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  748. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  749. db := database.GetDB()
  750. tx := db.Begin()
  751. defer func() {
  752. if err != nil {
  753. tx.Rollback()
  754. } else {
  755. tx.Commit()
  756. }
  757. }()
  758. err = s.updateClientTraffics(tx, oldInbound, inbound)
  759. if err != nil {
  760. return inbound, false, err
  761. }
  762. // Ensure created_at and updated_at exist in inbound.Settings clients
  763. {
  764. var oldSettings map[string]any
  765. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  766. emailToCreated := map[string]int64{}
  767. emailToUpdated := map[string]int64{}
  768. if oldSettings != nil {
  769. if oc, ok := oldSettings["clients"].([]any); ok {
  770. for _, it := range oc {
  771. if m, ok2 := it.(map[string]any); ok2 {
  772. if email, ok3 := m["email"].(string); ok3 {
  773. switch v := m["created_at"].(type) {
  774. case float64:
  775. emailToCreated[email] = int64(v)
  776. case int64:
  777. emailToCreated[email] = v
  778. }
  779. switch v := m["updated_at"].(type) {
  780. case float64:
  781. emailToUpdated[email] = int64(v)
  782. case int64:
  783. emailToUpdated[email] = v
  784. }
  785. }
  786. }
  787. }
  788. }
  789. }
  790. var newSettings map[string]any
  791. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  792. now := time.Now().Unix() * 1000
  793. if nSlice, ok := newSettings["clients"].([]any); ok {
  794. for i := range nSlice {
  795. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  796. email, _ := m["email"].(string)
  797. if _, ok3 := m["created_at"]; !ok3 {
  798. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  799. m["created_at"] = v
  800. } else {
  801. m["created_at"] = now
  802. }
  803. }
  804. // Preserve client's updated_at if present; do not bump on parent inbound update
  805. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  806. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  807. m["updated_at"] = v
  808. }
  809. }
  810. nSlice[i] = m
  811. }
  812. }
  813. newSettings["clients"] = nSlice
  814. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  815. inbound.Settings = string(bs)
  816. }
  817. }
  818. }
  819. }
  820. oldInbound.Total = inbound.Total
  821. oldInbound.Remark = inbound.Remark
  822. oldInbound.Enable = inbound.Enable
  823. oldInbound.ExpiryTime = inbound.ExpiryTime
  824. oldInbound.TrafficReset = inbound.TrafficReset
  825. oldInbound.Listen = inbound.Listen
  826. oldInbound.Port = inbound.Port
  827. oldInbound.Protocol = inbound.Protocol
  828. oldInbound.Settings = inbound.Settings
  829. oldInbound.StreamSettings = inbound.StreamSettings
  830. oldInbound.Sniffing = inbound.Sniffing
  831. if oldTagWasAuto && inbound.Tag == tag {
  832. inbound.Tag = ""
  833. }
  834. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  835. if err != nil {
  836. return inbound, false, err
  837. }
  838. inbound.Tag = oldInbound.Tag
  839. needRestart := false
  840. rt, rterr := s.runtimeFor(oldInbound)
  841. if rterr != nil {
  842. if oldInbound.NodeID != nil {
  843. err = rterr
  844. return inbound, false, err
  845. }
  846. needRestart = true
  847. } else {
  848. oldSnapshot := *oldInbound
  849. oldSnapshot.Tag = tag
  850. if oldInbound.NodeID == nil {
  851. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  852. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  853. }
  854. if inbound.Enable {
  855. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  856. if err2 != nil {
  857. logger.Debug("Unable to prepare runtime inbound config:", err2)
  858. needRestart = true
  859. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  860. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  861. } else {
  862. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  863. needRestart = true
  864. }
  865. }
  866. } else {
  867. if !inbound.Enable {
  868. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  869. err = err2
  870. return inbound, false, err
  871. }
  872. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  873. err = err2
  874. return inbound, false, err
  875. }
  876. }
  877. }
  878. if err = tx.Save(oldInbound).Error; err != nil {
  879. return inbound, false, err
  880. }
  881. newClients, gcErr := s.GetClients(oldInbound)
  882. if gcErr != nil {
  883. err = gcErr
  884. return inbound, false, err
  885. }
  886. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  887. return inbound, false, err
  888. }
  889. return inbound, needRestart, nil
  890. }
  891. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  892. if inbound == nil {
  893. return nil, fmt.Errorf("inbound is nil")
  894. }
  895. runtimeInbound := *inbound
  896. settings := map[string]any{}
  897. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  898. return nil, err
  899. }
  900. clients, ok := settings["clients"].([]any)
  901. if !ok {
  902. return &runtimeInbound, nil
  903. }
  904. var clientStats []xray.ClientTraffic
  905. err := tx.Model(xray.ClientTraffic{}).
  906. Where("inbound_id = ?", inbound.Id).
  907. Select("email", "enable").
  908. Find(&clientStats).Error
  909. if err != nil {
  910. return nil, err
  911. }
  912. enableMap := make(map[string]bool, len(clientStats))
  913. for _, clientTraffic := range clientStats {
  914. enableMap[clientTraffic.Email] = clientTraffic.Enable
  915. }
  916. finalClients := make([]any, 0, len(clients))
  917. for _, client := range clients {
  918. c, ok := client.(map[string]any)
  919. if !ok {
  920. continue
  921. }
  922. email, _ := c["email"].(string)
  923. if enable, exists := enableMap[email]; exists && !enable {
  924. continue
  925. }
  926. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  927. continue
  928. }
  929. finalClients = append(finalClients, c)
  930. }
  931. settings["clients"] = finalClients
  932. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  933. if err != nil {
  934. return nil, err
  935. }
  936. runtimeInbound.Settings = string(modifiedSettings)
  937. return &runtimeInbound, nil
  938. }
  939. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  940. // list: removes rows for emails that disappeared, inserts rows for newly-added
  941. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  942. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  943. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  944. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  945. oldClients, err := s.GetClients(oldInbound)
  946. if err != nil {
  947. return err
  948. }
  949. newClients, err := s.GetClients(newInbound)
  950. if err != nil {
  951. return err
  952. }
  953. // Email is the unique key for ClientTraffic rows. Clients without an
  954. // email have no stats row to sync — skip them on both sides instead of
  955. // risking a unique-constraint hit or accidental delete of an unrelated row.
  956. oldEmails := make(map[string]struct{}, len(oldClients))
  957. for i := range oldClients {
  958. if oldClients[i].Email == "" {
  959. continue
  960. }
  961. oldEmails[oldClients[i].Email] = struct{}{}
  962. }
  963. newEmails := make(map[string]struct{}, len(newClients))
  964. for i := range newClients {
  965. if newClients[i].Email == "" {
  966. continue
  967. }
  968. newEmails[newClients[i].Email] = struct{}{}
  969. }
  970. // Drop stats rows for removed emails — but not when a sibling inbound
  971. // still references the email, since the row is the shared accumulator.
  972. for i := range oldClients {
  973. email := oldClients[i].Email
  974. if email == "" {
  975. continue
  976. }
  977. if _, kept := newEmails[email]; kept {
  978. continue
  979. }
  980. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  981. if err != nil {
  982. return err
  983. }
  984. if stillUsed {
  985. continue
  986. }
  987. if err := s.DelClientStat(tx, email); err != nil {
  988. return err
  989. }
  990. }
  991. for i := range newClients {
  992. email := newClients[i].Email
  993. if email == "" {
  994. continue
  995. }
  996. if _, existed := oldEmails[email]; existed {
  997. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  998. return err
  999. }
  1000. continue
  1001. }
  1002. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1003. return err
  1004. }
  1005. }
  1006. return nil
  1007. }
  1008. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  1009. switch protocol {
  1010. case model.Trojan:
  1011. return client.Password
  1012. case model.Shadowsocks:
  1013. return client.Email
  1014. case model.Hysteria:
  1015. return client.Auth
  1016. default:
  1017. return client.ID
  1018. }
  1019. }
  1020. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  1021. client.SubID = subID
  1022. client.UpdatedAt = time.Now().UnixMilli()
  1023. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  1024. if clientID == "" {
  1025. return false, common.NewError("empty client ID")
  1026. }
  1027. settingsBytes, err := json.Marshal(map[string][]model.Client{
  1028. "clients": {client},
  1029. })
  1030. if err != nil {
  1031. return false, err
  1032. }
  1033. updatePayload := &model.Inbound{
  1034. Id: sourceInboundID,
  1035. Settings: string(settingsBytes),
  1036. }
  1037. return s.clientService.UpdateInboundClient(s, updatePayload, clientID)
  1038. }
  1039. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  1040. switch targetProtocol {
  1041. case model.VMESS, model.VLESS:
  1042. return uuid.NewString()
  1043. default:
  1044. return strings.ReplaceAll(uuid.NewString(), "-", "")
  1045. }
  1046. }
  1047. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetInbound *model.Inbound, email string, flow string) (model.Client, error) {
  1048. nowTs := time.Now().UnixMilli()
  1049. target := source
  1050. target.Email = email
  1051. target.CreatedAt = nowTs
  1052. target.UpdatedAt = nowTs
  1053. target.ID = ""
  1054. target.Password = ""
  1055. target.Auth = ""
  1056. target.Flow = ""
  1057. targetProtocol := targetInbound.Protocol
  1058. switch targetProtocol {
  1059. case model.VMESS:
  1060. target.ID = s.generateRandomCredential(targetProtocol)
  1061. case model.VLESS:
  1062. target.ID = s.generateRandomCredential(targetProtocol)
  1063. if (flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443") &&
  1064. inboundCanEnableTlsFlow(string(targetProtocol), targetInbound.StreamSettings) {
  1065. target.Flow = flow
  1066. }
  1067. case model.Trojan, model.Shadowsocks:
  1068. target.Password = s.generateRandomCredential(targetProtocol)
  1069. case model.Hysteria:
  1070. target.Auth = s.generateRandomCredential(targetProtocol)
  1071. default:
  1072. target.ID = s.generateRandomCredential(targetProtocol)
  1073. }
  1074. return target, nil
  1075. }
  1076. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  1077. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  1078. candidate := base
  1079. suffix := 0
  1080. for {
  1081. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  1082. occupied[strings.ToLower(candidate)] = struct{}{}
  1083. return candidate
  1084. }
  1085. suffix++
  1086. candidate = fmt.Sprintf("%s_%d", base, suffix)
  1087. }
  1088. }
  1089. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  1090. result := &CopyClientsResult{
  1091. Added: []string{},
  1092. Skipped: []string{},
  1093. Errors: []string{},
  1094. }
  1095. if targetInboundID == sourceInboundID {
  1096. return result, false, common.NewError("source and target inbounds must be different")
  1097. }
  1098. targetInbound, err := s.GetInbound(targetInboundID)
  1099. if err != nil {
  1100. return result, false, err
  1101. }
  1102. sourceInbound, err := s.GetInbound(sourceInboundID)
  1103. if err != nil {
  1104. return result, false, err
  1105. }
  1106. sourceClients, err := s.GetClients(sourceInbound)
  1107. if err != nil {
  1108. return result, false, err
  1109. }
  1110. if len(sourceClients) == 0 {
  1111. return result, false, nil
  1112. }
  1113. allowedEmails := map[string]struct{}{}
  1114. if len(clientEmails) > 0 {
  1115. for _, email := range clientEmails {
  1116. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1117. }
  1118. }
  1119. occupiedEmails := map[string]struct{}{}
  1120. allEmails, err := s.getAllEmails()
  1121. if err != nil {
  1122. return result, false, err
  1123. }
  1124. for _, email := range allEmails {
  1125. clean := strings.Trim(email, "\"")
  1126. if clean != "" {
  1127. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1128. }
  1129. }
  1130. newClients := make([]model.Client, 0)
  1131. needRestart := false
  1132. for _, sourceClient := range sourceClients {
  1133. originalEmail := strings.TrimSpace(sourceClient.Email)
  1134. if originalEmail == "" {
  1135. continue
  1136. }
  1137. if len(allowedEmails) > 0 {
  1138. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1139. continue
  1140. }
  1141. }
  1142. if sourceClient.SubID == "" {
  1143. newSubID := uuid.NewString()
  1144. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1145. if subErr != nil {
  1146. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1147. continue
  1148. }
  1149. if subNeedRestart {
  1150. needRestart = true
  1151. }
  1152. sourceClient.SubID = newSubID
  1153. }
  1154. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1155. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound, targetEmail, flow)
  1156. if buildErr != nil {
  1157. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1158. continue
  1159. }
  1160. newClients = append(newClients, targetClient)
  1161. result.Added = append(result.Added, targetEmail)
  1162. }
  1163. if len(newClients) == 0 {
  1164. return result, needRestart, nil
  1165. }
  1166. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1167. "clients": newClients,
  1168. })
  1169. if err != nil {
  1170. return result, needRestart, err
  1171. }
  1172. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  1173. Id: targetInboundID,
  1174. Settings: string(settingsPayload),
  1175. })
  1176. if err != nil {
  1177. return result, needRestart, err
  1178. }
  1179. if addNeedRestart {
  1180. needRestart = true
  1181. }
  1182. return result, needRestart, nil
  1183. }
  1184. const resetGracePeriodMs int64 = 30000
  1185. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  1186. // Xray's stats counters often report a zero delta for an active session across
  1187. // a single poll, so a 5s grace would still drop the client on the next tick.
  1188. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  1189. // long after a real disconnect.
  1190. const onlineGracePeriodMs int64 = 20000
  1191. type nodeTrafficCounter struct {
  1192. Up int64
  1193. Down int64
  1194. }
  1195. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  1196. return tx.Clauses(clause.OnConflict{
  1197. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  1198. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  1199. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  1200. }
  1201. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1202. var structuralChange bool
  1203. err := submitTrafficWrite(func() error {
  1204. var inner error
  1205. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
  1206. return inner
  1207. })
  1208. return structuralChange, err
  1209. }
  1210. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1211. if snap == nil || nodeID <= 0 {
  1212. return false, nil
  1213. }
  1214. db := database.GetDB()
  1215. now := time.Now().UnixMilli()
  1216. var central []model.Inbound
  1217. if err := db.Model(model.Inbound{}).
  1218. Where("node_id = ?", nodeID).
  1219. Find(&central).Error; err != nil {
  1220. return false, err
  1221. }
  1222. // Index under the stored tag and its prefix-flipped form so a snap matches
  1223. // whether the n<id>- prefix lives on the node side, the central side, or
  1224. // neither — a mismatch must never spawn a duplicate central inbound.
  1225. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  1226. prefix := nodeTagPrefix(&nodeID)
  1227. for i := range central {
  1228. tagToCentral[central[i].Tag] = &central[i]
  1229. if prefix != "" {
  1230. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  1231. tagToCentral[stripped] = &central[i]
  1232. } else {
  1233. tagToCentral[prefix+central[i].Tag] = &central[i]
  1234. }
  1235. }
  1236. }
  1237. var centralClientStats []xray.ClientTraffic
  1238. if len(central) > 0 {
  1239. ids := make([]int, 0, len(central))
  1240. for i := range central {
  1241. ids = append(ids, central[i].Id)
  1242. }
  1243. if err := db.Model(xray.ClientTraffic{}).
  1244. Where("inbound_id IN ?", ids).
  1245. Find(&centralClientStats).Error; err != nil {
  1246. return false, err
  1247. }
  1248. }
  1249. type csKey struct {
  1250. inboundID int
  1251. email string
  1252. }
  1253. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1254. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  1255. for i := range centralClientStats {
  1256. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1257. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  1258. }
  1259. nodeBaselines := make(map[string]nodeTrafficCounter)
  1260. var baselineRows []model.NodeClientTraffic
  1261. if err := db.Model(&model.NodeClientTraffic{}).
  1262. Where("node_id = ?", nodeID).
  1263. Find(&baselineRows).Error; err != nil {
  1264. return false, err
  1265. }
  1266. for i := range baselineRows {
  1267. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  1268. }
  1269. var existingEmailsList []string
  1270. if err := db.Model(xray.ClientTraffic{}).Pluck("email", &existingEmailsList).Error; err != nil {
  1271. return false, err
  1272. }
  1273. existingEmails := make(map[string]struct{}, len(existingEmailsList))
  1274. for _, e := range existingEmailsList {
  1275. existingEmails[e] = struct{}{}
  1276. }
  1277. var defaultUserId int
  1278. if len(central) > 0 {
  1279. defaultUserId = central[0].UserId
  1280. } else {
  1281. var u model.User
  1282. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1283. defaultUserId = u.Id
  1284. } else {
  1285. defaultUserId = 1
  1286. }
  1287. }
  1288. tx := db.Begin()
  1289. committed := false
  1290. defer func() {
  1291. if !committed {
  1292. tx.Rollback()
  1293. }
  1294. }()
  1295. structuralChange := false
  1296. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1297. for _, snapIb := range snap.Inbounds {
  1298. if snapIb == nil {
  1299. continue
  1300. }
  1301. snapTags[snapIb.Tag] = struct{}{}
  1302. // Record the prefix-flipped form too so the orphan sweep below keeps a
  1303. // central inbound whether its tag carries the n<id>- prefix or not.
  1304. if prefix != "" {
  1305. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  1306. snapTags[stripped] = struct{}{}
  1307. } else {
  1308. snapTags[prefix+snapIb.Tag] = struct{}{}
  1309. }
  1310. }
  1311. c, ok := tagToCentral[snapIb.Tag]
  1312. if !ok {
  1313. // Try snap.Tag first; on collision fall back to the n<id>-
  1314. // prefixed form so local+node can both own the same port.
  1315. pickFreeTag := func() (string, error) {
  1316. candidates := []string{snapIb.Tag}
  1317. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  1318. candidates = append(candidates, prefix+snapIb.Tag)
  1319. }
  1320. for _, t := range candidates {
  1321. var owner model.Inbound
  1322. err := tx.Where("tag = ?", t).First(&owner).Error
  1323. if errors.Is(err, gorm.ErrRecordNotFound) {
  1324. return t, nil
  1325. }
  1326. if err != nil {
  1327. return "", err
  1328. }
  1329. }
  1330. return "", nil
  1331. }
  1332. chosenTag, err := pickFreeTag()
  1333. if err != nil {
  1334. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  1335. continue
  1336. }
  1337. if chosenTag == "" {
  1338. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  1339. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  1340. logger.Warningf(
  1341. "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)",
  1342. snapIb.Tag, nodeID, nodeID,
  1343. )
  1344. }
  1345. continue
  1346. }
  1347. newIb := model.Inbound{
  1348. UserId: defaultUserId,
  1349. NodeID: &nodeID,
  1350. Tag: chosenTag,
  1351. Listen: snapIb.Listen,
  1352. Port: snapIb.Port,
  1353. Protocol: snapIb.Protocol,
  1354. Settings: snapIb.Settings,
  1355. StreamSettings: snapIb.StreamSettings,
  1356. Sniffing: snapIb.Sniffing,
  1357. TrafficReset: snapIb.TrafficReset,
  1358. Enable: snapIb.Enable,
  1359. Remark: snapIb.Remark,
  1360. Total: snapIb.Total,
  1361. ExpiryTime: snapIb.ExpiryTime,
  1362. Up: snapIb.Up,
  1363. Down: snapIb.Down,
  1364. }
  1365. if err := tx.Create(&newIb).Error; err != nil {
  1366. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  1367. continue
  1368. }
  1369. tagToCentral[snapIb.Tag] = &newIb
  1370. if newIb.Tag != snapIb.Tag {
  1371. tagToCentral[newIb.Tag] = &newIb
  1372. }
  1373. structuralChange = true
  1374. continue
  1375. }
  1376. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1377. updates := map[string]any{
  1378. "enable": snapIb.Enable,
  1379. "remark": snapIb.Remark,
  1380. "listen": snapIb.Listen,
  1381. "port": snapIb.Port,
  1382. "protocol": snapIb.Protocol,
  1383. "total": snapIb.Total,
  1384. "expiry_time": snapIb.ExpiryTime,
  1385. "settings": snapIb.Settings,
  1386. "stream_settings": snapIb.StreamSettings,
  1387. "sniffing": snapIb.Sniffing,
  1388. "traffic_reset": snapIb.TrafficReset,
  1389. }
  1390. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1391. updates["up"] = snapIb.Up
  1392. updates["down"] = snapIb.Down
  1393. }
  1394. if c.Settings != snapIb.Settings ||
  1395. c.Remark != snapIb.Remark ||
  1396. c.Listen != snapIb.Listen ||
  1397. c.Port != snapIb.Port ||
  1398. c.Total != snapIb.Total ||
  1399. c.ExpiryTime != snapIb.ExpiryTime ||
  1400. c.Enable != snapIb.Enable {
  1401. structuralChange = true
  1402. }
  1403. if err := tx.Model(model.Inbound{}).
  1404. Where("id = ?", c.Id).
  1405. Updates(updates).Error; err != nil {
  1406. return false, err
  1407. }
  1408. }
  1409. for _, c := range central {
  1410. if _, kept := snapTags[c.Tag]; kept {
  1411. continue
  1412. }
  1413. var goneEmails []string
  1414. if err := tx.Model(xray.ClientTraffic{}).
  1415. Where("inbound_id = ?", c.Id).
  1416. Pluck("email", &goneEmails).Error; err != nil {
  1417. return false, err
  1418. }
  1419. if len(goneEmails) > 0 {
  1420. if err := tx.Where("node_id = ? AND email IN ?", nodeID, goneEmails).
  1421. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1422. return false, err
  1423. }
  1424. }
  1425. if err := tx.Where("inbound_id = ?", c.Id).
  1426. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1427. return false, err
  1428. }
  1429. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  1430. return false, err
  1431. }
  1432. if err := tx.Where("id = ?", c.Id).
  1433. Delete(&model.Inbound{}).Error; err != nil {
  1434. return false, err
  1435. }
  1436. delete(tagToCentral, c.Tag)
  1437. structuralChange = true
  1438. }
  1439. for _, snapIb := range snap.Inbounds {
  1440. if snapIb == nil {
  1441. continue
  1442. }
  1443. c, ok := tagToCentral[snapIb.Tag]
  1444. if !ok {
  1445. continue
  1446. }
  1447. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1448. for _, cs := range snapIb.ClientStats {
  1449. snapEmails[cs.Email] = struct{}{}
  1450. base, seen := nodeBaselines[cs.Email]
  1451. var deltaUp, deltaDown int64
  1452. if seen {
  1453. if deltaUp = cs.Up - base.Up; deltaUp < 0 {
  1454. deltaUp = cs.Up
  1455. }
  1456. if deltaDown = cs.Down - base.Down; deltaDown < 0 {
  1457. deltaDown = cs.Down
  1458. }
  1459. }
  1460. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  1461. row := &xray.ClientTraffic{
  1462. InboundId: c.Id,
  1463. Email: cs.Email,
  1464. Enable: cs.Enable,
  1465. Total: cs.Total,
  1466. ExpiryTime: cs.ExpiryTime,
  1467. Reset: cs.Reset,
  1468. Up: cs.Up,
  1469. Down: cs.Down,
  1470. LastOnline: cs.LastOnline,
  1471. }
  1472. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  1473. Create(row).Error; err != nil {
  1474. return false, err
  1475. }
  1476. centralCS[csKey{c.Id, cs.Email}] = row
  1477. centralCSByEmail[cs.Email] = row
  1478. existingEmails[cs.Email] = struct{}{}
  1479. structuralChange = true
  1480. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  1481. return false, err
  1482. }
  1483. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  1484. continue
  1485. }
  1486. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  1487. (existing.Enable != cs.Enable ||
  1488. existing.Total != cs.Total ||
  1489. existing.ExpiryTime != cs.ExpiryTime ||
  1490. existing.Reset != cs.Reset) {
  1491. structuralChange = true
  1492. }
  1493. // Only allow the node to disable a client (cs.Enable=false), never
  1494. // to re-enable one the panel has already disabled. A stale snapshot
  1495. // from the node arriving after a central disable would otherwise
  1496. // overwrite enable=false back to true, letting the client accumulate
  1497. // far more traffic than their limit before being disabled again.
  1498. enableExpr := "CASE WHEN ? = 0 THEN 0 ELSE enable END"
  1499. if err := tx.Exec(
  1500. fmt.Sprintf(
  1501. `UPDATE client_traffics
  1502. SET up = up + ?, down = down + ?, enable = %s, total = ?, expiry_time = ?, reset = ?,
  1503. last_online = %s
  1504. WHERE email = ?`,
  1505. enableExpr,
  1506. database.GreatestExpr("last_online", "?"),
  1507. ),
  1508. deltaUp, deltaDown, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset,
  1509. cs.LastOnline, cs.Email,
  1510. ).Error; err != nil {
  1511. return false, err
  1512. }
  1513. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  1514. return false, err
  1515. }
  1516. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  1517. }
  1518. for k, existing := range centralCS {
  1519. if k.inboundID != c.Id {
  1520. continue
  1521. }
  1522. if _, kept := snapEmails[k.email]; kept {
  1523. continue
  1524. }
  1525. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1526. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1527. return false, err
  1528. }
  1529. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1530. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1531. return false, err
  1532. }
  1533. structuralChange = true
  1534. }
  1535. }
  1536. type oldSet struct {
  1537. inboundID int
  1538. emails map[string]struct{}
  1539. }
  1540. var perInboundOld []oldSet
  1541. for _, snapIb := range snap.Inbounds {
  1542. if snapIb == nil {
  1543. continue
  1544. }
  1545. c, ok := tagToCentral[snapIb.Tag]
  1546. if !ok {
  1547. continue
  1548. }
  1549. var oldEmailsRows []string
  1550. if err := tx.Table("clients").
  1551. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1552. Where("client_inbounds.inbound_id = ?", c.Id).
  1553. Pluck("email", &oldEmailsRows).Error; err == nil {
  1554. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1555. for _, e := range oldEmailsRows {
  1556. if e != "" {
  1557. oldEmails[e] = struct{}{}
  1558. }
  1559. }
  1560. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1561. }
  1562. clients, gcErr := s.GetClients(snapIb)
  1563. if gcErr != nil {
  1564. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1565. continue
  1566. }
  1567. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  1568. for _, cs := range snapIb.ClientStats {
  1569. csEnableByEmail[cs.Email] = cs.Enable
  1570. }
  1571. filtered := clients[:0]
  1572. for i := range clients {
  1573. if isClientEmailTombstoned(clients[i].Email) {
  1574. continue
  1575. }
  1576. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  1577. clients[i].Enable = false
  1578. }
  1579. filtered = append(filtered, clients[i])
  1580. }
  1581. localEmails := make([]string, 0, len(filtered))
  1582. for i := range filtered {
  1583. if filtered[i].Email != "" {
  1584. localEmails = append(localEmails, filtered[i].Email)
  1585. }
  1586. }
  1587. if len(localEmails) > 0 {
  1588. var localMeta []struct {
  1589. Email string
  1590. Comment string `gorm:"column:comment"`
  1591. }
  1592. if err := tx.Table("clients").
  1593. Select("email, comment").
  1594. Where("email IN ?", localEmails).
  1595. Find(&localMeta).Error; err == nil {
  1596. commentByEmail := make(map[string]string, len(localMeta))
  1597. for _, m := range localMeta {
  1598. commentByEmail[m.Email] = m.Comment
  1599. }
  1600. for i := range filtered {
  1601. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1602. filtered[i].Comment = cmt
  1603. }
  1604. }
  1605. }
  1606. }
  1607. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1608. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1609. }
  1610. }
  1611. for _, old := range perInboundOld {
  1612. var stillAttached []string
  1613. if err := tx.Table("clients").
  1614. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1615. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1616. Pluck("email", &stillAttached).Error; err != nil {
  1617. continue
  1618. }
  1619. stillSet := make(map[string]struct{}, len(stillAttached))
  1620. for _, e := range stillAttached {
  1621. stillSet[e] = struct{}{}
  1622. }
  1623. for email := range old.emails {
  1624. if _, kept := stillSet[email]; kept {
  1625. continue
  1626. }
  1627. var attachmentCount int64
  1628. if err := tx.Table("client_inbounds").
  1629. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1630. Where("clients.email = ?", email).
  1631. Count(&attachmentCount).Error; err != nil {
  1632. continue
  1633. }
  1634. if attachmentCount > 0 {
  1635. continue
  1636. }
  1637. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  1638. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  1639. }
  1640. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1641. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  1642. }
  1643. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1644. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  1645. }
  1646. structuralChange = true
  1647. }
  1648. }
  1649. if err := tx.Commit().Error; err != nil {
  1650. return false, err
  1651. }
  1652. committed = true
  1653. if p != nil {
  1654. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1655. }
  1656. return structuralChange, nil
  1657. }
  1658. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1659. var disabledNodeIDs []int
  1660. err = submitTrafficWrite(func() error {
  1661. var inner error
  1662. needRestart, clientsDisabled, disabledNodeIDs, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1663. return inner
  1664. })
  1665. if err == nil && len(disabledNodeIDs) > 0 {
  1666. s.restartRemoteNodesOnDisable(disabledNodeIDs)
  1667. }
  1668. return
  1669. }
  1670. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, []int, error) {
  1671. var err error
  1672. db := database.GetDB()
  1673. tx := db.Begin()
  1674. defer func() {
  1675. if err != nil {
  1676. tx.Rollback()
  1677. } else {
  1678. tx.Commit()
  1679. }
  1680. }()
  1681. err = s.addInboundTraffic(tx, inboundTraffics)
  1682. if err != nil {
  1683. return false, false, nil, err
  1684. }
  1685. err = s.addClientTraffic(tx, clientTraffics)
  1686. if err != nil {
  1687. return false, false, nil, err
  1688. }
  1689. needRestart0, count, err := s.autoRenewClients(tx)
  1690. if err != nil {
  1691. logger.Warning("Error in renew clients:", err)
  1692. } else if count > 0 {
  1693. logger.Debugf("%v clients renewed", count)
  1694. }
  1695. disabledClientsCount := int64(0)
  1696. needRestart1, count, disabledNodeIDs, err := s.disableInvalidClients(tx)
  1697. if err != nil {
  1698. logger.Warning("Error in disabling invalid clients:", err)
  1699. } else if count > 0 {
  1700. logger.Debugf("%v clients disabled", count)
  1701. disabledClientsCount = count
  1702. }
  1703. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1704. if err != nil {
  1705. logger.Warning("Error in disabling invalid inbounds:", err)
  1706. } else if count > 0 {
  1707. logger.Debugf("%v inbounds disabled", count)
  1708. }
  1709. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, disabledNodeIDs, nil
  1710. }
  1711. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1712. if len(traffics) == 0 {
  1713. return nil
  1714. }
  1715. var err error
  1716. for _, traffic := range traffics {
  1717. if traffic.IsInbound {
  1718. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  1719. Updates(map[string]any{
  1720. "up": gorm.Expr("up + ?", traffic.Up),
  1721. "down": gorm.Expr("down + ?", traffic.Down),
  1722. }).Error
  1723. if err != nil {
  1724. return err
  1725. }
  1726. }
  1727. }
  1728. return nil
  1729. }
  1730. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1731. if len(traffics) == 0 {
  1732. return nil
  1733. }
  1734. emails := make([]string, 0, len(traffics))
  1735. for _, traffic := range traffics {
  1736. emails = append(emails, traffic.Email)
  1737. }
  1738. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1739. // Match purely by email. client_traffics is email-keyed (one shared row per
  1740. // email regardless of how many inbounds the client is attached to), and these
  1741. // emails come from the local xray's report, so they always belong to a client
  1742. // attached to a local inbound. The old `inbound_id NOT IN (node inbounds)`
  1743. // filter dropped the local traffic of a client attached to both a node and the
  1744. // mother inbound whenever the node inbound happened to be attached first — its
  1745. // shared row then carried the node inbound's id (AddClientStat uses OnConflict
  1746. // DoNothing and never refreshes it), so the local poll skipped it entirely.
  1747. err = tx.Model(xray.ClientTraffic{}).
  1748. Where("email IN (?)", emails).
  1749. Find(&dbClientTraffics).Error
  1750. if err != nil {
  1751. return err
  1752. }
  1753. // Avoid empty slice error
  1754. if len(dbClientTraffics) == 0 {
  1755. return nil
  1756. }
  1757. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1758. if err != nil {
  1759. return err
  1760. }
  1761. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1762. // and dominated each cron tick on inbounds with thousands of active
  1763. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1764. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1765. for i := range traffics {
  1766. if traffics[i] != nil {
  1767. trafficByEmail[traffics[i].Email] = traffics[i]
  1768. }
  1769. }
  1770. now := time.Now().UnixMilli()
  1771. for dbTraffic_index := range dbClientTraffics {
  1772. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1773. if !ok {
  1774. continue
  1775. }
  1776. dbClientTraffics[dbTraffic_index].Up += t.Up
  1777. dbClientTraffics[dbTraffic_index].Down += t.Down
  1778. if t.Up+t.Down > 0 {
  1779. dbClientTraffics[dbTraffic_index].LastOnline = now
  1780. }
  1781. }
  1782. err = tx.Save(dbClientTraffics).Error
  1783. if err != nil {
  1784. logger.Warning("AddClientTraffic update data ", err)
  1785. }
  1786. return nil
  1787. }
  1788. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1789. now := time.Now().UnixMilli()
  1790. // "Start After First Use" stores a negative expiry (the duration). On the
  1791. // first traffic tick it becomes an absolute deadline of now+duration. Compute
  1792. // it once per email so every inbound the client is attached to lands on the
  1793. // same value (recomputing per inbound would skip all but the first one).
  1794. newExpiryByEmail := make(map[string]int64, len(dbClientTraffics))
  1795. for traffic_index := range dbClientTraffics {
  1796. if dbClientTraffics[traffic_index].ExpiryTime < 0 {
  1797. newExpiryByEmail[dbClientTraffics[traffic_index].Email] = now - dbClientTraffics[traffic_index].ExpiryTime
  1798. }
  1799. }
  1800. if len(newExpiryByEmail) == 0 {
  1801. return dbClientTraffics, nil
  1802. }
  1803. delayedEmails := make([]string, 0, len(newExpiryByEmail))
  1804. for email := range newExpiryByEmail {
  1805. delayedEmails = append(delayedEmails, email)
  1806. }
  1807. // Resolve the owning inbounds through the client_inbounds link, which is
  1808. // authoritative. client_traffics.inbound_id goes stale when an inbound is
  1809. // deleted and recreated, which would leave the negative expiry unconverted.
  1810. var inboundIds []int
  1811. err := tx.Table("client_inbounds").
  1812. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1813. Where("clients.email IN (?)", delayedEmails).
  1814. Distinct().
  1815. Pluck("client_inbounds.inbound_id", &inboundIds).Error
  1816. if err != nil {
  1817. return nil, err
  1818. }
  1819. if len(inboundIds) == 0 {
  1820. return dbClientTraffics, nil
  1821. }
  1822. var inbounds []*model.Inbound
  1823. err = tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1824. if err != nil {
  1825. return nil, err
  1826. }
  1827. for inbound_index := range inbounds {
  1828. settings := map[string]any{}
  1829. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1830. clients, ok := settings["clients"].([]any)
  1831. if ok {
  1832. var newClients []any
  1833. for client_index := range clients {
  1834. c := clients[client_index].(map[string]any)
  1835. email, _ := c["email"].(string)
  1836. if newExpiry, ok := newExpiryByEmail[email]; ok {
  1837. c["expiryTime"] = newExpiry
  1838. c["updated_at"] = now
  1839. }
  1840. if _, ok := c["created_at"]; !ok {
  1841. c["created_at"] = now
  1842. }
  1843. if _, ok := c["updated_at"]; !ok {
  1844. c["updated_at"] = now
  1845. }
  1846. newClients = append(newClients, any(c))
  1847. }
  1848. settings["clients"] = newClients
  1849. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1850. if err != nil {
  1851. return nil, err
  1852. }
  1853. inbounds[inbound_index].Settings = string(modifiedSettings)
  1854. }
  1855. }
  1856. for traffic_index := range dbClientTraffics {
  1857. if newExpiry, ok := newExpiryByEmail[dbClientTraffics[traffic_index].Email]; ok {
  1858. dbClientTraffics[traffic_index].ExpiryTime = newExpiry
  1859. }
  1860. }
  1861. err = tx.Save(inbounds).Error
  1862. if err != nil {
  1863. logger.Warning("AddClientTraffic update inbounds ", err)
  1864. logger.Error(inbounds)
  1865. } else {
  1866. for _, ib := range inbounds {
  1867. if ib == nil {
  1868. continue
  1869. }
  1870. cs, gcErr := s.GetClients(ib)
  1871. if gcErr != nil {
  1872. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  1873. continue
  1874. }
  1875. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  1876. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  1877. }
  1878. }
  1879. }
  1880. return dbClientTraffics, nil
  1881. }
  1882. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1883. // check for time expired
  1884. var traffics []*xray.ClientTraffic
  1885. now := time.Now().Unix() * 1000
  1886. var err, err1 error
  1887. err = tx.Model(xray.ClientTraffic{}).
  1888. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  1889. Where("inbound_id NOT IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NOT NULL")).
  1890. Find(&traffics).Error
  1891. if err != nil {
  1892. return false, 0, err
  1893. }
  1894. // return if there is no client to renew
  1895. if len(traffics) == 0 {
  1896. return false, 0, nil
  1897. }
  1898. var inbound_ids []int
  1899. var inbounds []*model.Inbound
  1900. needRestart := false
  1901. var clientsToAdd []struct {
  1902. protocol string
  1903. tag string
  1904. client map[string]any
  1905. }
  1906. // Resolve the inbounds to renew through the client_inbounds link rather than
  1907. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  1908. // recreated and would otherwise skip the renew entirely.
  1909. renewEmails := make([]string, 0, len(traffics))
  1910. for _, traffic := range traffics {
  1911. renewEmails = append(renewEmails, traffic.Email)
  1912. }
  1913. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  1914. var ids []int
  1915. if err = tx.Table("client_inbounds").
  1916. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1917. Where("clients.email IN ?", batch).
  1918. Distinct().
  1919. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  1920. return false, 0, err
  1921. }
  1922. inbound_ids = append(inbound_ids, ids...)
  1923. }
  1924. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1925. // per tick instead of N times across chunk boundaries.
  1926. inbound_ids = uniqueInts(inbound_ids)
  1927. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1928. // are touched in a single tick.
  1929. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1930. var page []*model.Inbound
  1931. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1932. return false, 0, err
  1933. }
  1934. inbounds = append(inbounds, page...)
  1935. }
  1936. for inbound_index := range inbounds {
  1937. settings := map[string]any{}
  1938. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1939. clients := settings["clients"].([]any)
  1940. for client_index := range clients {
  1941. c := clients[client_index].(map[string]any)
  1942. for traffic_index, traffic := range traffics {
  1943. if traffic.Email == c["email"].(string) {
  1944. newExpiryTime := traffic.ExpiryTime
  1945. for newExpiryTime < now {
  1946. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1947. }
  1948. c["expiryTime"] = newExpiryTime
  1949. traffics[traffic_index].ExpiryTime = newExpiryTime
  1950. traffics[traffic_index].Down = 0
  1951. traffics[traffic_index].Up = 0
  1952. if !traffic.Enable {
  1953. traffics[traffic_index].Enable = true
  1954. c["enable"] = true
  1955. clientsToAdd = append(clientsToAdd,
  1956. struct {
  1957. protocol string
  1958. tag string
  1959. client map[string]any
  1960. }{
  1961. protocol: string(inbounds[inbound_index].Protocol),
  1962. tag: inbounds[inbound_index].Tag,
  1963. client: c,
  1964. })
  1965. }
  1966. clients[client_index] = any(c)
  1967. break
  1968. }
  1969. }
  1970. }
  1971. settings["clients"] = clients
  1972. newSettings, err := json.MarshalIndent(settings, "", " ")
  1973. if err != nil {
  1974. return false, 0, err
  1975. }
  1976. inbounds[inbound_index].Settings = string(newSettings)
  1977. }
  1978. err = tx.Save(inbounds).Error
  1979. if err != nil {
  1980. return false, 0, err
  1981. }
  1982. for _, ib := range inbounds {
  1983. if ib == nil {
  1984. continue
  1985. }
  1986. cs, gcErr := s.GetClients(ib)
  1987. if gcErr != nil {
  1988. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  1989. continue
  1990. }
  1991. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  1992. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  1993. }
  1994. }
  1995. err = tx.Save(traffics).Error
  1996. if err != nil {
  1997. return false, 0, err
  1998. }
  1999. if p != nil {
  2000. err1 = s.xrayApi.Init(p.GetAPIPort())
  2001. if err1 != nil {
  2002. return true, int64(len(traffics)), nil
  2003. }
  2004. for _, clientToAdd := range clientsToAdd {
  2005. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  2006. if err1 != nil {
  2007. needRestart = true
  2008. }
  2009. }
  2010. s.xrayApi.Close()
  2011. }
  2012. return needRestart, int64(len(traffics)), nil
  2013. }
  2014. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  2015. now := time.Now().Unix() * 1000
  2016. needRestart := false
  2017. if p != nil {
  2018. var tags []string
  2019. err := tx.Table("inbounds").
  2020. Select("inbounds.tag").
  2021. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  2022. Scan(&tags).Error
  2023. if err != nil {
  2024. return false, 0, err
  2025. }
  2026. s.xrayApi.Init(p.GetAPIPort())
  2027. for _, tag := range tags {
  2028. err1 := s.xrayApi.DelInbound(tag)
  2029. if err1 == nil {
  2030. logger.Debug("Inbound disabled by api:", tag)
  2031. } else {
  2032. logger.Debug("Error in disabling inbound by api:", err1)
  2033. needRestart = true
  2034. }
  2035. }
  2036. s.xrayApi.Close()
  2037. }
  2038. result := tx.Model(model.Inbound{}).
  2039. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  2040. Update("enable", false)
  2041. err := result.Error
  2042. count := result.RowsAffected
  2043. return needRestart, count, err
  2044. }
  2045. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, []int, error) {
  2046. now := time.Now().Unix() * 1000
  2047. needRestart := false
  2048. var depletedRows []xray.ClientTraffic
  2049. err := tx.Model(xray.ClientTraffic{}).
  2050. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  2051. Find(&depletedRows).Error
  2052. if err != nil {
  2053. return false, 0, nil, err
  2054. }
  2055. if len(depletedRows) == 0 {
  2056. return false, 0, nil, nil
  2057. }
  2058. depletedEmails := make([]string, 0, len(depletedRows))
  2059. for i := range depletedRows {
  2060. if depletedRows[i].Email == "" {
  2061. continue
  2062. }
  2063. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  2064. }
  2065. type target struct {
  2066. InboundID int `gorm:"column:inbound_id"`
  2067. NodeID *int `gorm:"column:node_id"`
  2068. Tag string
  2069. Email string
  2070. }
  2071. var targets []target
  2072. if len(depletedEmails) > 0 {
  2073. err = tx.Raw(`
  2074. SELECT inbounds.id AS inbound_id, inbounds.node_id AS node_id,
  2075. inbounds.tag AS tag, clients.email AS email
  2076. FROM clients
  2077. JOIN client_inbounds ON client_inbounds.client_id = clients.id
  2078. JOIN inbounds ON inbounds.id = client_inbounds.inbound_id
  2079. WHERE clients.email IN ?
  2080. `, depletedEmails).Scan(&targets).Error
  2081. if err != nil {
  2082. return false, 0, nil, err
  2083. }
  2084. }
  2085. var localTargets []target
  2086. localByInbound := make(map[int]map[string]struct{})
  2087. remoteByInbound := make(map[int][]target)
  2088. for _, t := range targets {
  2089. if t.NodeID == nil {
  2090. localTargets = append(localTargets, t)
  2091. if localByInbound[t.InboundID] == nil {
  2092. localByInbound[t.InboundID] = make(map[string]struct{})
  2093. }
  2094. localByInbound[t.InboundID][t.Email] = struct{}{}
  2095. } else {
  2096. remoteByInbound[t.InboundID] = append(remoteByInbound[t.InboundID], t)
  2097. }
  2098. }
  2099. if p != nil && len(localTargets) > 0 {
  2100. s.xrayApi.Init(p.GetAPIPort())
  2101. for _, t := range localTargets {
  2102. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  2103. if err1 == nil {
  2104. logger.Debug("Client disabled by api:", t.Email)
  2105. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  2106. logger.Debug("User is already disabled. Nothing to do more...")
  2107. } else {
  2108. logger.Debug("Error in disabling client by api:", err1)
  2109. needRestart = true
  2110. }
  2111. }
  2112. s.xrayApi.Close()
  2113. }
  2114. for inboundID, emails := range localByInbound {
  2115. if _, _, mErr := s.markClientsDisabledInSettings(tx, inboundID, emails); mErr != nil {
  2116. logger.Warning("disableInvalidClients: settings.JSON sync failed for inbound", inboundID, ":", mErr)
  2117. }
  2118. }
  2119. result := tx.Model(xray.ClientTraffic{}).
  2120. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  2121. Update("enable", false)
  2122. err = result.Error
  2123. count := result.RowsAffected
  2124. if err != nil {
  2125. return needRestart, count, nil, err
  2126. }
  2127. if len(depletedEmails) > 0 {
  2128. if err := tx.Model(&model.ClientRecord{}).
  2129. Where("email IN ?", depletedEmails).
  2130. Updates(map[string]any{"enable": false, "updated_at": now}).Error; err != nil {
  2131. logger.Warning("disableInvalidClients update clients.enable:", err)
  2132. }
  2133. }
  2134. disabledNodeIDs := make(map[int]struct{})
  2135. for inboundID, group := range remoteByInbound {
  2136. emails := make(map[string]struct{}, len(group))
  2137. for _, t := range group {
  2138. emails[t.Email] = struct{}{}
  2139. }
  2140. if pushErr := s.disableRemoteClients(tx, inboundID, emails); pushErr != nil {
  2141. logger.Warning("disableInvalidClients: push to remote failed for inbound", inboundID, ":", pushErr)
  2142. needRestart = true
  2143. } else {
  2144. for _, t := range group {
  2145. if t.NodeID != nil {
  2146. disabledNodeIDs[*t.NodeID] = struct{}{}
  2147. }
  2148. }
  2149. }
  2150. }
  2151. nodeIDs := make([]int, 0, len(disabledNodeIDs))
  2152. for nodeID := range disabledNodeIDs {
  2153. nodeIDs = append(nodeIDs, nodeID)
  2154. }
  2155. return needRestart, count, nodeIDs, nil
  2156. }
  2157. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  2158. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  2159. if err != nil {
  2160. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  2161. return
  2162. }
  2163. if !restartOnDisable {
  2164. return
  2165. }
  2166. for _, nodeID := range nodeIDs {
  2167. nodeIDCopy := nodeID
  2168. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  2169. if rtErr != nil {
  2170. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  2171. continue
  2172. }
  2173. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  2174. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  2175. }
  2176. }
  2177. }
  2178. // markClientsDisabledInSettings flips client.enable=false in the inbound's
  2179. // stored settings JSON for the given emails and returns both the pre and
  2180. // post snapshots so a caller pushing to a remote node has the diff to hand.
  2181. func (s *InboundService) markClientsDisabledInSettings(tx *gorm.DB, inboundID int, emails map[string]struct{}) (oldIb, newIb *model.Inbound, err error) {
  2182. var ib model.Inbound
  2183. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).First(&ib).Error; err != nil {
  2184. return nil, nil, err
  2185. }
  2186. snapshot := ib
  2187. settings := map[string]any{}
  2188. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  2189. return nil, nil, err
  2190. }
  2191. clients, _ := settings["clients"].([]any)
  2192. now := time.Now().Unix() * 1000
  2193. mutated := false
  2194. for i := range clients {
  2195. entry, ok := clients[i].(map[string]any)
  2196. if !ok {
  2197. continue
  2198. }
  2199. email, _ := entry["email"].(string)
  2200. if _, hit := emails[email]; !hit {
  2201. continue
  2202. }
  2203. if cur, _ := entry["enable"].(bool); cur == false {
  2204. continue
  2205. }
  2206. entry["enable"] = false
  2207. entry["updated_at"] = now
  2208. clients[i] = entry
  2209. mutated = true
  2210. }
  2211. if !mutated {
  2212. return &snapshot, &ib, nil
  2213. }
  2214. settings["clients"] = clients
  2215. bs, marshalErr := json.MarshalIndent(settings, "", " ")
  2216. if marshalErr != nil {
  2217. return nil, nil, marshalErr
  2218. }
  2219. ib.Settings = string(bs)
  2220. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).
  2221. Update("settings", ib.Settings).Error; err != nil {
  2222. return nil, nil, err
  2223. }
  2224. return &snapshot, &ib, nil
  2225. }
  2226. func (s *InboundService) disableRemoteClients(tx *gorm.DB, inboundID int, emails map[string]struct{}) error {
  2227. oldSnapshot, ib, err := s.markClientsDisabledInSettings(tx, inboundID, emails)
  2228. if err != nil {
  2229. return err
  2230. }
  2231. rt, err := s.runtimeFor(ib)
  2232. if err != nil {
  2233. return err
  2234. }
  2235. if err := rt.UpdateInbound(context.Background(), oldSnapshot, ib); err != nil {
  2236. return err
  2237. }
  2238. return nil
  2239. }
  2240. func (s *InboundService) GetInboundTags() (string, error) {
  2241. db := database.GetDB()
  2242. var inboundTags []string
  2243. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2244. if err != nil && err != gorm.ErrRecordNotFound {
  2245. return "", err
  2246. }
  2247. tags, _ := json.Marshal(inboundTags)
  2248. return string(tags), nil
  2249. }
  2250. func (s *InboundService) GetClientReverseTags() (string, error) {
  2251. db := database.GetDB()
  2252. var inbounds []model.Inbound
  2253. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2254. if err != nil && err != gorm.ErrRecordNotFound {
  2255. return "[]", err
  2256. }
  2257. tagSet := make(map[string]struct{})
  2258. for _, inbound := range inbounds {
  2259. var settings map[string]any
  2260. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2261. continue
  2262. }
  2263. clients, ok := settings["clients"].([]any)
  2264. if !ok {
  2265. continue
  2266. }
  2267. for _, client := range clients {
  2268. clientMap, ok := client.(map[string]any)
  2269. if !ok {
  2270. continue
  2271. }
  2272. reverse, ok := clientMap["reverse"].(map[string]any)
  2273. if !ok {
  2274. continue
  2275. }
  2276. tag, _ := reverse["tag"].(string)
  2277. tag = strings.TrimSpace(tag)
  2278. if tag != "" {
  2279. tagSet[tag] = struct{}{}
  2280. }
  2281. }
  2282. }
  2283. rawTags := make([]string, 0, len(tagSet))
  2284. for tag := range tagSet {
  2285. rawTags = append(rawTags, tag)
  2286. }
  2287. sort.Strings(rawTags)
  2288. result, _ := json.Marshal(rawTags)
  2289. return string(result), nil
  2290. }
  2291. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2292. db := database.GetDB()
  2293. query := fmt.Sprintf(
  2294. "DELETE FROM client_traffics WHERE email NOT IN (SELECT %s %s)",
  2295. database.JSONFieldText("client.value", "email"),
  2296. database.JSONClientsFromInbound(),
  2297. )
  2298. db.Exec(query)
  2299. }
  2300. // AddClientStat inserts a per-client accounting row, no-op on email
  2301. // conflict. Xray reports traffic per email, so the surviving row acts as
  2302. // the shared accumulator for inbounds that re-use the same identity.
  2303. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2304. clientTraffic := xray.ClientTraffic{
  2305. InboundId: inboundId,
  2306. Email: client.Email,
  2307. Total: client.TotalGB,
  2308. ExpiryTime: client.ExpiryTime,
  2309. Enable: client.Enable,
  2310. Reset: client.Reset,
  2311. }
  2312. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2313. Create(&clientTraffic).Error
  2314. }
  2315. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2316. result := tx.Model(xray.ClientTraffic{}).
  2317. Where("email = ?", email).
  2318. Updates(map[string]any{
  2319. "enable": client.Enable,
  2320. "email": client.Email,
  2321. "total": client.TotalGB,
  2322. "expiry_time": client.ExpiryTime,
  2323. "reset": client.Reset,
  2324. })
  2325. err := result.Error
  2326. return err
  2327. }
  2328. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2329. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2330. }
  2331. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2332. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  2333. return err
  2334. }
  2335. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  2336. }
  2337. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2338. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2339. }
  2340. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  2341. const chunk = 400
  2342. for start := 0; start < len(emails); start += chunk {
  2343. end := min(start+chunk, len(emails))
  2344. batch := emails[start:end]
  2345. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  2346. return err
  2347. }
  2348. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  2349. return err
  2350. }
  2351. }
  2352. return nil
  2353. }
  2354. func (s *InboundService) delClientIPsByEmails(tx *gorm.DB, emails []string) error {
  2355. const chunk = 400
  2356. for start := 0; start < len(emails); start += chunk {
  2357. end := min(start+chunk, len(emails))
  2358. if err := tx.Where("client_email IN ?", emails[start:end]).Delete(model.InboundClientIps{}).Error; err != nil {
  2359. return err
  2360. }
  2361. }
  2362. return nil
  2363. }
  2364. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2365. db := database.GetDB()
  2366. var traffics []*xray.ClientTraffic
  2367. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2368. if err != nil {
  2369. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2370. return nil, nil, err
  2371. }
  2372. if len(traffics) == 0 {
  2373. return nil, nil, nil
  2374. }
  2375. traffic = traffics[0]
  2376. inbound, err = s.GetInbound(traffic.InboundId)
  2377. if errors.Is(err, gorm.ErrRecordNotFound) {
  2378. // client_traffics.inbound_id goes stale when an inbound is deleted and
  2379. // recreated; fall back to the authoritative client_inbounds link by email.
  2380. ids, idErr := s.clientService.GetInboundIdsForEmail(db, traffic.Email)
  2381. if idErr != nil {
  2382. return traffic, nil, idErr
  2383. }
  2384. if len(ids) > 0 {
  2385. inbound, err = s.GetInbound(ids[0])
  2386. }
  2387. }
  2388. return traffic, inbound, err
  2389. }
  2390. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2391. db := database.GetDB()
  2392. var traffics []*xray.ClientTraffic
  2393. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2394. if err != nil {
  2395. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2396. return nil, nil, err
  2397. }
  2398. if len(traffics) == 0 {
  2399. return nil, nil, nil
  2400. }
  2401. traffic = traffics[0]
  2402. inbound, err = s.GetInbound(traffic.InboundId)
  2403. if errors.Is(err, gorm.ErrRecordNotFound) {
  2404. // client_traffics.inbound_id is a legacy single-inbound pointer that goes
  2405. // stale when an inbound is deleted and recreated: the email-keyed traffic
  2406. // row survives but still references the missing inbound. Fall back to the
  2407. // authoritative client_inbounds link so email lookups (reset, info, …) work.
  2408. ids, idErr := s.clientService.GetInboundIdsForEmail(db, email)
  2409. if idErr != nil {
  2410. return traffic, nil, idErr
  2411. }
  2412. if len(ids) > 0 {
  2413. inbound, err = s.GetInbound(ids[0])
  2414. }
  2415. }
  2416. return traffic, inbound, err
  2417. }
  2418. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2419. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2420. if err != nil {
  2421. return nil, nil, err
  2422. }
  2423. if inbound == nil {
  2424. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2425. }
  2426. clients, err := s.GetClients(inbound)
  2427. if err != nil {
  2428. return nil, nil, err
  2429. }
  2430. for _, client := range clients {
  2431. if client.Email == clientEmail {
  2432. return traffic, &client, nil
  2433. }
  2434. }
  2435. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2436. }
  2437. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2438. return submitTrafficWrite(func() error {
  2439. db := database.GetDB()
  2440. return db.Model(xray.ClientTraffic{}).
  2441. Where("email = ?", clientEmail).
  2442. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
  2443. })
  2444. }
  2445. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  2446. err = submitTrafficWrite(func() error {
  2447. var inner error
  2448. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  2449. return inner
  2450. })
  2451. return
  2452. }
  2453. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  2454. needRestart := false
  2455. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2456. if err != nil {
  2457. return false, err
  2458. }
  2459. if !traffic.Enable {
  2460. inbound, err := s.GetInbound(id)
  2461. if err != nil {
  2462. return false, err
  2463. }
  2464. clients, err := s.GetClients(inbound)
  2465. if err != nil {
  2466. return false, err
  2467. }
  2468. for _, client := range clients {
  2469. if client.Email == clientEmail && client.Enable {
  2470. rt, rterr := s.runtimeFor(inbound)
  2471. if rterr != nil {
  2472. if inbound.NodeID != nil {
  2473. return false, rterr
  2474. }
  2475. needRestart = true
  2476. break
  2477. }
  2478. cipher := ""
  2479. if string(inbound.Protocol) == "shadowsocks" {
  2480. var oldSettings map[string]any
  2481. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2482. if err != nil {
  2483. return false, err
  2484. }
  2485. cipher = oldSettings["method"].(string)
  2486. }
  2487. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2488. "email": client.Email,
  2489. "id": client.ID,
  2490. "auth": client.Auth,
  2491. "security": client.Security,
  2492. "flow": client.Flow,
  2493. "password": client.Password,
  2494. "cipher": cipher,
  2495. })
  2496. if err1 == nil {
  2497. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2498. } else {
  2499. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2500. needRestart = true
  2501. }
  2502. break
  2503. }
  2504. }
  2505. }
  2506. traffic.Up = 0
  2507. traffic.Down = 0
  2508. traffic.Enable = true
  2509. db := database.GetDB()
  2510. err = db.Save(traffic).Error
  2511. if err != nil {
  2512. return false, err
  2513. }
  2514. now := time.Now().UnixMilli()
  2515. _ = db.Model(model.Inbound{}).
  2516. Where("id = ?", id).
  2517. Update("last_traffic_reset_time", now).Error
  2518. inbound, err := s.GetInbound(id)
  2519. if err == nil && inbound != nil && inbound.NodeID != nil {
  2520. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2521. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2522. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2523. }
  2524. } else {
  2525. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2526. }
  2527. }
  2528. return needRestart, nil
  2529. }
  2530. func (s *InboundService) ResetAllTraffics() error {
  2531. return submitTrafficWrite(func() error {
  2532. return s.resetAllTrafficsLocked()
  2533. })
  2534. }
  2535. func (s *InboundService) resetAllTrafficsLocked() error {
  2536. db := database.GetDB()
  2537. now := time.Now().UnixMilli()
  2538. if err := db.Model(model.Inbound{}).
  2539. Where("user_id > ?", 0).
  2540. Updates(map[string]any{
  2541. "up": 0,
  2542. "down": 0,
  2543. "last_traffic_reset_time": now,
  2544. }).Error; err != nil {
  2545. return err
  2546. }
  2547. return nil
  2548. }
  2549. func (s *InboundService) ResetInboundTraffic(id int) error {
  2550. return submitTrafficWrite(func() error {
  2551. db := database.GetDB()
  2552. return db.Model(model.Inbound{}).
  2553. Where("id = ?", id).
  2554. Updates(map[string]any{"up": 0, "down": 0}).Error
  2555. })
  2556. }
  2557. // EmailsByInbound returns the list of client emails currently configured on
  2558. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  2559. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  2560. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  2561. inbound, err := s.GetInbound(inboundId)
  2562. if err != nil {
  2563. return nil, err
  2564. }
  2565. clients, err := s.GetClients(inbound)
  2566. if err != nil {
  2567. return nil, err
  2568. }
  2569. emails := make([]string, 0, len(clients))
  2570. for _, c := range clients {
  2571. if e := strings.TrimSpace(c.Email); e != "" {
  2572. emails = append(emails, e)
  2573. }
  2574. }
  2575. return emails, nil
  2576. }
  2577. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2578. db := database.GetDB()
  2579. tx := db.Begin()
  2580. defer func() {
  2581. if err == nil {
  2582. tx.Commit()
  2583. } else {
  2584. tx.Rollback()
  2585. }
  2586. }()
  2587. // Collect depleted emails globally — a shared-email row owned by one
  2588. // inbound depletes every sibling that lists the email.
  2589. now := time.Now().Unix() * 1000
  2590. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2591. var depletedRows []xray.ClientTraffic
  2592. err = db.Model(xray.ClientTraffic{}).
  2593. Where(depletedClause, now).
  2594. Find(&depletedRows).Error
  2595. if err != nil {
  2596. return err
  2597. }
  2598. if len(depletedRows) == 0 {
  2599. return nil
  2600. }
  2601. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2602. for _, r := range depletedRows {
  2603. if r.Email == "" {
  2604. continue
  2605. }
  2606. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2607. }
  2608. if len(depletedEmails) == 0 {
  2609. return nil
  2610. }
  2611. var inbounds []*model.Inbound
  2612. inboundQuery := db.Model(model.Inbound{})
  2613. if id >= 0 {
  2614. inboundQuery = inboundQuery.Where("id = ?", id)
  2615. }
  2616. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2617. return err
  2618. }
  2619. for _, inbound := range inbounds {
  2620. var settings map[string]any
  2621. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2622. return err
  2623. }
  2624. rawClients, ok := settings["clients"].([]any)
  2625. if !ok {
  2626. continue
  2627. }
  2628. newClients := make([]any, 0, len(rawClients))
  2629. removed := 0
  2630. for _, client := range rawClients {
  2631. c, ok := client.(map[string]any)
  2632. if !ok {
  2633. newClients = append(newClients, client)
  2634. continue
  2635. }
  2636. email, _ := c["email"].(string)
  2637. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2638. removed++
  2639. continue
  2640. }
  2641. newClients = append(newClients, client)
  2642. }
  2643. if removed == 0 {
  2644. continue
  2645. }
  2646. if len(newClients) == 0 {
  2647. s.DelInbound(inbound.Id)
  2648. continue
  2649. }
  2650. settings["clients"] = newClients
  2651. ns, mErr := json.MarshalIndent(settings, "", " ")
  2652. if mErr != nil {
  2653. return mErr
  2654. }
  2655. inbound.Settings = string(ns)
  2656. if err = tx.Save(inbound).Error; err != nil {
  2657. return err
  2658. }
  2659. survivingClients, gcErr := s.GetClients(inbound)
  2660. if gcErr != nil {
  2661. err = gcErr
  2662. return err
  2663. }
  2664. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  2665. return err
  2666. }
  2667. }
  2668. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2669. // no out-of-scope inbound still references the email.
  2670. if id < 0 {
  2671. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2672. return err
  2673. }
  2674. emails := make([]string, 0, len(depletedEmails))
  2675. for e := range depletedEmails {
  2676. emails = append(emails, e)
  2677. }
  2678. var stillReferenced []string
  2679. emailExpr := database.JSONFieldText("client.value", "email")
  2680. stillQuery := fmt.Sprintf(
  2681. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  2682. emailExpr,
  2683. database.JSONClientsFromInbound(),
  2684. emailExpr,
  2685. )
  2686. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  2687. return err
  2688. }
  2689. stillSet := make(map[string]struct{}, len(stillReferenced))
  2690. for _, e := range stillReferenced {
  2691. stillSet[e] = struct{}{}
  2692. }
  2693. toDelete := make([]string, 0, len(emails))
  2694. for _, e := range emails {
  2695. if _, kept := stillSet[e]; !kept {
  2696. toDelete = append(toDelete, e)
  2697. }
  2698. }
  2699. if len(toDelete) > 0 {
  2700. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2701. return err
  2702. }
  2703. }
  2704. return nil
  2705. }
  2706. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2707. db := database.GetDB()
  2708. var inbounds []*model.Inbound
  2709. // Retrieve inbounds where settings contain the given tgId
  2710. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2711. if err != nil && err != gorm.ErrRecordNotFound {
  2712. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2713. return nil, err
  2714. }
  2715. var emails []string
  2716. for _, inbound := range inbounds {
  2717. clients, err := s.GetClients(inbound)
  2718. if err != nil {
  2719. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2720. continue
  2721. }
  2722. for _, client := range clients {
  2723. if client.TgID == tgId {
  2724. emails = append(emails, client.Email)
  2725. }
  2726. }
  2727. }
  2728. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2729. // account owns thousands of clients across inbounds.
  2730. uniqEmails := uniqueNonEmptyStrings(emails)
  2731. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2732. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2733. var page []*xray.ClientTraffic
  2734. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2735. if err == gorm.ErrRecordNotFound {
  2736. continue
  2737. }
  2738. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2739. return nil, err
  2740. }
  2741. traffics = append(traffics, page...)
  2742. }
  2743. if len(traffics) == 0 {
  2744. logger.Warning("No ClientTraffic records found for emails:", emails)
  2745. return nil, nil
  2746. }
  2747. // Populate UUID and other client data for each traffic record
  2748. for i := range traffics {
  2749. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2750. traffics[i].Enable = client.Enable
  2751. traffics[i].UUID = client.ID
  2752. traffics[i].SubId = client.SubID
  2753. }
  2754. }
  2755. return traffics, nil
  2756. }
  2757. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2758. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2759. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2760. // across forks/old binaries and also bounds per-query memory on truly large
  2761. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2762. const sqliteMaxVars = 900
  2763. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2764. // removed, preserving the order of first occurrence.
  2765. func uniqueNonEmptyStrings(in []string) []string {
  2766. if len(in) == 0 {
  2767. return nil
  2768. }
  2769. seen := make(map[string]struct{}, len(in))
  2770. out := make([]string, 0, len(in))
  2771. for _, v := range in {
  2772. if v == "" {
  2773. continue
  2774. }
  2775. if _, ok := seen[v]; ok {
  2776. continue
  2777. }
  2778. seen[v] = struct{}{}
  2779. out = append(out, v)
  2780. }
  2781. return out
  2782. }
  2783. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2784. func uniqueInts(in []int) []int {
  2785. if len(in) == 0 {
  2786. return nil
  2787. }
  2788. seen := make(map[int]struct{}, len(in))
  2789. out := make([]int, 0, len(in))
  2790. for _, v := range in {
  2791. if _, ok := seen[v]; ok {
  2792. continue
  2793. }
  2794. seen[v] = struct{}{}
  2795. out = append(out, v)
  2796. }
  2797. return out
  2798. }
  2799. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2800. // Returns nil for an empty input or non-positive size.
  2801. func chunkStrings(s []string, size int) [][]string {
  2802. if size <= 0 || len(s) == 0 {
  2803. return nil
  2804. }
  2805. out := make([][]string, 0, (len(s)+size-1)/size)
  2806. for i := 0; i < len(s); i += size {
  2807. end := min(i+size, len(s))
  2808. out = append(out, s[i:end])
  2809. }
  2810. return out
  2811. }
  2812. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2813. // Returns nil for an empty input or non-positive size.
  2814. func chunkInts(s []int, size int) [][]int {
  2815. if size <= 0 || len(s) == 0 {
  2816. return nil
  2817. }
  2818. out := make([][]int, 0, (len(s)+size-1)/size)
  2819. for i := 0; i < len(s); i += size {
  2820. end := min(i+size, len(s))
  2821. out = append(out, s[i:end])
  2822. }
  2823. return out
  2824. }
  2825. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2826. uniq := uniqueNonEmptyStrings(emails)
  2827. if len(uniq) == 0 {
  2828. return nil, nil
  2829. }
  2830. db := database.GetDB()
  2831. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2832. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2833. var page []*xray.ClientTraffic
  2834. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2835. return nil, err
  2836. }
  2837. traffics = append(traffics, page...)
  2838. }
  2839. return traffics, nil
  2840. }
  2841. // GetAllClientTraffics returns the full set of client_traffics rows so the
  2842. // websocket broadcasters can ship a complete snapshot every cycle. The old
  2843. // delta-only path (GetActiveClientTraffics on activeEmails) silently dropped
  2844. // the per-client section whenever no client moved bytes in the cycle or a
  2845. // node sync failed, leaving client rows in the UI stuck at stale numbers.
  2846. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  2847. db := database.GetDB()
  2848. var traffics []*xray.ClientTraffic
  2849. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  2850. return nil, err
  2851. }
  2852. return traffics, nil
  2853. }
  2854. type InboundTrafficSummary struct {
  2855. Id int `json:"id"`
  2856. Up int64 `json:"up"`
  2857. Down int64 `json:"down"`
  2858. Total int64 `json:"total"`
  2859. Enable bool `json:"enable"`
  2860. }
  2861. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2862. db := database.GetDB()
  2863. var summaries []InboundTrafficSummary
  2864. if err := db.Model(&model.Inbound{}).
  2865. Select("id, up, down, total, enable").
  2866. Find(&summaries).Error; err != nil {
  2867. return nil, err
  2868. }
  2869. return summaries, nil
  2870. }
  2871. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2872. db := database.GetDB()
  2873. var traffics []*xray.ClientTraffic
  2874. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  2875. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2876. return nil, err
  2877. }
  2878. if len(traffics) == 0 {
  2879. return nil, nil
  2880. }
  2881. t := traffics[0]
  2882. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  2883. c := rec.ToClient()
  2884. t.UUID = c.ID
  2885. t.SubId = c.SubID
  2886. return t, nil
  2887. }
  2888. t2, client, err := s.GetClientByEmail(email)
  2889. if err != nil {
  2890. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2891. return nil, err
  2892. }
  2893. if t2 != nil && client != nil {
  2894. t2.UUID = client.ID
  2895. t2.SubId = client.SubID
  2896. return t2, nil
  2897. }
  2898. return nil, nil
  2899. }
  2900. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2901. return submitTrafficWrite(func() error {
  2902. db := database.GetDB()
  2903. err := db.Model(xray.ClientTraffic{}).
  2904. Where("email = ?", email).
  2905. Updates(map[string]any{
  2906. "up": upload,
  2907. "down": download,
  2908. }).Error
  2909. if err != nil {
  2910. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2911. }
  2912. return err
  2913. })
  2914. }
  2915. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2916. db := database.GetDB()
  2917. inbound := &model.Inbound{}
  2918. traffic = &xray.ClientTraffic{}
  2919. // Search for inbound settings that contain the query
  2920. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2921. if err != nil {
  2922. if err == gorm.ErrRecordNotFound {
  2923. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2924. return nil, err
  2925. }
  2926. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2927. return nil, err
  2928. }
  2929. traffic.InboundId = inbound.Id
  2930. // Unmarshal settings to get clients
  2931. settings := map[string][]model.Client{}
  2932. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2933. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2934. return nil, err
  2935. }
  2936. clients := settings["clients"]
  2937. for _, client := range clients {
  2938. if (client.ID == query || client.Password == query) && client.Email != "" {
  2939. traffic.Email = client.Email
  2940. break
  2941. }
  2942. }
  2943. if traffic.Email == "" {
  2944. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2945. return nil, gorm.ErrRecordNotFound
  2946. }
  2947. // Retrieve ClientTraffic based on the found email
  2948. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2949. if err != nil {
  2950. if err == gorm.ErrRecordNotFound {
  2951. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2952. return nil, err
  2953. }
  2954. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2955. return nil, err
  2956. }
  2957. return traffic, nil
  2958. }
  2959. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2960. db := database.GetDB()
  2961. InboundClientIps := &model.InboundClientIps{}
  2962. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2963. if err != nil {
  2964. return "", err
  2965. }
  2966. if InboundClientIps.Ips == "" {
  2967. return "", nil
  2968. }
  2969. // Try to parse as new format (with timestamps)
  2970. type IPWithTimestamp struct {
  2971. IP string `json:"ip"`
  2972. Timestamp int64 `json:"timestamp"`
  2973. }
  2974. var ipsWithTime []IPWithTimestamp
  2975. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2976. // If successfully parsed as new format, return with timestamps
  2977. if err == nil && len(ipsWithTime) > 0 {
  2978. return InboundClientIps.Ips, nil
  2979. }
  2980. // Otherwise, assume it's old format (simple string array)
  2981. // Try to parse as simple array and convert to new format
  2982. var oldIps []string
  2983. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2984. if err == nil && len(oldIps) > 0 {
  2985. // Convert old format to new format with current timestamp
  2986. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2987. for i, ip := range oldIps {
  2988. newIpsWithTime[i] = IPWithTimestamp{
  2989. IP: ip,
  2990. Timestamp: time.Now().Unix(),
  2991. }
  2992. }
  2993. result, _ := json.Marshal(newIpsWithTime)
  2994. return string(result), nil
  2995. }
  2996. // Return as-is if parsing fails
  2997. return InboundClientIps.Ips, nil
  2998. }
  2999. func (s *InboundService) ClearClientIps(clientEmail string) error {
  3000. db := database.GetDB()
  3001. result := db.Model(model.InboundClientIps{}).
  3002. Where("client_email = ?", clientEmail).
  3003. Update("ips", "")
  3004. err := result.Error
  3005. if err != nil {
  3006. return err
  3007. }
  3008. return nil
  3009. }
  3010. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  3011. db := database.GetDB()
  3012. var inbounds []*model.Inbound
  3013. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  3014. if err != nil && err != gorm.ErrRecordNotFound {
  3015. return nil, err
  3016. }
  3017. return inbounds, nil
  3018. }
  3019. func (s *InboundService) MigrationRequirements() {
  3020. db := database.GetDB()
  3021. tx := db.Begin()
  3022. var err error
  3023. defer func() {
  3024. if err == nil {
  3025. tx.Commit()
  3026. if !database.IsPostgres() {
  3027. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  3028. logger.Warningf("VACUUM failed: %v", dbErr)
  3029. }
  3030. }
  3031. } else {
  3032. tx.Rollback()
  3033. }
  3034. }()
  3035. if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
  3036. if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
  3037. return
  3038. }
  3039. }
  3040. if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
  3041. if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
  3042. return
  3043. }
  3044. }
  3045. // Fix inbounds based problems
  3046. var inbounds []*model.Inbound
  3047. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error
  3048. if err != nil && err != gorm.ErrRecordNotFound {
  3049. return
  3050. }
  3051. for inbound_index := range inbounds {
  3052. settings := map[string]any{}
  3053. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  3054. if raw, exists := settings["clients"]; exists && raw == nil {
  3055. settings["clients"] = []any{}
  3056. }
  3057. clients, ok := settings["clients"].([]any)
  3058. if ok {
  3059. // Fix Client configuration problems
  3060. newClients := make([]any, 0, len(clients))
  3061. hasVisionFlow := false
  3062. for client_index := range clients {
  3063. c := clients[client_index].(map[string]any)
  3064. // Add email='' if it is not exists
  3065. if _, ok := c["email"]; !ok {
  3066. c["email"] = ""
  3067. }
  3068. // Convert string tgId to int64
  3069. if _, ok := c["tgId"]; ok {
  3070. var tgId any = c["tgId"]
  3071. if tgIdStr, ok2 := tgId.(string); ok2 {
  3072. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  3073. if err == nil {
  3074. c["tgId"] = tgIdInt64
  3075. }
  3076. }
  3077. }
  3078. // Remove "flow": "xtls-rprx-direct"
  3079. if _, ok := c["flow"]; ok {
  3080. if c["flow"] == "xtls-rprx-direct" {
  3081. c["flow"] = ""
  3082. }
  3083. }
  3084. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  3085. hasVisionFlow = true
  3086. }
  3087. // Backfill created_at and updated_at
  3088. if _, ok := c["created_at"]; !ok {
  3089. c["created_at"] = time.Now().Unix() * 1000
  3090. }
  3091. c["updated_at"] = time.Now().Unix() * 1000
  3092. newClients = append(newClients, any(c))
  3093. }
  3094. settings["clients"] = newClients
  3095. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  3096. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  3097. // for any non-empty flow (including the UDP variant) or kept it after the
  3098. // flow was cleared from the client modal — clean those up here.
  3099. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  3100. delete(settings, "testseed")
  3101. }
  3102. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3103. if err != nil {
  3104. return
  3105. }
  3106. inbounds[inbound_index].Settings = string(modifiedSettings)
  3107. }
  3108. // Add client traffic row for all clients which has email
  3109. modelClients, err := s.GetClients(inbounds[inbound_index])
  3110. if err != nil {
  3111. return
  3112. }
  3113. for _, modelClient := range modelClients {
  3114. if len(modelClient.Email) > 0 {
  3115. var count int64
  3116. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  3117. if count == 0 {
  3118. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  3119. }
  3120. }
  3121. }
  3122. // Heal clients table for installs where the one-shot seeder
  3123. // skipped clients due to a tgId-string unmarshal error.
  3124. if syncErr := s.clientService.SyncInbound(tx, inbounds[inbound_index].Id, modelClients); syncErr != nil {
  3125. logger.Warning("MigrationRequirements sync clients failed:", syncErr)
  3126. }
  3127. }
  3128. tx.Save(inbounds)
  3129. // Remove orphaned traffics
  3130. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  3131. // Migrate old MultiDomain to External Proxy
  3132. var externalProxy []struct {
  3133. Id int
  3134. Port int
  3135. StreamSettings []byte
  3136. }
  3137. externalProxyQuery := `select id, port, stream_settings
  3138. from inbounds
  3139. WHERE protocol in ('vmess','vless','trojan')
  3140. AND json_extract(stream_settings, '$.security') = 'tls'
  3141. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`
  3142. if database.IsPostgres() {
  3143. externalProxyQuery = `select id, port, stream_settings
  3144. from inbounds
  3145. WHERE protocol in ('vmess','vless','trojan')
  3146. AND NULLIF(stream_settings, '')::jsonb #>> '{security}' = 'tls'
  3147. AND NULLIF(stream_settings, '')::jsonb #> '{tlsSettings,settings,domains}' IS NOT NULL`
  3148. }
  3149. err = tx.Raw(externalProxyQuery).Scan(&externalProxy).Error
  3150. if err != nil || len(externalProxy) == 0 {
  3151. return
  3152. }
  3153. for _, ep := range externalProxy {
  3154. var reverses any
  3155. var stream map[string]any
  3156. json.Unmarshal(ep.StreamSettings, &stream)
  3157. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  3158. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  3159. if domains, ok := settings["domains"].([]any); ok {
  3160. for _, domain := range domains {
  3161. if domainMap, ok := domain.(map[string]any); ok {
  3162. domainMap["forceTls"] = "same"
  3163. domainMap["port"] = ep.Port
  3164. domainMap["dest"] = domainMap["domain"].(string)
  3165. delete(domainMap, "domain")
  3166. }
  3167. }
  3168. }
  3169. reverses = settings["domains"]
  3170. delete(settings, "domains")
  3171. }
  3172. }
  3173. stream["externalProxy"] = reverses
  3174. newStream, _ := json.MarshalIndent(stream, " ", " ")
  3175. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  3176. }
  3177. err = tx.Raw(`UPDATE inbounds
  3178. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3179. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  3180. if err != nil {
  3181. return
  3182. }
  3183. }
  3184. func (s *InboundService) MigrateDB() {
  3185. s.MigrationRequirements()
  3186. s.MigrationRemoveOrphanedTraffics()
  3187. }
  3188. func (s *InboundService) GetOnlineClients() []string {
  3189. if p == nil {
  3190. return []string{}
  3191. }
  3192. return p.GetOnlineClients()
  3193. }
  3194. func (s *InboundService) GetOnlineClientsByNode() map[int][]string {
  3195. if p == nil {
  3196. return map[int][]string{}
  3197. }
  3198. return p.GetOnlineClientsByNode()
  3199. }
  3200. func (s *InboundService) GetActiveInboundsByNode() map[int][]string {
  3201. if p == nil {
  3202. return map[int][]string{}
  3203. }
  3204. return p.GetActiveInboundsByNode()
  3205. }
  3206. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  3207. if p != nil {
  3208. p.SetNodeOnlineClients(nodeID, emails)
  3209. }
  3210. }
  3211. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  3212. if p != nil {
  3213. p.ClearNodeOnlineClients(nodeID)
  3214. }
  3215. }
  3216. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  3217. db := database.GetDB()
  3218. var rows []xray.ClientTraffic
  3219. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  3220. if err != nil && err != gorm.ErrRecordNotFound {
  3221. return nil, err
  3222. }
  3223. result := make(map[string]int64, len(rows))
  3224. for _, r := range rows {
  3225. result[r.Email] = r.LastOnline
  3226. }
  3227. return result, nil
  3228. }
  3229. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  3230. // panel's own xray this poll into the local online/active sets, applying the
  3231. // grace window and pruning stale entries. Pass nil to only prune. See
  3232. // xray.Process for why the local sets are kept separate from the shared
  3233. // last_online column.
  3234. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  3235. if p != nil {
  3236. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  3237. }
  3238. }
  3239. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  3240. db := database.GetDB()
  3241. // Step 1: Get ClientTraffic records for emails in the input list.
  3242. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  3243. uniqEmails := uniqueNonEmptyStrings(emails)
  3244. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  3245. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3246. var page []xray.ClientTraffic
  3247. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  3248. return nil, nil, err
  3249. }
  3250. clients = append(clients, page...)
  3251. }
  3252. // Step 2: Sort clients by (Up + Down) descending
  3253. sort.Slice(clients, func(i, j int) bool {
  3254. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  3255. })
  3256. // Step 3: Extract sorted valid emails and track found ones
  3257. validEmails := make([]string, 0, len(clients))
  3258. found := make(map[string]bool)
  3259. for _, client := range clients {
  3260. validEmails = append(validEmails, client.Email)
  3261. found[client.Email] = true
  3262. }
  3263. // Step 4: Identify emails that were not found in the database
  3264. extraEmails := make([]string, 0)
  3265. for _, email := range emails {
  3266. if !found[email] {
  3267. extraEmails = append(extraEmails, email)
  3268. }
  3269. }
  3270. return validEmails, extraEmails, nil
  3271. }
  3272. type SubLinkProvider interface {
  3273. SubLinksForSubId(host, subId string) ([]string, error)
  3274. LinksForClient(host string, inbound *model.Inbound, email string) []string
  3275. }
  3276. var registeredSubLinkProvider SubLinkProvider
  3277. func RegisterSubLinkProvider(p SubLinkProvider) {
  3278. registeredSubLinkProvider = p
  3279. }
  3280. func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
  3281. if registeredSubLinkProvider == nil {
  3282. return nil, common.NewError("sub link provider not registered")
  3283. }
  3284. return registeredSubLinkProvider.SubLinksForSubId(host, subId)
  3285. }
  3286. func (s *InboundService) GetAllClientLinks(host string, email string) ([]string, error) {
  3287. if email == "" {
  3288. return nil, common.NewError("client email is required")
  3289. }
  3290. if registeredSubLinkProvider == nil {
  3291. return nil, common.NewError("sub link provider not registered")
  3292. }
  3293. rec, err := s.clientService.GetRecordByEmail(nil, email)
  3294. if err != nil {
  3295. return nil, err
  3296. }
  3297. inboundIds, err := s.clientService.GetInboundIdsForRecord(rec.Id)
  3298. if err != nil {
  3299. return nil, err
  3300. }
  3301. var links []string
  3302. for _, ibId := range inboundIds {
  3303. inbound, getErr := s.GetInbound(ibId)
  3304. if getErr != nil {
  3305. return nil, getErr
  3306. }
  3307. links = append(links, registeredSubLinkProvider.LinksForClient(host, inbound, email)...)
  3308. }
  3309. return links, nil
  3310. }