inbound.go 121 KB

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