1
0

inbound.go 113 KB

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